node.js - Nodejs Crypto 到 Swift commonCrypto
问题描述
想要将以下 NodeCrypto
示例转换为等效的 Swift commonCrypto
:
function encrypt(key, text){
let iv = crypto.randomBytes(IV_LENGTH);
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
let final_encrypted = iv.toString('hex') + ':' + encrypted.toString('hex');
console.log(final_encrypted); // <-- final encrypted string
}
function decrypt(key, enc_text){
let textParts = enc_text.split(':');
let iv = Buffer.from(textParts.shift(), 'hex');
let encryptedText = Buffer.from(textParts.join(':'), 'hex');
let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
let decrypted = decipher.update(encryptedText);
let final = decipher.final();
decrypted = Buffer.concat([decrypted, final]);
console.log(decrypted.toString()); // <-- final decrypted string
}
Swift 实现代码贴在这里:Swift AES encryption using CommonCrypto
解决方案
推荐阅读
- c - 为什么在 char** cast 后出现分段错误?
- python - 在 Docker 中使用 Celery 的 Flask 应用程序中的应用程序上下文错误
- c - 没有循环的函数是否可并行化?
- java - 永久编辑类路径中的 txt 文件
- python - 如何从 txt 文件中绘制字符串日期时间
- dll - 在 .NetCore 2.1 (Windows) 中加载本机库
- reactjs - 为什么在我的测试中我的子组件上的道具没有更新?
- c# - 如何模拟 Elasticsearch NEST 的 IGetMappingResponse 进行单元测试
- c++ - 包装非类型模板常量以避免混合相同类型的参数
- python - 使用 Cython 公开 C 结构时的内存效率