angular使用RSA加密 用户名和密码 后端JAVA解密
RSA主要是生成公钥和私钥,公钥给前端加密,私钥用于解密。1、先在angular中引入jsencryptnpm install --save jsencrypt在index.html<script href="../node_modules/jsencrypt/bin/jsencrypt.min.js"></script>2、访问后端接口获取一个公钥@GetMapping(
RSA主要是生成公钥和私钥,公钥给前端加密,私钥用于解密。
1、先在angular中引入jsencrypt
npm install --save jsencrypt
在index.html
<script href="../node_modules/jsencrypt/bin/jsencrypt.min.js"></script>
2、访问后端接口获取一个公钥
@GetMapping("/getKey")
public RetModel<String> getKey(HttpServletRequest request){
// 生成一个公钥
String publicKey = RSAUtils.generateBase64PublicKey();
User user = SessionUtils.getCurrentUser();
if (user != null) {
user.setPublicKey(publicKey);
}
SessionUtils.setCurrentUser(user);
return new RetModel<String>(publicKey);
}
3、前端使用公钥对用户名和密码进行加密 加密后传给后端
import * as JsEncryptModule from 'jsencrypt'; //引入JSEncrypt
login(name: string, pass: string, publicKey: string): Observable<any> {
let encrypt = new JsEncryptModule.JSEncrypt();
encrypt.setPublicKey(publicKey); // 公钥
name = encrypt.encrypt(name.trim()); // 加密
pass = encrypt.encrypt(pass.trim()); // 加密
let user = {
name: name,
pass: pass
}
return this.http.post(`${this.urlPrefix}/login `, user);
}
4、后端解密,首先创建一个解密工具类。
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPublicKey;
public class RSAUtils {
private static final KeyPair keyPair = initKey();
private static KeyPair initKey() {
try {
Provider provider =new org.bouncycastle.jce.provider.BouncyCastleProvider();
Security.addProvider(provider);
SecureRandom random = new SecureRandom();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", provider);
generator.initialize(1024,random);
return generator.generateKeyPair();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public static String generateBase64PublicKey() {
PublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
return new String(Base64.encodeBase64(publicKey.getEncoded()));
}
public static String decryptBase64(String string) {
return new String(decrypt(Base64.decodeBase64(string.getBytes())));
}
private static byte[] decrypt(byte[] byteArray) {
try {
Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
Security.addProvider(provider);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", provider);
PrivateKey privateKey = keyPair.getPrivate();
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plainText = cipher.doFinal(byteArray);
return plainText;
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
5、直接调用工具类解密 user.getName()是需要解密的字符串
RSAUtils.decryptBase64(user.getName())
————————————————
原文链接:https://blog.csdn.net/weixin_41133806/article/details/102798401
更多推荐
所有评论(0)