import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.security.Key; import java.security.KeyStore; import java.security.Provider; import java.security.Security; import java.security.cert.Certificate; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class How2Unwrap { // Keystore Settings private static final String MERCHANT_CERTIFICATE_ALIAS = "TLGcertificate"; private static final String KEYSTORE_FILENAME = "devteststore"; private static final String KEYSTORE_PASSWORD = "espayment"; private static final String KEYSTORE_TYPE = "JCEKS"; // Encryption Defaults private static final String CIPHER_ALGORITHM = "AES"; private static final String WRAP_ALGORITHM = "RSA/ECB/OAEPWithSHA1AndMGF1Padding"; private static final int CIPHER_KEY_SIZE = 256; // Security Providers private static final String SECURITY_PROVIDER_CLASS = "org.bouncycastle.jce.provider.BouncyCastleProvider"; private static final String SECURITY_PROVIDER = "BC"; private static final String JCE_PROVIDER = "SunJCE"; public static void main(String[] args) throws Exception { Security.addProvider((Provider)Class.forName(SECURITY_PROVIDER_CLASS).newInstance()); // 1/ generate a session key to be wrapped KeyGenerator generator = KeyGenerator.getInstance(CIPHER_ALGORITHM, SECURITY_PROVIDER); generator.init(CIPHER_KEY_SIZE); SecretKey keyToBeWrapped = generator.generateKey(); System.out.println("==> Generated key: "+ new String(keyToBeWrapped.getEncoded())); // 2/ Get certificate to use it as a wrapping key // - Read the Keystore InputStream storeStream = new BufferedInputStream(new FileInputStream(KEYSTORE_FILENAME)); KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE, JCE_PROVIDER); keyStore.load(storeStream, KEYSTORE_PASSWORD.toCharArray()); storeStream.close(); // - get certificate Certificate wrapCertificate = keyStore.getCertificate(MERCHANT_CERTIFICATE_ALIAS); Key wrappingKey = wrapCertificate.getPublicKey(); // 3/ Wrap session key using the merchant certificate // - Prepare a wrapper Cipher cipherUsingCertificate = Cipher.getInstance(WRAP_ALGORITHM, SECURITY_PROVIDER); // - wrap now // cipherUsingCertificate.init(Cipher.WRAP_MODE, wrapCertificate); cipherUsingCertificate.init(Cipher.WRAP_MODE, wrappingKey); byte[] certificateWrappedKey = cipherUsingCertificate.wrap(keyToBeWrapped); System.out.println("==> Same wrapped : " + new String(certificateWrappedKey)); // 4/ unwrap the wrapped key // cipherUsingCertificate.init(Cipher.UNWRAP_MODE, wrapCertificate); cipherUsingCertificate.init(Cipher.UNWRAP_MODE, wrappingKey); Key key2 = cipherUsingCertificate.unwrap(certificateWrappedKey, WRAP_ALGORITHM, Cipher.SECRET_KEY); System.out.println("==> Same unwrapped: " + new String(key2.getEncoded())); } }