An example of using RSA to encrypt a single asymmetric key. : RSA algorithm « Security « Java Tutorial






import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class MainClass {
  public static void main(String[] args) throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(128);
    Key blowfishKey = keyGenerator.generateKey();

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.genKeyPair();

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());

    byte[] blowfishKeyBytes = blowfishKey.getEncoded();
    System.out.println(new String(blowfishKeyBytes));
    byte[] cipherText = cipher.doFinal(blowfishKeyBytes);
    System.out.println(new String(cipherText));
    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

    byte[] decryptedKeyBytes = cipher.doFinal(cipherText);
    System.out.println(new String(decryptedKeyBytes));
    SecretKey newBlowfishKey = new SecretKeySpec(decryptedKeyBytes, "Blowfish");
  }
}








36.38.RSA algorithm
36.38.1.Basic RSA example.
36.38.2.RSA example with random key generation.
36.38.3.RSA example with PKCS #1 Padding.
36.38.4.RSA example with OAEP Padding and random key generation.
36.38.5.An example of using RSA to encrypt a single asymmetric key.
36.38.6.Simple Digital Signature Example
36.38.7.Creates a 1024 bit RSA key pair and stores it to the filesystem as two files
36.38.8.RSA Signature Generation
36.38.9.An RSA sample application