android 和 Koa2 服务器 在 AES加密上的 通用算法
**首先是koa2上**使用的是crypto-jsconst CryptoJS = require("crypto-js");function AESEncrypt(value,key,slot) {if(isEmpty(key)){key = AESKey}if(!isEmpty(slot)){key = key + slot}key = CryptoJS.enc.Utf8.parse(key)
·
**
首先是koa2上
**
使用的是crypto-js
const CryptoJS = require("crypto-js");
function AESEncrypt(value,key,slot) {
if(isEmpty(key)){
key = AESKey
}
if(!isEmpty(slot)){
key = key + slot
}
key = CryptoJS.enc.Utf8.parse(key)
let iv = key
return CryptoJS.AES.encrypt(value, key,{
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}).toString();
}
function AESDecrypt(value,key,slot) {
if(isEmpty(key)){
key = AESKey
}
if(!isEmpty(slot)){
key = key + slot
}
key = CryptoJS.enc.Utf8.parse(key)
let iv = key
return CryptoJS.AES.decrypt(value, key,{
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}).toString(CryptoJS.enc.Utf8);
}
然后android上
只写了 解密的 加密的
public static String decryptAES(String data, String pass) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keyspec = new SecretKeySpec(pass.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(pass.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] result=cipher.doFinal(Base64.decode(data.getBytes(),Base64.DEFAULT));
return new String(result, "utf-8");
}
private static String encryptAES(String data,String pass) throws Exception {
byte[] raw = pass.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(pass.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.encodeToString(encrypted,Base64.DEFAULT);
}
以上方法均已验证,请放心使用
更多推荐
已为社区贡献4条内容
所有评论(0)