Skip to content

Instantly share code, notes, and snippets.

@JulienGenoud
Last active April 5, 2018 15:36
Show Gist options
  • Save JulienGenoud/fdcabaa30678ce044d088643ccb05ec7 to your computer and use it in GitHub Desktop.
Save JulienGenoud/fdcabaa30678ce044d088643ccb05ec7 to your computer and use it in GitHub Desktop.
String str = "coucou";
String seed = "seedFromSensor";
// generate public and private keys
final int keySize = 2048;
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom sr = new SecureRandom(seed.getBytes());
keyPairGenerator.initialize(keySize, sr);
KeyPair keyPair = keyPairGenerator.genKeyPair();
PublicKey pubKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] pubKeyBytes = pubKey.getEncoded();
// send the pubKeyBytes
// encrypt the message
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(pubKeyBytes)));
byte[] encrypted = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
// decrypt the message
Cipher cipher2 = Cipher.getInstance("RSA");
cipher2.init(Cipher.DECRYPT_MODE, privateKey);
new String(cipher2.doFinal(encrypted), StandardCharsets.UTF_8);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment