提问人:Mombre Enpellido 提问时间:11/15/2023 最后编辑:Mombre Enpellido 更新时间:11/16/2023 访问量:85
为什么我的解密函数不适用于 CryptoJS?
Why is my decryption function not working with CryptoJS?
问:
我对加密很陌生,我正在尝试将 CryptoJS 与 AES 用于 ReactNative 项目。要求是使用加密数据从端点获取数据,但是当我尝试解密时,我的代码返回一个空字符串。
在PHP中,端点数据由以下函数加密:
$KEY;
$IV_LENGTH = 16;
这里的键是静态的,已经由 getKey() 函数生成。
public function encrypt($plain_text){
global $KEY;
$iv = $this->generateIV();
$encrypted = openssl_encrypt($plain_text, 'aes-256-cbc', hex2bin($KEY), OPENSSL_RAW_DATA, $iv);
return base64_encode($iv.$encrypted);
}
public function decrypt($encrypted){
global $IV_LENGTH;
global $KEY;
$data = base64_decode($encrypted);
$iv = substr($data, 0, $IV_LENGTH);
$encryptedData = substr($data, $IV_LENGTH);
return openssl_decrypt($encryptedData, 'aes-256-cbc', hex2bin($KEY), OPENSSL_RAW_DATA, $iv);
}
public function getKey(){
$salt = random_bytes(256);
$iterations = 999;
$passphrase = 'orpheus';
return hash_pbkdf2("sha512", $passphrase, $salt, $iterations, 64);
}
public function generateIV(){
global $IV_LENGTH;
return openssl_random_pseudo_bytes($IV_LENGTH);
}
JS中测试的加密函数(这里的KEY和PHP代码中的KEY是一样的):
import { Buffer } from 'buffer';
import {KEY} from '../constants/Constants'
import CryptoJS from 'react-native-crypto-js';
const CryptoJSAesEncrypt = (text) => {
let iv = CryptoJS.lib.WordArray.random(16);
let encryptedData = CryptoJS.AES.encrypt(text, KEY, {iv: iv});
let encrypt = iv+encryptedData;
return (Buffer.from(encrypt).toString('base64'));
}
CryptoJSAesEncrypt,输入 textoo! 返回例如: NGFjMjdkODMxNTNlMGYwZmM1ZDYyNTc1MTcwMjBkNDNVMkZzZEdWa1gxOWlUcXA4NXphaEx1VjdlbncwVEVxcm9vUENrSXlWUWZvPQ==
const CryptoJSAesDecrypt = (encrypted) => {
let data = Buffer.from(encrypted, 'base64').toString('ascii');
let iv = data.substring(0,16);
let encryptedData = data.substring(16);
let decrypted = CryptoJS.AES.decrypt(encryptedData, KEY, {iv: iv});
return decrypted.toString(CryptoJS.enc.Utf8)
}
编辑:
我使用 js 函数中包含的十六进制解码进行了测试
const CryptoJSAesEncrypt = (text) => {
let iv = CryptoJS.lib.WordArray.random(16);
let encryptedData = CryptoJS.AES.encrypt(text, CryptoJS.enc.Hex.parse(KEY).toString(), {iv: iv});
let encrypt = iv+encryptedData;
return (Buffer.from(encrypt).toString('base64'));
}
const CryptoJSAesDecrypt = (encrypted) => {
let data = Buffer.from(encrypted, 'base64').toString('ascii');
let iv = data.substring(0,16);
let encryptedData = data.substring(16);
let decrypted = CryptoJS.AES.decrypt(encryptedData, CryptoJS.enc.Hex.parse(KEY).toString(), {iv: iv});
return decrypted.toString(CryptoJS.enc.Utf8);
}
测试:
const text = 'YES!';
const a = CryptoJSAesEncrypt(text);
console.log('Text: ',text); //Text: YES!
console.log('Encryption: ',a); //Encryption: MjAwYjdiMmNhODkwNDBiZDYxYTY2MTczNThiNjIwZDRVMkZzZEdWa1gxK0FwQ0F5d3VtMnc1ait4NGVVMkFVOFZ3OFczajZMcjJZPQ==
console.log('Decryption: ', CryptoJSAesDecrypt(a)); //Decryption:
解密不返回任何内容。
答: 暂无答案
评论
getKey()
echo $c->getKey();
$KEY = 'random string';
KEY = 'random string';
hex2bin()
CryptoJS.enc.Hex.parse()