当前位置: 首页 > Web前端 > JavaScript

在golang和javascript中使用RSA

时间:2023-03-27 10:37:56 JavaScript

要求是先在golang中生成一个keypair。javascript在向golang发送数据之前,首先请求publickeyAPI获取publickey,然后根据publickey对数据进行加密,最后将加密后的数据发送给golang。实现1.Golang生成keypairvar(privateKey*rsa.PrivateKeypublicKey*rsa.PublicKeypublicKeyStringstring)ifpri,err:=rsa.GenerateKey(rand.Reader,32);err!=nil{panic(err)}else{privateKey=pripublicKey=&pri.PublicKey}//将publicKey转换为PKIX,ASN.1DER格式ifderPkix,err:=x509.MarshalPKIXPublicKey(publicKey);err!=nil{returnerr}else{//设置PEM编码结构block:=pem.Block{Type:"RSAPUBLICKEY",Bytes:derPkix,}//将publicKey作为字符串返回给javascriptpublicKeyString=string(pem.EncodeToMemory(&block))}二、javascript使用publickey加密数据npminstalljsencryptgetpublickeyconst[pk,setPK]=useState('')useEffect(()=>{fetch(`${url}`,{method:'GET'}).then(r=>r.json()).then(d=>{if(d.hasOwnProperty('public_key'))setPK(d.public_key)elsealert('API返回值缺少必填字段!')}).catch(e=>{alert(e)})},[])加密用户数据letencryptor=newJSEncrypt()//创建一个新的JSEncrypt对象encryptor.setPublicKey(pk)//设置publickeyletciphertext=encryptor.encrypt(data)//加密数据3.Golang使用私钥解密数据//Decodebase64stringbytes,err:=base64.StdEncoding.DecodeString(ciphertext)iferr!=nil{panic(err)}//解密明文,e:=rsa.DecryptPKCS1v15(rand.Reader,privateKey,bytes,)iferr!=nil{panic(e)}