菜鸡源码,专注精品下载!
当前位置:首页 > 建站教程 > 建站知识

JavaScript中的加密解密方法

发布时间:2024-01-05  栏目:建站知识   浏览:   分类:js教程

Javascript加密解密方法主要有以下几种:1. 对称加密算法,如AES、DES等;2. 非对称加密算法,如RSA、ECC等;3. 哈希算法,如MD5、SHA-1等。其中,对称加密算法加解密速度快,但密钥管理复杂;非对称加密算法安全性高,但加解密速度慢;哈希算法主要用于数据完整性校验,不可逆。在实际应用中,可以根据需求选择合适的加密解密方法。同时,为了提高安全性,通常会结合使用多种加密技术,如先使用非对称加密算法进行密钥交换,再使用对称加密算法进行数据传输。

安装crypto-js

npminstallcrypto-js--save-devnpminstallmd5--save-dev

一些常见的built-in 函数加密

unescape

unescape() 函数可对通过 escape() 编码的字符串进行解码。

lete=escape("始識")console.log(e)//%u59CB%u8B58letu=unescape(e)console.log(u)//始識

URL编码与解码

lete=encodeURI("https://始識的博客")console.log(e)//https://%E5%A7%8B%E8%AD%98%E7%9A%84%E5%8D%9A%E5%AE%A2letu=decodeURI(e)console.log(u)//https://始識的博客fromCharCode

将 Unicode 编码转为一个字符

varn=String.fromCharCode(65);//A[101,118,97,108].map(item=>{returnString.fromCharCode(item)})['e','v','a','l']Base64btoaatob

node实现方式

//Base64encodedstringconststr='https://www.cnblogs.com/zichliang/p/17265960.html';//b编码constbuffBase64=Buffer.from(str,'utf-8').toString('base64');console.log(buffBase64);//解码constbuffStr=Buffer.from(buffBase64,'base64').toString("utf-8");//printnormalstringconsole.log(buffStr);

引用 crypto-js 加密模块

varCryptoJS=require('crypto-js')functionbase64Encode(){varsrcs=CryptoJS.enc.Utf8.parse(text);varencodeData=CryptoJS.enc.Base64.stringify(srcs);returnencodeData}functionbase64Decode(){varsrcs=CryptoJS.enc.Base64.parse(encodeData);vardecodeData=srcs.toString(CryptoJS.enc.Utf8);returndecodeData}vartext="https://www.cnblogs.com/zichliang/p/17265960.html"varencodeData=base64Encode()vardecodeData=base64Decode()console.log("Base64编码:",encodeData)console.log("Base64解码:",decodeData)

MD5

//引用crypto-js加密模块varCryptoJS=require('crypto-js')functionMD5Test(){vartext="https://www.cnblogs.com/zichliang"returnCryptoJS.MD5(text).toString()}console.log(MD5Test())//50177badb579733de56b628ae57fb972

PBKDF2

//引用crypto-js加密模块varCryptoJS=require('crypto-js')functionpbkdf2Encrypt(){vartext="https://www.cnblogs.com/zichliang"varsalt="1234567"//key长度128,10次重复运算varencryptedData=CryptoJS.PBKDF2(text,salt,{keySize:128/32,iterations:10});returnencryptedData.toString()}console.log(pbkdf2Encrypt())//bcda4be78de797d8f5067331b1a70d40

SHA1

//引用crypto-js加密模块varCryptoJS=require('crypto-js')functionSHA1Encrypt(){vartext="https://www.cnblogs.com/zichliang"returnCryptoJS.SHA1(text).toString();}console.log(SHA1Encrypt())//ca481c13d5af7135b69d11ffb0a443a635fbc307

SHA256

//引用crypto-js加密模块varCryptoJS=require('crypto-js')functionSHA256Encrypt(){vartext="https://www.cnblogs.com/zichliang"returnCryptoJS.SHA256(text).toString();}console.log(SHA256Encrypt())//0b16c8942abbf124f6fef65ae145314dd72ed495ede2b95fe0bde722c0e26478

或者使用原生JS源代码文件生成

不要问为什么只有这个有js源码,因为这个加密我刚好用到了。

functionsha256(s){constchrsz=8consthexcase=0functionsafe_add(x,y){constlsw=(x&0xFFFF)+(y&0xFFFF)constmsw=(x>>16)+(y>>16)+(lsw>>16)return(msw<<16)|(lsw&0xFFFF)}functionS(X,n){return(X>>>n)|(X<<(32-n))}functionR(X,n){return(X>>>n)}functionCh(x,y,z){return((x&y)^((~x)&z))}functionMaj(x,y,z){return((x&y)^(x&z)^(y&z))}functionSigma0256(x){return(S(x,2)^S(x,13)^S(x,22))}functionSigma1256(x){return(S(x,6)^S(x,11)^S(x,25))}functionGamma0256(x){return(S(x,7)^S(x,18)^R(x,3))}functionGamma1256(x){return(S(x,17)^S(x,19)^R(x,10))}functioncore_sha256(m,l){constK=[0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2]constHASH=[0x6A09E667,0xBB67AE85,0x3C6EF372,0xA54FF53A,0x510E527F,0x9B05688C,0x1F83D9AB,0x5BE0CD19]constW=newArray(64)leta,b,c,d,e,f,g,h,i,jletT1,T2m[l>>5]|=0x80<<(24-l%32)m[((l+64>>9)<<4)+15]=lfor(i=0;i<m.length;i+=16){a=HASH[0]b=HASH[1]c=HASH[2]d=HASH[3]e=HASH[4]f=HASH[5]g=HASH[6]h=HASH[7]for(j=0;j<64;j++){if(j<16){W[j]=m[j+i]}else{W[j]=safe_add(safe_add(safe_add(Gamma1256(W[j-2]),W[j-7]),Gamma0256(W[j-15])),W[j-16])}T1=safe_add(safe_add(safe_add(safe_add(h,Sigma1256(e)),Ch(e,f,g)),K[j]),W[j])T2=safe_add(Sigma0256(a),Maj(a,b,c))h=gg=ff=ee=safe_add(d,T1)d=cc=bb=aa=safe_add(T1,T2)}HASH[0]=safe_add(a,HASH[0])HASH[1]=safe_add(b,HASH[1])HASH[2]=safe_add(c,HASH[2])HASH[3]=safe_add(d,HASH[3])HASH[4]=safe_add(e,HASH[4])HASH[5]=safe_add(f,HASH[5])HASH[6]=safe_add(g,HASH[6])HASH[7]=safe_add(h,HASH[7])}returnHASH}functionstr2binb(str){constbin=[]constmask=(1<<chrsz)-1for(leti=0;i<str.length*chrsz;i+=chrsz){bin[i>>5]|=(str.charCodeAt(i/chrsz)&mask)<<(24-i%32)}returnbin}functionUtf8Encode(string){string=string.replace(/\r\n/g,'\n')letutfText=''for(letn=0;n<string.length;n++){constc=string.charCodeAt(n)if(c<128){utfText+=String.fromCharCode(c)}elseif((c>127)&&(c<2048)){utfText+=String.fromCharCode((c>>6)|192)utfText+=String.fromCharCode((c&63)|128)}else{utfText+=String.fromCharCode((c>>12)|224)utfText+=String.fromCharCode(((c>>6)&63)|128)utfText+=String.fromCharCode((c&63)|128)}}returnutfText}functionbinb2hex(binarray){consthex_tab=hexcase?'0123456789ABCDEF':'0123456789abcdef'letstr=''for(leti=0;i<binarray.length*4;i++){str+=hex_tab.charAt((binarray[i>>2]>>((3-i%4)*8+4))&0xF)+hex_tab.charAt((binarray[i>>2]>>((3-i%4)*8))&0xF)}returnstr}s=Utf8Encode(s)returnbinb2hex(core_sha256(str2binb(s),s.length*chrsz))}

使用

console.log(sha256('https://www.cnblogs.com/zichliang'))//0b16c8942abbf124f6fef65ae145314dd72ed495ede2b95fe0bde722c0e26478

HMAC-SHA256

//引用crypto-js加密模块varCryptoJS=require('crypto-js')functionHmacSHA256Encrypt(){varhash=CryptoJS.HmacSHA256("这是加密信息","这是秘钥");varhashInBase64=CryptoJS.enc.Base64.stringify(hash);returnhashInBase64;}console.log(HmacSHA256Encrypt())//qMlLziV3yzjVb3VgwWhbSTYLsCZXTB1jftypu04SUDM=

js源代码

//Toensurecross-browsersupportevenwithoutaproperSubtleCrypto//impelmentation(orwithoutaccesstotheimpelmentation,asisthecasewith//ChromeloadedoverHTTPinsteadofHTTPS),thislibrarycancreateSHA-256//HMACsignaturesusingnothingbutrawJavaScript/*eslint-disableno-magic-numbers,id-length,no-param-reassign,new-cap*///Bygivinginternalfunctionsnamesthatwecanmangle,futurecallsto//themarereducedtoasinglebyte(minorspacesavingsinminifiedfile)varuint8Array=Uint8Array;varuint32Array=Uint32Array;varpow=Math.pow;//Willbeinitializedbelow//UsingaUint32Arrayinsteadofasimplearraymakestheminifiedcode//abitbigger(weloseour`unshift()`hack),butcomeswithhuge//performancegainsvarDEFAULT_STATE=newuint32Array(8);varROUND_CONSTANTS=[];//Reusableobjectforexpandedmessage//UsingaUint32Arrayinsteadofasimplearraymakestheminifiedcode//7byteslarger,butcomeswithhugeperformancegainsvarM=newuint32Array(64);//Afterminificationthecodetocomputethedefaultstateandround//constantsissmallerthantheoutput.Moreimportantly,thisservesasa//goodeducationalaideforanyonewonderingwherethemagicnumberscome//from.NomagicnumbersFTW!functiongetFractionalBits(n){return((n-(n|0))*pow(2,32))|0;}varn=2,nPrime=0;while(nPrime<64){//isPrime()wasin-linedfromitsoriginalfunctionformtosave//afewbytesvarisPrime=true;//Math.sqrt()wasreplacedwithpow(n,1/2)tosaveafewbytes//varsqrtN=pow(n,1/2);//Sotechnicallytodetermineifanumberisprimeyouonlyneedto//checknumbersuptothesquareroot.Howeverthisfunctiononlyruns//onceandwe'reonlycomputingthefirst64primes(upto311),soon//anymodernCPUthiswholefunctionrunsinacouplemilliseconds.//Bygoington/2insteadofsqrt(n)wenet8bytesavingsandno//scalingperformancecostfor(varfactor=2;factor<=n/2;factor++){if(n%factor===0){isPrime=false;}}if(isPrime){if(nPrime<8){DEFAULT_STATE[nPrime]=getFractionalBits(pow(n,1/2));}ROUND_CONSTANTS[nPrime]=getFractionalBits(pow(n,1/3));nPrime++;}n++;}//Forcross-platformsupportweneedtoensurethatall32-bitwordsare//inthesameendianness.AUTF-8TextEncoderwillreturnBigEndiandata,//souponreadingorwritingtoourArrayBufferwe'llonlyswapthebytes//ifoursystemisLittleEndian(whichisabout99%ofCPUs)varLittleEndian=!!newuint8Array(newuint32Array([1]).buffer)[0];functionconvertEndian(word){if(LittleEndian){return(//byte1->byte4(word>>>24)|//byte2->byte3(((word>>>16)&0xff)<<8)|//byte3->byte2((word&0xff00)<<8)|//byte4->byte1(word<<24));}else{returnword;}}functionrightRotate(word,bits){return(word>>>bits)|(word<<(32-bits));}functionsha256(data){//CopydefaultstatevarSTATE=DEFAULT_STATE.slice();//Cachingthisreducesoccurrencesof".length"inminifiedJavaScript//3morebytesavings!:Dvarlegth=data.length;//PaddatavarbitLength=legth*8;varnewBitLength=(512-((bitLength+64)%512)-1)+bitLength+65;//"bytes"and"words"arestoredBigEndianvarbytes=newuint8Array(newBitLength/8);varwords=newuint32Array(bytes.buffer);bytes.set(data,0);//Appenda1bytes[legth]=0b10000000;//StorelengthinBigEndianwords[words.length-1]=convertEndian(bitLength);//Loopiterator(avoidtwoinstancesof"var")--saves2bytesvarround;//Processblocks(512bits/64bytes/16wordsatatime)for(varblock=0;block<newBitLength/32;block+=16){varworkingState=STATE.slice();//Roundsfor(round=0;round<64;round++){varMRound;//Expandmessageif(round<16){//ConverttoplatformEndiannessforlatermathMRound=convertEndian(words[block+round]);}else{vargamma0x=M[round-15];vargamma1x=M[round-2];MRound=M[round-7]+M[round-16]+(rightRotate(gamma0x,7)^rightRotate(gamma0x,18)^(gamma0x>>>3))+(rightRotate(gamma1x,17)^rightRotate(gamma1x,19)^(gamma1x>>>10));}//MarraymatchesplatformendiannessM[round]=MRound|=0;//Computationvart1=(rightRotate(workingState[4],6)^rightRotate(workingState[4],11)^rightRotate(workingState[4],25))+((workingState[4]&workingState[5])^(~workingState[4]&workingState[6]))+workingState[7]+MRound+ROUND_CONSTANTS[round];vart2=(rightRotate(workingState[0],2)^rightRotate(workingState[0],13)^rightRotate(workingState[0],22))+((workingState[0]&workingState[1])^(workingState[2]&(workingState[0]^workingState[1])));for(vari=7;i>0;i--){workingState[i]=workingState[i-1];}workingState[0]=(t1+t2)|0;workingState[4]=(workingState[4]+t1)|0;}//Updatestatefor(round=0;round<8;round++){STATE[round]=(STATE[round]+workingState[round])|0;}}//FinallythestateneedstobeconvertedtoBigEndianforoutput//AndwewanttoreturnaUint8Array,notaUint32Arrayreturnnewuint8Array(newuint32Array(STATE.map(function(val){returnconvertEndian(val);})).buffer);}functionhmac(key,data){if(key.length>64)key=sha256(key);if(key.length<64){consttmp=newUint8Array(64);tmp.set(key,0);key=tmp;}//GenerateinnerandouterkeysvarinnerKey=newUint8Array(64);varouterKey=newUint8Array(64);for(vari=0;i<64;i++){innerKey[i]=0x36^key[i];outerKey[i]=0x5c^key[i];}//AppendtheinnerKeyvarmsg=newUint8Array(data.length+64);msg.set(innerKey,0);msg.set(data,64);//HasthepreviousmessageandappendtheouterKeyvarresult=newUint8Array(64+32);result.set(outerKey,0);result.set(sha256(msg),64);//Hashthepreviousmessagereturnsha256(result);}//ConvertastringtoaUint8Array,SHA-256it,andconvertbacktostringconstencoder=newTextEncoder("utf-8");functionsign(inputKey,inputData){constkey=typeofinputKey==="string"?encoder.encode(inputKey):inputKey;constdata=typeofinputData==="string"?encoder.encode(inputData):inputData;returnhmac(key,data);}functionhash(str){returnhex(sha256(encoder.encode(str)));}functionhex(bin){returnbin.reduce((acc,val)=>acc+("00"+val.toString(16)).substr(-2),"");}

使用

console.log(hex(sign("秘钥","数据")))//qMlLziV3yzjVb3VgwWhbSTYLsCZXTB1jftypu04SUDM=

HMAC

//引用crypto-js加密模块varCryptoJS=require('crypto-js')functionHMACEncrypt(){vartext="https://www.cnblogs.com/zichliang"varkey="secret"returnCryptoJS.HmacMD5(text,key).toString();}console.log(HMACEncrypt())//20ca7a63f1f4a7047ffd6b722b45319a

DES

//引用crypto-js加密模块varCryptoJS=require('crypto-js')functiondesEncrypt(){varkey=CryptoJS.enc.Utf8.parse(desKey),iv=CryptoJS.enc.Utf8.parse(desIv),srcs=CryptoJS.enc.Utf8.parse(text),//CBC加密模式,Pkcs7填充方式encrypted=CryptoJS.DES.encrypt(srcs,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7});returnencrypted.toString();}functiondesDecrypt(){varkey=CryptoJS.enc.Utf8.parse(desKey),iv=CryptoJS.enc.Utf8.parse(desIv),srcs=encryptedData,//CBC加密模式,Pkcs7填充方式decrypted=CryptoJS.DES.decrypt(srcs,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7});returndecrypted.toString(CryptoJS.enc.Utf8);}vartext="https://www.cnblogs.com/zichliang"//待加密对象vardesKey="0123456789ABCDEF"//密钥vardesIv="0123456789ABCDEF"//初始向量varencryptedData=desEncrypt()vardecryptedData=desDecrypt()console.log("加密字符串:",encryptedData)console.log("解密字符串:",decryptedData)//加密字符串:p+4ovmk1n5YwN3dq5y8VqhngLKW//5MM/qDgtj2SOC6TpJaFgSKEVg==

3DES

//引用crypto-js加密模块varCryptoJS=require('crypto-js')functiontripleDesEncrypt(){varkey=CryptoJS.enc.Utf8.parse(desKey),iv=CryptoJS.enc.Utf8.parse(desIv),srcs=CryptoJS.enc.Utf8.parse(text),//ECB加密方式,Iso10126填充方式encrypted=CryptoJS.TripleDES.encrypt(srcs,key,{iv:iv,mode:CryptoJS.mode.ECB,padding:CryptoJS.pad.Iso10126});returnencrypted.toString();}functiontripleDesDecrypt(){varkey=CryptoJS.enc.Utf8.parse(desKey),iv=CryptoJS.enc.Utf8.parse(desIv),srcs=encryptedData,//ECB加密方式,Iso10126填充方式decrypted=CryptoJS.TripleDES.decrypt(srcs,key,{iv:iv,mode:CryptoJS.mode.ECB,padding:CryptoJS.pad.Iso10126});returndecrypted.toString(CryptoJS.enc.Utf8);}vartext="https://www.cnblogs.com/zichliang"//待加密对象vardesKey="0123456789ABCDEF"//密钥vardesIv="0123456789ABCDEF"//偏移量varencryptedData=tripleDesEncrypt()vardecryptedData=tripleDesDecrypt()console.log("加密字符串:",encryptedData)console.log("解密字符串:",decryptedData)//加密字符串:pl/nNfpIrejwK+/X87VmGZIbS3kOB+IpFcx/97wpR4AO6q9HGjxb4w==

AES

//引用crypto-js加密模块varCryptoJS=require('crypto-js')functionaesEncrypt(){varkey=CryptoJS.enc.Utf8.parse(aesKey),iv=CryptoJS.enc.Utf8.parse(aesIv),srcs=CryptoJS.enc.Utf8.parse(text),//CBC加密方式,Pkcs7填充方式encrypted=CryptoJS.AES.encrypt(srcs,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7});returnencrypted.toString();}functionaesDecrypt(){varkey=CryptoJS.enc.Utf8.parse(aesKey),iv=CryptoJS.enc.Utf8.parse(aesIv),srcs=encryptedData,//CBC加密方式,Pkcs7填充方式decrypted=CryptoJS.AES.decrypt(srcs,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7});returndecrypted.toString(CryptoJS.enc.Utf8);}vartext="https://www.cnblogs.com/zichliang"//待加密对象varaesKey="0123456789ABCDEF"//密钥,16倍数varaesIv="0123456789ABCDEF"//偏移量,16倍数varencryptedData=aesEncrypt()vardecryptedData=aesDecrypt()console.log("加密字符串:",encryptedData)console.log("解密字符串:",decryptedData)//加密字符串:/q8i+1GN8yfzIb8CaEJfDOfDQ74in+XzQZYBtKF2wkAB6dM1qbBZ3HJVlY+kHDE3

RC4

//引用crypto-js加密模块varCryptoJS=require('crypto-js')functionRC4Encrypt(){returnCryptoJS.RC4.encrypt(text,key).toString();}functionRC4Decrypt(){returnCryptoJS.RC4.decrypt(encryptedData,key).toString(CryptoJS.enc.Utf8);}vartext="https://www.cnblogs.com/zichliang"varkey="12345678ASDFG"varencryptedData=RC4Encrypt()vardecryptedData=RC4Decrypt()console.log("加密字符串:",encryptedData)console.log("解密字符串:",decryptedData)//加密字符串:U2FsdGVkX19/bT2W57mzjwoF5Fc3Zb4WiyDU+MiNMmHfdJvZeScl0EW9yJWCPiRrsA==

Rabbit

//引用crypto-js加密模块varCryptoJS=require('crypto-js')functionrabbitEncrypt(){returnCryptoJS.Rabbit.encrypt(text,key).toString();}functionrabbitDecrypt(){returnCryptoJS.Rabbit.decrypt(encryptedData,key).toString(CryptoJS.enc.Utf8);}vartext="https://www.cnblogs.com/zichliang/p/16653303.html"varkey="1234567ASDFG"varencryptedData=rabbitEncrypt()vardecryptedData=rabbitDecrypt()console.log("加密字符串:",encryptedData)console.log("解密字符串:",decryptedData)//加密字符串:U2FsdGVkX1/pYbHvbNff3/RNpso4yRKIX0XDFta8hoLNxe52K8HSmF+XV8ayYqucTKVPP6AJtGczXS7U9kkxHnw=

RSA

使用 node-rsa

需要安装一个库

npminstallnode-rsa
//引用node-rsa加密模块varNodeRSA=require('node-rsa');functionrsaEncrypt(){pubKey=newNodeRSA(publicKey,'pkcs8-public');varencryptedData=pubKey.encrypt(text,'base64');returnencryptedData}functionrsaDecrypt(){priKey=newNodeRSA(privatekey,'pkcs8-private');vardecryptedData=priKey.decrypt(encryptedData,'utf8');returndecryptedData}varkey=newNodeRSA({b:512});//生成512位秘钥varpublicKey=key.exportKey('pkcs8-public');//导出公钥varprivatekey=key.exportKey('pkcs8-private');//导出私钥vartext="https://www.cnblogs.com/zichliang/p/16653303.html"varencryptedData=rsaEncrypt()vardecryptedData=rsaDecrypt()console.log("公钥:\n",publicKey)console.log("私钥:\n",privatekey)console.log("加密字符串:",encryptedData)console.log("解密字符串:",decryptedData)/*公钥:-----BEGINPUBLICKEY-----MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAN7JoMDNvvpB/po2OMSeSKsromfP5EyI0fAz6XDVwqdTUBwwAArLlqIzmVNK0yi4nlbj5eF+O8ZjRkRQ6xKP/CMCAwEAAQ==-----ENDPUBLICKEY-----私钥:-----BEGINPRIVATEKEY-----MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEA3smgwM2++kH+mjY4xJ5IqyuiZ8/kTIjR8DPpcNXCp1NQHDAACsuWojOZU0rTKLieVuPl4X47xmNGRFDrEo/8IwIDAQABAkEArI0Ps6TnIJ9SmZAbYbWSZPjTvYHXuatSpq8eQ+Vb8Ql003G5Y2FIoWpQX1jQ9/DsxEZ/1u+71bl08z1eONz2KQIhAPgLZOKanhDDaOn5sO7Y2RM3TyLS08mCGNGQxEhkEttFAiEA5e7bvnrSNh1lcF/QTxkWPGoXb9kxPljm49CfiTS9PEcCIDzxX7olTwzDVjWWeZhVgxArmK/vqMVrx3lF3lQC8ncZAiBlpY5nSoybd6tcXj8MeJ6n3o6112I5mbuYgqXEVhhCCQIgY6vinhOzMF0dX9MNjBm8x1mUCd4XG2TNQQcOik3RIGw=-----ENDPRIVATEKEY-----加密字符串:ZolvYwjFqOp1Yldui7rm75mSN5kz7533nc3B3H6xZGQR9v0elhbcjmI9vXaBsgdLNTuyoVk3bfzWfQdeIpvCpcBCTGe1HG9KrSBYDiWJc4vBgVBz8D57/XaS1zjM0kuAJ/ELu4os7XG5lMQbRbFhHXs7zQsIBq6/m2IZdGWx7HjB2jiQBQPMfszdQUOwQAbM5o7lRvUgdMVaZkEWpOTEybmUX4kxBP5CvNtB86oTRUw+U7Ex7QB8lWj33hoKvh70解密字符串:https://www.cnblogs.com/zichliang/p/16653303.html*/

使用自带模块crypto:

constcrypto=require('crypto');constnodeRSA=require('node-rsa');//生成一个1024长度的密钥对constkey=newnodeRSA({b:1024});//导出公钥constpublicKey=key.exportKey('public');//导出私钥constprivateKey=key.exportKey('private');constsecret='https://www.cnblogs.com/zichliang/p/16653303.html'//使用私钥加密,公钥解密constencrypt=crypto.privateEncrypt(privateKey,Buffer.from(secret));constdecrypt=crypto.publicDecrypt(publicKey,encrypt);console.log('加密后:',encrypt.toString('base64'));console.log('解密后:',decrypt.toString());

RSA 长加密

这个加密是真的麻烦 ,而且还需要导入jsencrypt.min.js

这里贴上 GitHub地址 https://github.com/wangqinglongDo/github_demo/blob/master/libs/jsencrypt.min.js

对了 还需要补环境 而且解密也不是很好用,如果有大佬知道如何解密的 希望在评论区告诉我

varencrypt=newJSEncrypt();varpublickKey="-----BEGINPUBLICKEY-----\MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLFb8qp1vRFvi/qfgi1Wg7Mi8l\LcpfAc+tgpyD7aFW9QquQVMm/jG1IJZVQ6LsdkI7TiDutMCzOMCBXbdSC9BCIAGA\L2Sz3cYVlGb1kYSM0ZMcUMIK5eF4Bptke070XHvbi8wArtysJ0l71RHDd786tNbG\W0hDSw3zAqTErbxFaQIDAQAB\-----ENDPUBLICKEY-----\"encrypt.setPublicKey(publickKey);//设置公钥加密证书vardata="https://www.cnblogs.com/zichliang/p/17265960.html";varcommonEncodeData=encrypt.encryptLong(data);//普通的加密console.log(commonEncodeData)varcnEscapeData=window.btoa(window.encodeURIComponent(data));//base64解密后的加密varencryptData=encrypt.encryptLong(cnEscapeData);//获取加密后数据。console.log(encryptData)


评论
建站知识
建站知识
使用技巧
调试安装
运营推广