Preface
In a previous project, I felt that the encryption method of login registration was not safe and needed to be modified, so I used RSA encryption. It is said online that it is the safest and existing technology cannot be cracked. I know that the login of JD.com and China Life are both used for this encryption. I want to sort it out, someone will definitely use it. Introduction to
- RSA encryption
- RSA encryption benefits
- RSA encryption explanation
- RSA encryption and decryption explanation
- RSA signature and verification explanation
- RSA test
- RSA encryption application
1. Introduction to RSA encryption
RSA encryption algorithm is an asymmetric encryption algorithm. RSA is widely used in public key encryption and electronic commerce. The RSA was proposed in 1977 by Ron Rivest, Adi Shamir and Leonard Adleman. At that time, all three of them worked at MIT . RSA is composed of the letters at the beginning of the last names of the three of them.
The difficulty of factoring the huge integers determines the reliability of RSA algorithm . In other words, the more difficult it is to factorize a huge integer, the more reliable the RSA algorithm is. If someone finds an algorithm for fast factorization, the reliability of information encrypted with RSA will definitely decrease dramatically. But the possibility of finding such an algorithm is very small. Today, only the short RSA key can be solved by powerful means. So far, there is no reliable way to attack RSA algorithms in the world. As long as the length of its key is long enough, the information encrypted with RSA cannot be actually solved.
2. The benefits of RSA encryption
. If you want to talk about its benefits, you feel it is necessary to first talk about the disadvantages of several commonly used encryption methods.
MD5 encryption is used more frequently in development, and is generally used in the encryption of the login password or the verification of the interface. With the same parameters, its encryption result is the same. If the password is relatively simple and stolen, you can query your inscription password through big data. Because it is not decryptable, it can only be used as a signature verification on the interface, and data cannot be transmitted encryptedly.
base64 encrypted is unsafe because it can be decrypted.
AES encryption has been used in our interface docking. It is symmetric encryption, requiring the key to be the same, which can easily cause the key to leak. No RES encryption is secure.
RSA encryption , which is an asymmetric encryption algorithm, that is, the encryption key (public key) and the decrypted secret key ( private key ) are different. And the results of the same parameters are different each time, which can ensure that even if your data is stolen, there is no way to get your plaintext data through big data. During the docking process, your public key will always be exposed, so the data is absolutely safe.
3. Explanation of RSA encryption
encryption is to prevent information leakage. The lengths of the public and private keys encrypted by
RSA can be defined, and there is currently no upper limit. The length of mainstream keys is at least 1024 bits or more, which means at least 128 bytes (bytes). There will be security problems less than this length.
RSA encrypted plaintext length cannot be greater than the length of the key, but since the length of the plaintext is smaller than the length of the key, padding needs to be used to take up 11 bytes, so the length of the encryption plaintext key length -1
Here we define the length of the secret key as 1024bits
//RSA maximum encrypted plaintext size private static final int MAX_ENCRYPT_BLOCK = 117;// RSA maximum decrypted ciphertext size private static final int MAX_DECRYPT_BLOCK = 128;// Get the key pair public static KeyPair getKeyPair() throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(1024);//Define the key length to 1024 return generator.generateKeyPair();} // Get the private key public static PrivateKey getPrivateKey(String privateKey) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes()); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey); return keyFactory.generatePrivate(keySpec); } //Get public static PublicKey getPublicKey(String publicKey) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes()); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey); return keyFactory.generatePublic(keySpec); }
Because the encrypted plaintext length cannot be greater than 117, plaintext with length greater than 117 can be encrypted and decrypted in segments.
//RSA encryption public static String encrypt(String data, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); int inputLen = data.getBytes().length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offset = 0; byte[] cache; int i = 0; // Encryption of data segments while (inputLen - offset 0) { if (inputLen - offset MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset); } out.write(cache, 0, cache.length); i++; offset = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); // Get encrypted content using base64 for encoding, and convert it into a string using UTF-8 as the standard // Encrypted string return new String(Base64.encodeBase64String(encryptedData));}//RSA decryption public static String decrypt(String data, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] dataBytes = Base64.decodeBase64(data); int inputLen = dataBytes.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offset = 0; byte[] cache; int i = 0; // Decrypt the data segment while (inputLen - offset 0) { if (inputLen - offset MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(dataBytes, offset, inputLen - offset); } out.write(cache, 0, cache.length); i++; offset = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); // Decrypted content return new String(decryptedData, "UTF-8"); }
4. Explanation of RSA signature
signature is to prevent information from being modified in series. The public key of the signed public.
A passes a message to B, and A signs the data through the private key to form a signature, and gives the signature and data to B.
B gets the signature and data, and verify the signature through the public key. If true, it means that it is a message sent by A, otherwise it is not.
//Signature public static String sign(String data, PrivateKey privateKey) throws Exception { byte[] keyBytes = privateKey.getEncoded(); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey key = keyFactory.generatePrivate(keySpec); Signature signature = Signature.getInstance("MD5withRSA"); signature.initSign(key); signature.update(data.getBytes()); return new String(Base64.encodeBase64(signature.sign())); } //Sign verification public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception { byte[] keyBytes = publicKey.getEncoded(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey key = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance("MD5withRSA"); signature.initVerify(key); signature.update(srcData.getBytes()); return signature.verify(Base64.decodeBase64(sign.getBytes())); }
Note: To modify the key length, you need to synchronously modify the maximum decrypted ciphertext size
5. RSA test
public static void main(String[] args) { try { // Generate key pair KeyPair keyPair = getKeyPair(); String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded())); System.out.println("Private Key:" + privateKey); String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded())); System.out.println("Public key:" + publicKey); // RSA encryption String data = "Narrow name login password"; String encryptData = encrypt(data, getPublicKey(publicKey)); System.out.println("Encrypted content:" + encryptData); // RSA decrypt String decryptData = decrypt(encryptData, getPrivateKey(privateKey)); System.out.println("Decrypted content:" + decryptData);// RSA signature String sign = sign(data, getPrivateKey(privateKey)); // RSA signature verification boolean result = verify(data, getPublicKey(publicKey), sign); System.out.print("Certificate verification result:" + result); } catch (Exception e) { e.printStackTrace(); System.out.print("Encryption and decryption exception"); } }
results
6. Application of RSA encryption
Because jsencrypt.min.js makes a good encapsulation of RSA, we can directly reference it on the front-end page.
front-end js encryption
script src="/Resource/js/jsencrypt.min.js"/scriptscript type="text/javascript"function to_login(){ var userAccount = $('#userAccount').val(); var password = $('#password').val(); if(userAccount==""||password==""){ alert("Username or password cannot be empty!"); return; } $.ajax({ type : 'POST', dataType : 'json', url : ' ${contextPath}/customer/to/loginTest', data : { userAccount :userAccount, password :getEntryptPwd(password) }, success: function(data){ if(data.result == -1){alert(data.msg); }else if(data.result == 2){ alert("Verification successful"); return; } } });}function getEntryptPwd(pwd){ var pubKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC50/mvgdowH3nC5XOYQya'+ 'G78kYmws4b/1KJCb9zG85IJf2cmZ+9sJS80jYLRjuqFQfwwwixhibLjshp4bZirvR8jIkf9yti9'+ 'HSGF1pHqNVag2HNyEbFFJ13c7lI+3LN5/0dByoIB3g/80R6kVMhAShzYRE6EfhBCoap6fzZfJu3QIDAQAB'; var encrypt = new JSEncrypt(); encrypt.setPublicKey(pubKey); return encrypt.encrypt(pwd);}/script
decryption reference the above decryption.
JD login page
! ! !