前端进行Rsa加密

RSA

RSA加密拥有公钥与密钥,其中密钥是根据公钥来决定的。
对称性加密是采用了对称密码编码,算法是加密与解密使用了相同的密钥加密,RSA公钥与私钥是不同的,是非对称性加密算法。

公钥与密钥的生成方法

Mac生成公钥与私钥
Mac一般自带openssl,没有先进行安装。

$ sudo apt-get install openssl

1.新建一文件夹用来存放公钥私钥
2.进入文件夹,生成私钥

$ openssl genrsa -out rsa_private_key.pem 1024

此时会提示输入密码。
私钥文件名:rsa_private_key.pem

3.通过私钥提取公钥

$ openssl rsa -in private.key -pubout -out pub.key

公钥文件名:rsa_public_key.pem

加密与解密

加密

require('jsencrypt')

function encrypt(message,publicKey){
	var encrypt=new JSEncrypt();
	encrypt.setPublicKey(publicKey);	//	 publicKey为公钥
	const txt = encrypt.encrypt(message);
	return txt;
}

解密

node RSA解密方法

const crypto = require("crypto");
	
function decrypt(encryptTxt,privateK) {   
    const priKey = crypto.Utils.pemPriKey(privateK, crypto.Utils.PKCS1);	// privateK为私钥
    const decryptText = cryptoAsymmetric.privateDecrypt(priKey, encryptTxt, { input: 'base64' }).toString();
    return decryptText;
  }
}

js RSA解密方法

require('jsencrypt')

function decrypt(encryptTxt,privateK){
	var encrypt=new JSEncrypt();
	encrypt.setPrivateKey(privateK);
 	encrypt.decrypt(encryptTxt);
	return txt;
}

By:Yl

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前端Vue RSA加密示例代码如下: ```javascript 前端Vue RSA加密 import JSEncrypt from 'jsencrypt' // 创建RSA加密实例 const encrypt = new JSEncrypt() // 设置RSA公钥 const publicKey = 'YOUR_RSA_PUBLIC_KEY' encrypt.setPublicKey(publicKey) // 要加密的数据 const data = 'YOUR_DATA_TO_ENCRYPT' // 使用RSA公钥进行加密 const encryptedData = encrypt.encrypt(data) // 将加密后的数据发送到后端进行解密 ``` 后端Java解密示例代码如下: ```java import java.security.KeyFactory; import java.security.PrivateKey; import java.security.spec.PKCS8EncodedKeySpec; import javax.crypto.Cipher; import org.apache.commons.codec.binary.Base64; public class RSADecrypt { public static String decrypt(String encryptedData, String privateKeyStr) throws Exception { // 将Base64编码后的私钥字符串转换为PrivateKey对象 byte[] privateKeyBytes = Base64.decodeBase64(privateKeyStr); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); // 使用私钥进行解密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] encryptedBytes = Base64.decodeBase64(encryptedData); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); // 返回解密后的数据 return new String(decryptedBytes); } } ``` 请将 `YOUR_RSA_PUBLIC_KEY` 替换为你的RSA公钥,然后在前端加密后的数据发送到后端,后端调用 `RSADecrypt.decrypt()` 方法进行解密,并将 `YOUR_DATA_TO_ENCRYPT` 替换为你要加密的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值