Last active
April 5, 2018 15:36
-
-
Save JulienGenoud/fdcabaa30678ce044d088643ccb05ec7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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