Encryption & Decryption

The following Java encryption examples use the Spongy Castle library.

Encrypt Message

Encrypt message using RSA public key with PKCS1-OAEP padding:

private byte[] encryptWithPublicKey(byte[] message, String publicKey) throws Exception {
    String strippedKey = Crypto.stripPublicKeyHeaders(publicKey);
    PublicKey apiPublicKey= Crypto.getRSAPublicKeyFromString(strippedKey);
    Cipher rsaCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "SC");
    rsaCipher.init(Cipher.ENCRYPT_MODE, apiPublicKey);
    return rsaCipher.doFinal(message);
}

Decrypt Package

Decrypt a package using RSA private key with PKCS1-OAEP padding:

public static byte[] decryptWithPrivateKey(byte[] message, String privateKey) throws Exception {
    PrivateKey pKey = getRSAPrivateKeyFromString(privateKey);
    Cipher rsaCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "SC");
    rsaCipher.init(Cipher.DECRYPT_MODE, pKey);
    return rsaCipher.doFinal(message);
}

User Contributed

LaunchKey links to user contributed code as a resource to its community. LaunchKey does not in any way guarantee or warrant the quality and security of these code bases. User contributed code is supported by the creators. If you do find a link from the site to user contributed code that is malicious or inappropriate in any way, please report that link to LaunchKey immediately and we will investigate the claim. Submit any issue to LaunchKey support at https://launchkey.com./support. ×