Skip to content

RSAUtils

Dokkaltek edited this page Apr 10, 2025 · 5 revisions

RSA encryption and decryption

By default the library uses RSA/ECB/OAEPWithSHA-256AndMGF1Padding, which isn't the same that java uses by default, but is considered to be more secure.

Strings

// RSA (RSA/ECB/OAEPWithSHA-256AndMGF1Padding)
String sampleString = "Your message here";
KeyPair result = RSAUtils.generateRSAKeyPair(RSAKeyBits.KEY_2048);
String encryptedMessage = RSAUtils.encryptToRSA(sampleString, result.getPublic());
String decryptedMessage = RSAUtils.decryptRSA(encryptedMessage, result.getPrivate());

Bytes

// RSA (RSA/ECB/OAEPWithSHA-256AndMGF1Padding)
byte[] sampleBytes = "Your message here".getBytes(StandardCharsets.UTF_8);
KeyPair result = RSAUtils.generateRSAKeyPair(RSAKeyBits.KEY_2048);
byte[] encryptedBytes = RSAUtils.encryptBytesToRSA(sampleBytes, result.getPublic());
byte[] decryptedBytes = RSAUtils.decryptRSABytes(encryptedBytes, result.getPrivate());

RSA with custom algorithm

Strings

// RSA (RSA/ECB/OAEPWithSHA-256AndMGF1Padding)
String algorithm = "RSA/None/OAEPWithSHA-256AndMGF1Padding";
String sampleString = "Your message here";
KeyPair result = RSAUtils.generateRSAKeyPair(RSAKeyBits.KEY_2048);
String encryptedMessage = RSAUtils.encryptToRSAWithAlgorithm(algorithm, sampleString, result.getPublic());
String decryptedMessage = RSAUtils.decryptRSAWithAlgorithm(algorithm, encryptedMessage, result.getPrivate());

Bytes

// RSA (RSA/ECB/OAEPWithSHA-256AndMGF1Padding)
String algorithm = "RSA/None/OAEPWithSHA-256AndMGF1Padding";
byte[] sampleBytes = "Your message here".getBytes(StandardCharsets.UTF_8);
KeyPair result = RSAUtils.generateRSAKeyPair(RSAKeyBits.KEY_2048);
byte[] encryptedBytes = RSAUtils.encryptBytesToRSAWithAlgorithm(algorithm, sampleBytes, result.getPublic());
byte[] decryptedBytes = RSAUtils.decryptRSABytesWithAlgorithm(algorithm, encryptedBytes, result.getPrivate());

Writing and reading keys to files

Writing keys to files

File publicKey = new File("rsa-public.pem");
File privateKey = new File("rsa-private.pem");
KeyPair result = RSAUtils.generateRSAKeyPair(RSAKeyBits.KEY_2048);
RSAUtils.writePublicKeyToFile(result.getPublic(), publicKey);
RSAUtils.writePublicKeyToFile(result.getPrivate(), privateKey);

Reading keys from files

File publicKeyFile = new File("rsa-public.pem");
File privateKeyFile = new File("rsa-private.pem");
PublicKey publicKey = RSAUtils.readPublicKeyFromFile(publicKeyFile);
PrivateKey privateKey = RSAUtils.readPrivateKeyFromFile(privateKeyFile);