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;
}

猜你喜欢

转载自blog.csdn.net/weixin_42851135/article/details/83023690