使用RSA密钥对加密解密数据
作者: 郭政鸿 /1/6
前言: 前几天看了非对称加密, 那非对称加密处理常见的https中的应用, 平时我们可以用来做什么呢?
1. 生成RSA密钥对
使用openssl生成工具
opensslgenrsa-outrsa_test_private2048#生成私钥
-out 指定输出路径2048用于指定秘钥长度
opensslrsa-inres_test_private-pubout-outres_test_public#通过私钥生成公钥
-in 指定输入的私钥路径-pubout 输出公钥-out 指定公钥输出路径
然后执行完上诉命令我们可以看到当前文件夹下生成了以下两个密钥对文件
2. 编写程序使用秘钥对将文件进行加密解密
这里使用的是nodeJS作为编程语言
新建一个xx.txt的文件, 内容如下
进入代码部分
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')));constcrypto=require('crypto');
3. 总结
很多时候小小的知识点也能够玩出大大的花样, 比如学习了非对称加密可以考虑做一个文件加密工具呀❤️