Skip to content

Instantly share code, notes, and snippets.

@VictorZZZZ
Created June 21, 2023 12:50
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 VictorZZZZ/e5438fdbe6ddaf58e20ebeae481220a1 to your computer and use it in GitHub Desktop.
Save VictorZZZZ/e5438fdbe6ddaf58e20ebeae481220a1 to your computer and use it in GitHub Desktop.
Encryption and Decryption example in Java
public class RSAEncryption {
public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
// generateKeyPair();
final PublicKey publicKey = getPublicKeyFromFile("public.key");
final PrivateKey privateKey = getPrivateKeyFromFile("private.key");
String secret = "Some string";
String encodedMessage = encryptString(publicKey, secret);
System.out.println("Encoded string: " + encodedMessage);
String decryptedMessage = decodeMessage(privateKey, encodedMessage);
System.out.println("Decoded string: " + decryptedMessage);
// System.out.println(Base64.getEncoder().encodeToString("test".getBytes()));
// System.out.println(new String(Base64.getDecoder().decode("dGVzdA==")));
}
private static String decodeMessage(final PrivateKey privateKey, final String encodedMessage) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
final byte[] decode = Base64.getDecoder().decode(encodedMessage);
Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedMessageBytes = decryptCipher.doFinal(decode);
String decryptedMessage = new String(decryptedMessageBytes, StandardCharsets.UTF_8);
return decryptedMessage;
}
private static String encryptString(final PublicKey publicKey, final String secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] secretMessageBytes = secret.getBytes(StandardCharsets.UTF_8);
byte[] encryptedMessageBytes = encryptCipher.doFinal(secretMessageBytes);
return Base64.getEncoder().encodeToString(encryptedMessageBytes);
}
private static void generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
final KeyPair keyPair = generator.generateKeyPair();
final PublicKey publicKey = keyPair.getPublic();
final PrivateKey privateKey = keyPair.getPrivate();
try (FileOutputStream fos = new FileOutputStream("public.key")) {
final byte[] encoded = publicKey.getEncoded();
final String publicKeyInString = Base64.getEncoder().encodeToString(encoded);
fos.write(publicKeyInString.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
try (FileOutputStream fos = new FileOutputStream("private.key")) {
final byte[] encoded = privateKey.getEncoded();
final String privateKeyInBytes = Base64.getEncoder().encodeToString(encoded);
fos.write(privateKeyInBytes.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static PublicKey getPublicKeyFromFile(String filePath) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
File publicKeyFile = new File(filePath);
byte[] publicKeyBytes = Files.readAllBytes(publicKeyFile.toPath());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyBytes));
return keyFactory.generatePublic(publicKeySpec);
}
private static PrivateKey getPrivateKeyFromFile(String filePath) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
File privateKeyFile = new File(filePath);
byte[] privateKeyBytes = Files.readAllBytes(privateKeyFile.toPath());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyBytes));
return keyFactory.generatePrivate(privateKeySpec);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment