1. 程式人生 > >java實現加密解密

java實現加密解密

1.加密
public static String encryt(String str) {
// 根據金鑰,對Cipher物件進行初始化,ENCRYPT_MODE表示加密模式
try {
Cipher c = Cipher.getInstance(“AES”);
c.init(Cipher.ENCRYPT_MODE, KEY_SPEC);
byte[] src = str.getBytes();
// 加密,結果儲存進cipherByte
byte[] cipherByte = c.doFinal(src);
return Base64.encodeBase64String(cipherByte);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
2.解密
public static String decrypt(String deCodeStr) {
// 根據金鑰,對Cipher物件進行初始化,DECRYPT_MODE表示解密模式
try {
if (null == deCodeStr){
return null;
}
byte[] buff = Base64.decodeBase64(deCodeStr);
Cipher c;
c = Cipher.getInstance(“AES”);
c.init(Cipher.DECRYPT_MODE, KEY_SPEC);
byte[] cipherByte = c.doFinal(buff);
return new String(cipherByte);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}