|
|
|
|
115
|
|
115
|
|
116
|
public void publicPrivateKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
|
116
|
public void publicPrivateKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
|
117
|
//Create a Key Pair Generator
|
117
|
//Create a Key Pair Generator
|
118
|
- KeyPairGenerator keyGenAlice = KeyPairGenerator.getInstance("DSA","SUN");
|
|
|
119
|
- KeyPairGenerator keyGenBob = KeyPairGenerator.getInstance("DSA", "SUN");
|
|
|
|
|
118
|
+ KeyPairGenerator keyGenAlice = KeyPairGenerator.getInstance("RSA");
|
|
|
119
|
+ KeyPairGenerator keyGenBob = KeyPairGenerator.getInstance("RSA");
|
120
|
|
120
|
|
121
|
//Initialize the Key Pair Generator
|
121
|
//Initialize the Key Pair Generator
|
122
|
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
|
122
|
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
|
|
|
|
|
145
|
"When in eternal lines to time thou grow’st:\n" +
|
145
|
"When in eternal lines to time thou grow’st:\n" +
|
146
|
" So long as men can breathe or eyes can see,\n" +
|
146
|
" So long as men can breathe or eyes can see,\n" +
|
147
|
" So long lives this, and this gives life to thee.\n";
|
147
|
" So long lives this, and this gives life to thee.\n";
|
148
|
- Key aesKey = new SecretKeySpec(pubAlice.toString().getBytes(), "AES");
|
|
|
|
|
148
|
+
|
|
|
149
|
+ //encrypt
|
149
|
Cipher cipher = Cipher.getInstance("RSA");
|
150
|
Cipher cipher = Cipher.getInstance("RSA");
|
150
|
- cipher.init(Cipher.ENCRYPT_MODE, privAlice);
|
|
|
|
|
151
|
+ cipher.init(Cipher.PUBLIC_KEY, pubAlice);
|
151
|
byte[] encrypted = cipher.doFinal(expected.getBytes());
|
152
|
byte[] encrypted = cipher.doFinal(expected.getBytes());
|
152
|
String enc = new String(Base64.getEncoder().encodeToString(encrypted));
|
153
|
String enc = new String(Base64.getEncoder().encodeToString(encrypted));
|
153
|
System.err.println("Encrypted: " + enc);
|
154
|
System.err.println("Encrypted: " + enc);
|
154
|
- //During the decryption (Java 8):
|
|
|
155
|
-
|
|
|
156
|
- System.out.print("Enter ciphertext: ");
|
|
|
157
|
- encrypted = Base64.getDecoder().decode(enc);
|
|
|
158
|
|
155
|
|
159
|
- cipher.init(Cipher.DECRYPT_MODE, aesKey);
|
|
|
|
|
156
|
+ //decrypt
|
|
|
157
|
+ cipher.init(Cipher.PRIVATE_KEY, privAlice);
|
160
|
String decrypted = new String(cipher.doFinal(encrypted));
|
158
|
String decrypted = new String(cipher.doFinal(encrypted));
|
161
|
System.err.println("Decrypted: " + decrypted);
|
159
|
System.err.println("Decrypted: " + decrypted);
|
162
|
}
|
160
|
}
|