AES加密,就是对称加密。分享牛系列,分享牛专栏,分享牛。客户端可以保存一个密钥,调用加密的值传入需要加密的值,然后程序根据密钥算出一个新的值,当然了解密也需要,对应的密钥才可以解密。
写一个程序如下:
/**
*
*/
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* @author qq 1515308
*/
public class AESEncrypter {
public static void main(String[] args) {
String encryptAsString = new AESEncrypter().encrypt("qq:1515308");
System.out.println(encryptAsString);
String decryptAsString = new AESEncrypter().decryptAsString(encryptAsString);
System.out.println(decryptAsString);
}
private static String aesKeyStr = "NGQxNmUwMjM4M2Y0MTI2MTM3NDI0Y2MxMjA1N2IyNDM=";
private SecretKey aesKey;
private AESEncrypter() {
aesKey = loadAesKey();
}
private AESEncrypter(String aes) {
aesKey = loadAesKey(aes);
}
private static AESEncrypter INSTANCE;
private static Map<String, AESEncrypter> INSTANCES = new HashMap<>();
public static AESEncrypter getInstance() {
if (INSTANCE == null) {
synchronized (aesKeyStr) {
if (INSTANCE == null) {
INSTANCE = new AESEncrypter();
}
}
}
return INSTANCE;
}
public static AESEncrypter getInstance(String aes) {
if (INSTANCES.get(aes) == null) {
synchronized (aesKeyStr) {
if (INSTANCES.get(aes) == null) {
INSTANCES.put(aes, new AESEncrypter(aes));
}
}
}
return INSTANCES.get(aes);
}
public String encrypt(String msg) {
try {
Cipher ecipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, aesKey);
return Encrypter.toHexString(ecipher.doFinal(msg.getBytes()));
} catch (Exception e) {
String errMsg = "decrypt error, data:" + msg;
throw new EncrypterException(errMsg, e);
}
}
public byte[] decrypt(String msg) {
try {
Cipher dcipher = Cipher.getInstance("AES");
dcipher.init(Cipher.DECRYPT_MODE, aesKey);
return dcipher.doFinal(Encrypter.toBytes(msg));
} catch (Exception e) {
String errMsg = "decrypt error, data:" + msg;
throw new EncrypterException(errMsg, e);
}
}
public String decryptAsString(String msg) {
return new String(this.decrypt(msg));
}
private static SecretKey loadAesKey() {
String buffer = new String(Base64.decodeBase64(aesKeyStr));
byte[] keyStr = Encrypter.toBytes(buffer);
SecretKeySpec aesKey = new SecretKeySpec(keyStr, "AES");
return aesKey;
}
private static SecretKey loadAesKey(String aesKeyStr) {
String buffer = new String(Base64.decodeBase64(aesKeyStr));
byte[] keyStr = Encrypter.toBytes(buffer);
SecretKeySpec aesKey = new SecretKeySpec(keyStr, "AES");
return aesKey;
}
}
程序的输出如下:
ac8f63257d3d0e85844b4d74269bd153
qq:1515308
加密解密是OK的。
分享牛系列,分享牛专栏,分享牛。 分享牛原创(尊重原创 转载对的时候第一行请注明,转载出处来自分享牛http://blog.csdn.net/qq_30739519) Java架构师交流群 523988350 qq:1515308