Summary
RSA encryption algorithm is an asymmetric encryption algorithm
The way of RSA encryption
-
Data encrypted by public key and decrypted by private key
-
Data encrypted by private key and decrypted by public key
RSA is a pair of keys. They are public key and private key. The public key and private key are actually a group of numbers. The binary bit length can be 1024 bits or 2048 bits. The longer the length is, the greater the encryption strength is. So far, the maximum length that can be cracked is 768 bits. As long as the length is higher than 768 bits, it is relatively safe
Disadvantages of RSA encryption
Because the principle of RSA algorithm is large number calculation, the fastest RSA algorithm is several times slower than symmetric encryption algorithm.
public class RSAUtils { public static String RSA_ALGORITHM = "RSA"; public static String UTF8 = "UTF-8"; /** * Key length, the default key length of DSA algorithm is 1024 * Key length must be a multiple of 64, between 512 and 65536 bits * */ private static final int KEY_SIZE=1024; public static void main(String[] args) throws Exception { String password = "1234abcd5678"; KeyStore keys = createKeys(); byte[] publicKey = getPublicKey(keys); byte[] privateKey = getPrivateKey(keys); System.out.println("Public key:"+Base64.encode(publicKey)); System.out.println("Private key:"+ Base64.encode(privateKey)); byte[] encryptByPublicKey = encryptByPublicKey(password.getBytes(), publicKey); System.out.println("Data encrypted with public key:"+Base64.encode(encryptByPublicKey)); byte[] decryptByPrivateKey = decryptByPrivateKey(encryptByPublicKey, privateKey); System.out.println("Data decrypted with private key:"+new String(decryptByPrivateKey)); } /** * Generate key pair * @return Key pair object * @throws NoSuchAlgorithmException */ public static KeyStore createKeys() throws NoSuchAlgorithmException { //KeyPairGenerator is used to generate public and private key pairs. The key pair generator uses the getInstance factory method KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM); keyPairGenerator.initialize(KEY_SIZE); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); KeyStore keyStore = new KeyStore( publicKey, privateKey); return keyStore; } /** * Get private key * @param keyStore * @return */ private static byte[] getPrivateKey(KeyStore keyStore){ return ((RSAPrivateKey)keyStore.privateKey).getEncoded(); } /** * Get public key * @param keyStore * @return */ private static byte[] getPublicKey(KeyStore keyStore){ return ((RSAPublicKey)keyStore.publicKey).getEncoded(); } /** * Private key encryption * @param data Data to be encrypted * @param key secret key * @return byte[] Encrypted data * */ public static byte[] encryptByPrivateKey(byte[] data,byte[] key) throws Exception{ //Get the private key PKCS8EncodedKeySpec pkcs8KeySpec=new PKCS8EncodedKeySpec(key); KeyFactory keyFactory=KeyFactory.getInstance(RSA_ALGORITHM); //Generate private key PrivateKey privateKey=keyFactory.generatePrivate(pkcs8KeySpec); //data encryption Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateKey); return cipher.doFinal(data); } /** * Public key encryption * @param data * @param key * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws InvalidKeyException */ private static byte[] encryptByPublicKey(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException { //Instantiate key factory KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM); //Initialize the public key and create a new X509EncodedKeySpec based on the given encoding key. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); //data encryption Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE,publicKey); return cipher.doFinal(data); } /** * Private key decryption * @param data Data to be decrypted * @param key secret key * @return byte[] Declassified data * */ public static byte[] decryptByPrivateKey(byte[] data,byte[] key) throws Exception{ //Get the private key PKCS8EncodedKeySpec pkcs8KeySpec=new PKCS8EncodedKeySpec(key); KeyFactory keyFactory=KeyFactory.getInstance(RSA_ALGORITHM); //Generate private key PrivateKey privateKey=keyFactory.generatePrivate(pkcs8KeySpec); //data decryption Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); } /** * Public key decryption * @param data Data to be decrypted * @param key secret key * @return byte[] Declassified data * */ public static byte[] decryptByPublicKey(byte[] data,byte[] key) throws Exception{ //Instantiate key factory KeyFactory keyFactory=KeyFactory.getInstance(RSA_ALGORITHM); //Initialize public key //Key material conversion X509EncodedKeySpec x509KeySpec=new X509EncodedKeySpec(key); //Generate public key PublicKey pubKey=keyFactory.generatePublic(x509KeySpec); //data decryption Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, pubKey); return cipher.doFinal(data); } //Define key class @Data @AllArgsConstructor public static class KeyStore{ private Object publicKey; private Object privateKey; } }
Test results:
Public key: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdnS/LflJjuj4M9V63SPe3YUx0uFD/oVoPRwG2 p1HXNSp6x+h7ImVAns9Bx5aKKthTH6V70W0TAdreCwS7WyzakvnHu4zWhGX77JM7/dEgdU5LSK8s I7YLz4bKhCpjBQGXJiKj/3InDPidWzw6w53Ce207HUzrYgR71rM3/OfewwIDAQAB //Private key: miicdgibadanbgqqqhkig9w0baqefaascamawggkiaaogbaj2dl8t + umo6pgz1xrdi97dhths4 UP+hWg9HAbanUdc1KnrH6HsiZUCez0HHlooq2FMfpXvRbRMB2t4LBLtbLNqS+ce7jNaEZfvskzv9 0SB1TktIrywjtgvPhsqEKmMFAZcmIqP/cicM+J1bPDrDncJ7bTsdTOtiBHvWszf8597DAgMBAAEC gYBb6uuQtV6/IkJFtGNEaJ1uqKO5/jPeoO6wsixhpTqpUywu5p7CENET2onsRsWYVlxKPc54Yy5F Q3OswqhDy2xgL5AFcCboDHCipVojA/6lQsWnvQL1Go/NkAf88YmIMvcNV6TrlBW3TWOr9D6+/LUW Hjbmr744bE7eRODAV/PVYQJBAOZe0uIm5mXm+eoyE8BT7SVu7XWeQZNtDNvD0a6h4QxQA+fkftVP 9icAfRxZEi3WH8aCtUJJkDdzo3u11XdPQF8CQQCvJjBoQI+5l4dlBfsN3jvLr9H6U1Hx20EF47t/ FbfSEHHJ0LQ6frVyEqQr2MSuL+RhE4ko+PWpB62meFpmKuwdAkEAxI73xDqIrz3K0wZzT9DMMPpa 5dZoAVA0fnawPB6nFIhZLM0LYxpc3p5OIZfmKPHgHtJ7sdlukcG7JdzaDHi0ZQJAe6pqKWHUWQUd av3zChKsg5+rkaS8yhi163OlEhECjkZgIU/DwT1v3ZA97FuMWzSjestxX8WQpn0uZci6g0KxHQJA BA1IIAnT7LlLHDWDXAH3B4U60GQZh7BbfF7m3nQvttLeUOc2hpklN3Rr3hpKRDghX5m5iZeiIPri nPq25FdzAA== //Data encrypted with public key: i9ybxgll3kuqnsnf71ntxkcgzhzd7tpjjtixw1sg3avxov0tz84u9ehewbtf4ptow4tjxkxva7 H2cRSkMknaZ0zGI7cGm/TANevR5cdYVdxa7IBIevDRvj+Lnklo8HQg0QgSqLAQeJ1d38lQkcXoXO i5Qdol2RFTkC7zIPKdc= //Data decrypted with private key: 1234abcd5678