后端
- maven引:
RSA加密
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
<version>5.6.3</version>
</dependency>
Base64
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
- 生成公钥私钥(一对):
@Test
public void generatePairKey() throws UnsupportedEncodingException {
RSA rsa = new RSA();
String privateKeyBase64 = rsa.getPrivateKeyBase64();
String publicKeyBase64 = rsa.getPublicKeyBase64();
Console.log("priKey:{}", privateKeyBase64);
Console.log("pubKey:{}", publicKeyBase64);
}
- 验证测试:
//privateKeyBase64 私钥解密,用上面获取到的私钥解密
RSA rsa = new RSA(privateKey, null);
//encodePassword 前端传入的publicKeyBase64加密后的密码
byte[] decrypt = rsa.decrypt(Base64.decodeBase64(encodePassword), KeyType.PrivateKey);
String password = new String(decrypt);
前端
- 安装
npm install jsencrypt
- 加密
import JSEncrypt from 'jsencrypt'
var encryptor = new JSEncrypt() // 创建加密对象实例
//之前ssl生成的公钥,复制的时候要小心不要有空格
var pubKey = '后端生成的publicKeyBase64公钥'
encryptor.setPublicKey(pubKey)//设置公钥
var rsaPassWord = encryptor.encrypt('要加密的内容') // 对内容进行加密
前端内容部分有引用简书作者文章,特此说明。原创链接在下方