Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

RSA Encrypt RSA/ECB/OAEPWithSHA1AndMGF1Padding

See more RSA Examples

Demonstrates how to RSA encrypt using RSA/ECB/OAEPWithSHA1AndMGF1Padding. Also demonstrates RSA/ECB/OAEPWithSHA-256AndMGF1Padding. Both of these terms are from Java's JCE. Note: In this context, "ECB" doesn't actually mean anything. It's a symmetric cipher mode that doesn't apply (or make sense) in this context.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.PrivateKey;
import com.chilkatsoft.chilkat2.PublicKey;
import com.chilkatsoft.chilkat2.Rsa;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example assumes the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        Rsa rsa = new Rsa();

        // First load a public key object with a public key.
        // In this case, we'll load it from a file.
        PublicKey pubkey = new PublicKey();
        try {
            pubkey.loadFromFile("qa_data/pem/rsa_public.pem");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // RSA encryption is limited to small amounts of data. The limit
        // is typically a few hundred bytes and is based on the key size and
        // padding (OAEP vs. PKCS1_5).  RSA encryption is typically used for
        // encrypting hashes or symmetric (bulk encryption algorithm) secret keys.
        String plainText = "Time is an illusion. Lunchtime doubly so.";

        // Import the public key to be used for encrypting.
        rsa.usePublicKey(pubkey);

        // To get OAEP padding, set the PkcsPadding property equal to false
        rsa.setPkcsPadding(false);
        rsa.setOaepHash("sha256");

        // Indicate we'll want hex output
        rsa.setEncodingMode("hex");

        // Encrypt..
        boolean usePrivateKey = false;
        String encryptedStr = rsa.encryptStringENC(plainText, usePrivateKey);
        System.out.println(encryptedStr);

        // -------------------------------------------------
        // Now decrypt with the matching private key.
        Rsa rsa2 = new Rsa();

        PrivateKey privKey = new PrivateKey();
        try {
            privKey.loadEncryptedPem("qa_data/pem/rsa_passwd.pem", "passwd");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        rsa2.usePrivateKey(privKey);

        // Make sure we have the same settings used for encryption.
        rsa2.setPkcsPadding(false);
        rsa2.setEncodingMode("hex");
        rsa2.setOaepHash("sha256");

        String originalStr = rsa2.decryptStringENC(encryptedStr, true);

        System.out.println(originalStr);
    }
}