Java中加密解密常用函数
发布时间:2023-07-06 10:12:26
在Java中,加密和解密是常见的操作,可以使用不同的加密算法和Java提供的加密类库来实现。下面介绍几种常用的加密解密函数。
1. Base64加密解密:Base64是一种将二进制数据编码为可打印ASCII字符的方法。Java中可以使用Base64类来进行加密和解密操作。示例代码如下:
import java.util.Base64;
public class Base64Demo {
public static void main(String[] args) {
String text = "Hello, World!";
// 加密
String encodedText = Base64.getEncoder().encodeToString(text.getBytes());
System.out.println("Encoded text: " + encodedText);
// 解密
byte[] decodedBytes = Base64.getDecoder().decode(encodedText);
String decodedText = new String(decodedBytes);
System.out.println("Decoded text: " + decodedText);
}
}
2. 对称加密解密:对称加密是指使用同一个密钥进行加密和解密的方式。Java中提供了多种对称加密算法,如AES、DES、DESede等。示例代码如下:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class SymmetricEncryptionDemo {
public static void main(String[] args) throws Exception {
String algorithm = "AES";
String text = "Hello, World!";
// 生成密钥
KeyGenerator keyGen = KeyGenerator.getInstance(algorithm);
SecretKey secretKey = keyGen.generateKey();
// 加密
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(text.getBytes());
System.out.println("Encrypted text: " + new String(encryptedBytes));
// 解密
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
System.out.println("Decrypted text: " + new String(decryptedBytes));
}
}
3. 非对称加密解密:非对称加密是指使用不同的密钥进行加密和解密的方式,其中一个密钥用于加密,另一个密钥用于解密。Java中提供了多种非对称加密算法,如RSA、DSA等。示例代码如下:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class AsymmetricEncryptionDemo {
public static void main(String[] args) throws Exception {
String algorithm = "RSA";
String text = "Hello, World!";
// 生成密钥对
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 加密
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(text.getBytes());
System.out.println("Encrypted text: " + new String(encryptedBytes));
// 解密
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
System.out.println("Decrypted text: " + new String(decryptedBytes));
}
}
这些是Java中常用的加密解密函数,可以根据具体需求选择合适的加密算法和实现方式。
