Untitled
unknown
plain_text
2 years ago
2.1 kB
13
Indexable
import javax.crypto.Cipher;
import java.security.*;
public class RSAOEAPExample {
public static void main(String[] args) throws Exception {
// Generate RSA key pair
KeyPair keyPair = generateRSAKeyPair();
// Message to be encrypted
String originalMessage = "Hello, RSA-OEAP!";
// Encrypt the message
byte[] encryptedMessage = encrypt(originalMessage, keyPair.getPublic());
// Decrypt the message
String decryptedMessage = decrypt(encryptedMessage, keyPair.getPrivate());
// Display the results
System.out.println("Original Message: " + originalMessage);
System.out.println("Encrypted Message: " + bytesToHex(encryptedMessage));
System.out.println("Decrypted Message: " + decryptedMessage);
}
// Generate RSA key pair
public static KeyPair generateRSAKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); // You can adjust the key size as needed
return keyPairGenerator.generateKeyPair();
}
// Encrypt using RSA-OEAP
public static byte[] encrypt(String message, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(message.getBytes());
}
// Decrypt using RSA-OEAP
public static String decrypt(byte[] encryptedMessage, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedMessage);
return new String(decryptedBytes);
}
// Convert bytes to hexadecimal string
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
hexString.append(String.format("%02X", b));
}
return hexString.toString();
}
}
Editor is loading...
Leave a Comment