Developer's Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
KeyGenExample.java
package com.p6r.example11;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.crypto.Cipher;
import sun.security.tools.keytool.CertAndKeyGen;
import sun.security.x509.X500Name;
public class KeyGenExampleForDisplay {
public KeyGenExampleForDisplay() {
}
public static void main(String[] args) {
try { // [A] Get the P6R PKCS11 Provider Keystore
// -> "12345678" is the keystore's password (i.e., the PKCS11 token's PIN)
// -> "SunPKCS11-P6RPKCS11" defines the security provider
KeyStore ks = KeyStore.getInstance("PKCS11", "SunPKCS11-P6RPKCS11");
ks.load(null, "12345678".toCharArray());
// [B] Is there anything in the keystore already?
// run this test a second time and you will see the certificate created by this test case
System.out.println("Existing Certificate Chains Start\n");
java.security.cert.Certificate[] certchain = ks.getCertificateChain("example11_rsa_private_key");
if (null != certchain) {
for (java.security.cert.Certificate cert : certchain) {
System.out.println(cert.toString());
}
}
System.out.println("\nExisting Certificate Chains End\n");
// [C] Generate a RSA key pair
Key publicKey = keyPairWithCert(ks);
System.out.println("\nSearch for RSA key pair:\n");
Key privateKey = ks.getKey("example11_rsa_private_key", null);
if (privateKey != null) {
System.out.println("Key with alias 'example11_rsa_private_key' found: " + privateKey.toString());
// first encrypt the data using the RSA public key
String testData = new String("Simple string to encrypt for example12 890123456");
byte[] cipherText = encryptData(publicKey, testData.getBytes());
// second decrypt the result to verify we get the original string back
String clearText = decryptData(privateKey, cipherText);
if (!testData.equalsIgnoreCase(clearText)) {
System.out.println("\noriginal string: " + testData + "\n");
System.out.println("mismatch decrypted string: " + clearText + "\n");
} else System.out.println("\ndecrypted data matches original data: " + clearText + "\n");
} else System.out.println("Key with alias 'example11_rsa_private_key' not found\n");
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
}
private static byte[] encryptData(Key publicKey, byte[] clearText) {
byte[] cipherText = null;
try {
// with no security provider do the encrypt locally
Cipher encryptCipher = Cipher.getInstance("RSA"); //, "SunPKCS11-P6RPKCS11");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
cipherText = encryptCipher.doFinal(clearText);
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
private static String decryptData(Key privateKey, byte[] cipherText) {
byte[] clearText = null;
try {
// with no security provider do the decrypt locally
Cipher decryptCipher = Cipher.getInstance("RSA"); //, "SunPKCS11-P6RPKCS11");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
clearText = decryptCipher.doFinal(cipherText);
} catch (Exception e) {
e.printStackTrace();
}
return new String(clearText);
}
public static KeyPair generatePublicPrivateKeys(KeyPairGenerator keyGen) {
try {
SecureRandom random = SecureRandom.getInstance("PKCS11", "SunPKCS11-P6RPKCS11");
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
return pair;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
return null;
}
public static Key keyPairWithCert(KeyStore ks) {
KeyPair kp = null;
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "SunPKCS11-P6RPKCS11");
CertAndKeyGen gen = new CertAndKeyGen("RSA", "SHA1WithRSA");
gen.generate(1024);
kp = generatePublicPrivateKeys(keyGen);
System.out.println("Created public: " + kp.getPublic().toString() + "\n\nand private: " + kp.getPrivate().toString() + "\n");
X509Certificate cert = gen.getSelfCertificate(new X500Name("CN=ROOT"), (long) 365 * 24 * 3600);
X509Certificate[] chain = new X509Certificate[1];
chain[0] = cert;
// replace already existing keys under the same alias
if (ks.containsAlias("example11_rsa_public_key")) ks.deleteEntry("example11_rsa_public_key");
ks.setKeyEntry("example11_rsa_private_key", kp.getPrivate(), null, chain);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return kp.getPublic();
}
}