不多说,直接上代码,对称加密只有一个密钥。用他来加密,也用它来解密。
package com.example.shirotest.utils;
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
public class AESKeyPairUtils {
public static void main(String[] args) {
String content = "www.baidu.com";
String password = "123";
System.out.println("加密之前:" + content);
// 加密
byte[] encrypt = AESKeyPairUtils.encrypt(content, password);
System.out.println("加密后的内容:" + new String(encrypt));
// 解密
String msg = AESKeyPairUtils.decrypt(encrypt, password);
System.out.println("解密后的内容:" + new String(msg));
}
/**
* AES加密字符串
* @param content 需要被加密的字符串
* @param password 加密需要的密码
* @return 密文字符串
*/
public static byte[] encrypt(String content,String password){
try {
SecretKeySpec secretKeySpec = getSecretKeySpec(password);
Cipher cipher = Cipher.getInstance("AES");//创建密码器
cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);
byte[] bytes = cipher.doFinal(content.getBytes("UTF-8"));
return bytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(byte[] content,String password){
String msg = "";
try {
SecretKeySpec secretKeySpec = getSecretKeySpec(password);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE,secretKeySpec);
byte[] bytes = cipher.doFinal(content);
msg = new String(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return msg;
}
/**
* 获取cipher
* @param password 密码
* @return
*/
public static SecretKeySpec getSecretKeySpec(String password){
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128,new SecureRandom(password.getBytes()));
SecretKey secretKey = keyGenerator.generateKey();
System.out.println("secretkey:"+ Base64.encodeBase64String(secretKey.getEncoded()));
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(),"AES");
return secretKeySpec;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}