Skip to content

Instantly share code, notes, and snippets.

@volnoboy
Created December 19, 2017 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save volnoboy/76af2c04975a9e0e62af7644bb89f53b to your computer and use it in GitHub Desktop.
Save volnoboy/76af2c04975a9e0e62af7644bb89f53b to your computer and use it in GitHub Desktop.
RSA crypto example
package com.volnoboy.util;
import sun.security.rsa.RSAPublicKeyImpl;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class Crypto {
private final String RSA = "RSA";
private final int KEY_SIZE = 3072;
public static void main(String [] args) throws Exception {
Crypto crypto = new Crypto();
KeyPair keyPair = crypto.buildKeyPair();
PublicKey pubKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte [] encrypted = crypto.encrypt(privateKey, "This is secret a message...");
System.out.println(new String(encrypted));
byte[] secret = crypto.decrypt(pubKey, encrypted);
System.out.println(new String(secret));
}
public String decrypt(BigInteger n, BigInteger e, byte [] encrypted) throws Exception {
RSAPublicKeyImpl publicKey = new RSAPublicKeyImpl(n, e);
return new String(decrypt(publicKey, encrypted));
}
private KeyPair buildKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
keyPairGenerator.initialize(KEY_SIZE);
return keyPairGenerator.genKeyPair();
}
private byte[] encrypt(PrivateKey privateKey, String message) throws Exception {
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(message.getBytes());
}
private byte[] decrypt(PublicKey publicKey, byte [] encrypted) throws Exception {
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(encrypted);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment