Skip to content

Commit b9072c5

Browse files
committed
Version 1.1.0
1 parent d8a4222 commit b9072c5

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

myRSA.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
var crypto=require('crypto'), fs=require('fs')
2+
var padding=crypto.constants.RSA_PKCS1_OAEP_PADDING
3+
var rootDir=__dirname+(process.platform=="win32"?"\\":"/")
4+
const atob=(text)=>Buffer.from(text,'base64').toString('binary')
5+
const btoa=(text)=>Buffer.from(text,'binary').toString('base64')
6+
let oaepHash="sha256"
7+
8+
function str2ab(str) {
9+
const buf = new ArrayBuffer(str.length);
10+
const bufView = new Uint8Array(buf);
11+
for (let i = 0, strLen = str.length; i < strLen; i++) {
12+
bufView[i] = str.charCodeAt(i);
13+
}
14+
return buf;
15+
}
16+
function ab2str(buf,getOwnPropertyNames) {
17+
var buff=new Uint8Array(buf)
18+
return Object.getOwnPropertyNames(buff)
19+
.map(i=>String.fromCharCode(buff[i])).join('')
20+
}
21+
22+
function make_RSA_keys(key_name){
23+
let publicKeyEncoding={type:'spki',format:'pem'}
24+
let privateKeyEncoding={type:'pkcs8',format:'pem'}
25+
let {privateKey,publicKey}=crypto.generateKeyPairSync('rsa',
26+
{modulusLength:4096,publicKeyEncoding,privateKeyEncoding}
27+
)
28+
fs.writeFileSync(rootDir+key_name+'-prv.pem',privateKey)
29+
fs.writeFileSync(rootDir+key_name+'-pub.pem',publicKey)
30+
return [privateKey, publicKey]
31+
}
32+
33+
function get_RSA_keys(key_name){
34+
return [
35+
fs.readFileSync(rootDir+key_name+'-prv.pem'),
36+
fs.readFileSync(rootDir+key_name+'-pub.pem')
37+
]
38+
}
39+
40+
function rsa_decrypt(key,text){
41+
if(typeof key=="string"){key=Buffer.from(key)}
42+
return JSON.parse(text).map(txt=>{
43+
let data=str2ab(atob(txt))
44+
let result=crypto.privateDecrypt({key,padding,oaepHash},data)
45+
return ab2str(result)
46+
}).join('')
47+
}
48+
49+
function rsa_encrypt(key,text){
50+
var list=[], n=446
51+
for(let i in text){
52+
let index=(i-(i%n))/n
53+
list[index]=list[index]!=undefined? list[index]+text[i]: text[i]
54+
}
55+
if(typeof key=="string"){key=Buffer.from(key)}
56+
return JSON.stringify( list.map(txt=>{
57+
let data=str2ab(txt)
58+
let result=crypto.publicEncrypt({key,padding,oaepHash},data)
59+
return btoa(ab2str(result))
60+
}) )
61+
}
62+
63+
module.exports={rsa_encrypt,rsa_decrypt,get_RSA_keys,make_RSA_keys,ab2str,str2ab}

0 commit comments

Comments
 (0)