700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 加密解密_使用RSA密钥对加密解密数据

加密解密_使用RSA密钥对加密解密数据

时间:2022-04-12 04:36:03

相关推荐

加密解密_使用RSA密钥对加密解密数据

使用RSA密钥对加密解密数据

作者: 郭政鸿 /1/6

前言: 前几天看了非对称加密, 那非对称加密处理常见的https中的应用, 平时我们可以用来做什么呢?

1. 生成RSA密钥对

使用openssl生成工具

#生成私钥

opensslgenrsa-outrsa_test_private2048

-out 指定输出路径2048用于指定秘钥长度

#通过私钥生成公钥

opensslrsa-inres_test_private-pubout-outres_test_public

-in 指定输入的私钥路径-pubout 输出公钥-out 指定公钥输出路径

然后执行完上诉命令我们可以看到当前文件夹下生成了以下两个密钥对文件

image-0104133918013

2. 编写程序使用秘钥对将文件进行加密解密

这里使用的是nodeJS作为编程语言

新建一个xx.txt的文件, 内容如下

image-0104134307049

进入代码部分

constcrypto=require('crypto');

constfs=require('fs');

constpath=require('path');

constencode=(inputValue,publicKeyPath)=>newPromise((resolve,reject)=>{

//获取公钥真实硬盘地址

constkeyPath=path.resolve(publicKeyPath);

//将需要加密的数据转成buffer数据

constinputBuffer=Buffer.from(inputValue,"utf-8");

fs.readFile(keyPath,(error,key)=>{

if(error){

//读取公钥内容出错处理

reject(error);

}

//利用crypto的publicEncrypt函数将明文数据加密

resolve(crypto.publicEncrypt(key,inputBuffer).toString('base64'));

});

});

constdecode=(inputValue,privateKeyPath)=>newPromise((resolve,reject)=>{

fs.readFile(path.resolve(privateKeyPath),(error,key)=>{

if(error)reject(error);

//利用privateDecrypt进行解密

resolve(crypto.privateDecrypt(key,Buffer.from(inputValue,'base64')));

})

});

//测试demo

constinputM=fs.readFileSync('./xx.txt');

encode(inputM,'./rsa_test_public').then(res=>fs.writeFileSync('./S',res));

constinputS=fs.readFileSync('./S');

decode(inputS.toString('utf-8'),'./rsa_test_private').then(res=>console.log(res.toString('utf-8')));

3. 总结

很多时候小小的知识点也能够玩出大大的花样, 比如学习了非对称加密可以考虑做一个文件加密工具呀❤️

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。