求助 :AES/CBC/PKCS5Padding 加密要和java相同,请问要怎么加密,我加密出来值不同
已解决
java代码
public static String encryptAES(String content, String key)
throws InvalidKeyException, NoSuchAlgorithmException,
NoSuchPaddingException, UnsupportedEncodingException,
InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] byteContent = content.getBytes("UTF-8");
String IV_STRING = key.substring(0, 16);
// 注意,为了能与 iOS 统一
// 这里的 key 不可以使用 KeyGenerator、SecureRandom、SecretKey 生成
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
// 指定加密的算法、工作模式和填充方式
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,ivParameterSpec);
byte[] encryptedBytes = cipher.doFinal(byteContent);
String mm = new String(Hex.encodeHex(encryptedBytes));
return mm.toUpperCase();
}let sKey: string = "qnfk0xqkmm6xrwc6mk61tmc4xxw9vm00"
let iv: string = "qnfk0xqkmm6xrwc6"
static async aesEncrypt(text: string, key: string, iv: string): Promise<string> {
try {
//转换key
let symKeyBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(key, 'utf-8').buffer) };
let aesGenerator = cryptoFramework.createSymKeyGenerator("AES128");
let symKey = await aesGenerator.convertKey(symKeyBlob);
// 初始化加解密操作环境
let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE;
//创建加密器
let cipher = cryptoFramework.createCipher("AES128|CBC|PKCS5");
let ivBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(iv, 'utf-8').buffer) };
let ivParamsSpec: cryptoFramework.IvParamsSpec = {
algName: "IvParamsSpec",
iv: ivBlob
};
//初始化加密
await cipher.init(mode, symKey, ivParamsSpec);
//开始加密
let updateOutput = await cipher.doFinal({ data: new Uint8Array(buffer.from(text, 'utf-8').buffer) });
console.log("Test", "encrypt result:" + updateOutput.data.toString())
//转换字符串
// let result =
let result = uint8ArrayToHexStr(updateOutput.data)
let a = util.TextDecoder.create('utf-8').decodeWithStream(updateOutput.data).trim()
LogUtil.debug("测试1", result)
LogUtil.debug("测试2", a)
return result
} catch (error) {
console.log("Test", "encrypt error result:" + JSON.stringify(error))
return "error"
}
}
8
浏览259 发布于2024-12-27 02:33北京
全部评论
最多点赞
最新发布
最早发布
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
- 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
- 如您发布的内容为转载内容,请注明内容来源。
我要提问题
了解社区公约,与您携手共创和谐专业的开发者社区。





































苏公安网备 32011402010933号