RSA key pair creation / encryption / decryption sample (JAVA)

As the title says. I think there are various things such as putting it in the store or passing it as a file The key pair is once Base64 encoded.

Dependence(maven)


<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk16</artifactId>
    <version>1.45</version>
</dependency>

RSAKeyPairSample.java


/**
 *RSAKeyPair creation, encryption, and decryption samples
 * @author ryutaro_hakozaki
 */
public class RSAKeyPairSample {

    public static void main(String argv[]){
        
        RSAKeyPairSample sample = new RSAKeyPairSample();
        
        /**
         *Creating a Key Pair
         */
        String[] keyPair = sample.createKeyPairAsBase64();
        System.out.println("Public key== " + keyPair[0]);
        System.out.println("Private key== " + keyPair[1]);
        
        /**
         *Encrypted with private key
         *Since it is RSA, you can encrypt it with either one.
         *In secure communication, it is encrypted with a public key
         *Digital signature encrypts the hash of the document with the private key
         */
        final String message = "Qiita is a technical information sharing service for programmers.";
        byte[] encryptBytes = sample.encryptByBase64Key(message.getBytes(), keyPair[1]);
        System.out.println("----------------------------------------");
        System.out.println("[Plaintext]");
        System.out.println(message);
        System.out.println("[Encryption result]");
        System.out.println(new String(encryptBytes));
        
        /**
         *Decrypt with public key
         *Decryption is possible if the key is a pair
         */
        byte[] decryptBytes = sample.decryptBtBase64Key(encryptBytes, keyPair[0]);
        System.out.println("[Decryption result]");
        System.out.println(new String(decryptBytes));
        
    }
    
    /**
     *Create an RSA key pair
     * @return Base64 encoded public and cryptographic keys
     */
    public String[] createKeyPairAsBase64(){
        String[] keyPair = new String[2];

        /**
         *Create Key Pair
         */
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        Cipher cipher;
        KeyPairGenerator generator;
        try {
            cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");
            generator = KeyPairGenerator.getInstance("RSA", "BC");
        } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException ex) {
            return keyPair;
        }
        SecureRandom random = new SecureRandom();
        generator.initialize(2048, random);
        KeyPair pair = generator.generateKeyPair();
        
        /**
         *Base64 encoded Key Pair and returned
         */
        keyPair[0] = encodeObjectAsBase64(pair.getPublic());
        keyPair[1] = encodeObjectAsBase64(pair.getPrivate());
        
        return keyPair;        
    }

    /**
     *Perform encryption
     * @param data
     * @param base64Key
     * @return Encrypted data
     */
    public byte[] encryptByBase64Key(byte[] data, String base64Key){
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        try {
            Key myKey = (Key) decodeObjectFromBase64(base64Key);
            Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");
            cipher.init(Cipher.ENCRYPT_MODE, myKey, new SecureRandom());
            return cipher.doFinal(data);
        } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException  ex) {
            return null;
        }
    }
    
    /**
     *Decrypt
     * @param data
     * @param base64Key
     * @return Decrypted data
     */
    private byte[] decryptBtBase64Key(byte[] data, String base64Key){
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        try {
            Key myKey = (Key) decodeObjectFromBase64(base64Key);
            Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");
            cipher.init(Cipher.DECRYPT_MODE, myKey, new SecureRandom());
            return cipher.doFinal(data);
        } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException  ex) {
            return null;
        }
    }
    
    /**
     *Base64 encode Object
     * @param o
     * @return encoding result
     */    
    private static String encodeObjectAsBase64(Object o){
        //Depending on the situation, this time I will compress the bytes and return as small a size as possible
        try(ByteArrayOutputStream byteos = new ByteArrayOutputStream();
            GZIPOutputStream gos = new GZIPOutputStream(byteos);) {
            try(ObjectOutputStream objos = new ObjectOutputStream(gos)){
                objos.writeObject(o);
            }
            byte[] retObject = byteos.toByteArray();
            return Base64.getEncoder().encodeToString(retObject);
        } catch (IOException ex) {
            Logger.getLogger(RSAKeyPairSample.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     *Convert Base64 encoding to Object
     * @param s
     * @return
     * @throws IOException 
     */
    private static Object decodeObjectFromBase64(String s) throws IOException{
       byte[] bytes = Base64.getDecoder().decode(s);
       try(GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
           return new ObjectInputStream(gis).readObject();
       } catch (ClassNotFoundException ex) {
           return null;
       }
    }

}

Execution result


Public key==H4sIAAAAAAAAAFvzloG1uIhBN78oXS8pvzQvuTI5sbgkJ1UvKzlVr6AovywzJbVI (omitted)
Private key==H4sIAAAAAAAAAJVVe1QTdxae8AiRhzwiUApUEamAJRBQtx608lBsIArIY4GAOEmGZGJeTiaQAA (omitted)
----------------------------------------
[Plaintext]
Qiita is a technical information sharing service for programmers.
[Encryption result]
(abridgement)
[Decryption result]
Qiita is a technical information sharing service for programmers.

Recommended Posts

RSA key pair creation / encryption / decryption sample (JAVA)
RSA encryption / decryption with java 8
[memo] Generate RSA key pair for SSH in Java
Java encryption and decryption PDF
SpringSecurity TextEncryptor: Common key encryption / decryption
Java encryption, decryption of Word documents
KMS) Envelope encryption with openssl and java decryption
[Java] Generics sample
Java sample code 02
Java sample code 03
Selenium sample (Java)
Java GUI sample
Java sample code 04
java file creation
Java sample code 01
java directory creation