List of usage examples for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec
public PKCS8EncodedKeySpec(byte[] encodedKey)
From source file:org.ejbca.util.keystore.KeyTools.java
/** * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is * set to 'privateKey' and the private key password is null. * * @param alias the alias used for the key entry * @param privKey RSA private key/*from w ww . j a v a 2s. co m*/ * @param cert user certificate * @param cachain CA-certificate chain or null if only one cert in chain, in that case use 'cert'. * @return KeyStore containing PKCS12-keystore * @exception Exception if input parameters are not OK or certificate generation fails */ public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert, final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException { if (log.isTraceEnabled()) { log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } // Certificate chain if (cert == null) { throw new IllegalArgumentException("Parameter cert cannot be null."); } int len = 1; if (cachain != null) { len += cachain.length; } final Certificate[] chain = new Certificate[len]; // To not get a ClassCastException we need to generate a real new certificate with BC final CertificateFactory cf = CertTools.getCertificateFactory(); chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded())); if (cachain != null) { for (int i = 0; i < cachain.length; i++) { final X509Certificate tmpcert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded())); chain[i + 1] = tmpcert; } } if (chain.length > 1) { for (int i = 1; i < chain.length; i++) { final X509Certificate cacert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded())); // Set attributes on CA-cert try { final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i]; // We construct a friendly name for the CA, and try with some parts from the DN if they exist. String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN"); // On the ones below we +i to make it unique, O might not be otherwise if (cafriendly == null) { cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O") + i; } if (cafriendly == null) { cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU" + i); } if (cafriendly == null) { cafriendly = "CA_unknown" + i; } caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(cafriendly)); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } } } // Set attributes on user-cert try { final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0]; certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); // in this case we just set the local key id to that of the public key certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(chain[0].getPublicKey())); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } // "Clean" private key, i.e. remove any old attributes final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC"); final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded())); // Set attributes for private key try { final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk; // in this case we just set the local key id to that of the public key keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(chain[0].getPublicKey())); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } // store the key and the certificate chain final KeyStore store = KeyStore.getInstance("PKCS12", "BC"); store.load(null, null); store.setKeyEntry(alias, pk, null, chain); if (log.isTraceEnabled()) { log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } return store; }
From source file:com.wwpass.connection.WWPassConnection.java
private static PKCS8EncodedKeySpec readKeyFile(String path) throws IOException { FileInputStream stream = new FileInputStream(new File(path)); try {// www . ja va2 s . c o m FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); String pem = Charset.defaultCharset().decode(bb).toString(); pem = pem.replaceFirst("-----BEGIN (RSA )?PRIVATE KEY-----\r?\n?", "") .replace("-----END (RSA )?PRIVATE KEY-----", ""); Base64 dec1 = new Base64(); byte[] encoded = dec1.decode(pem); return new PKCS8EncodedKeySpec(encoded); } finally { stream.close(); } }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is set to 'privateKey' and the private key password is * null.//from www .j av a 2 s . c o m * * @param alias * the alias used for the key entry * @param privKey * RSA private key * @param cert * user certificate * @param cachain * CA-certificate chain or null if only one cert in chain, in that case use 'cert'. * @return KeyStore containing PKCS12-keystore * @exception Exception * if input parameters are not OK or certificate generation fails */ public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert, final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException { if (log.isTraceEnabled()) { log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } // Certificate chain if (cert == null) { throw new IllegalArgumentException("Parameter cert cannot be null."); } int len = 1; if (cachain != null) { len += cachain.length; } final Certificate[] chain = new Certificate[len]; // To not get a ClassCastException we need to generate a real new certificate with BC final CertificateFactory cf = CertTools.getCertificateFactory(); chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded())); if (cachain != null) { for (int i = 0; i < cachain.length; i++) { final X509Certificate tmpcert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded())); chain[i + 1] = tmpcert; } } if (chain.length > 1) { for (int i = 1; i < chain.length; i++) { final X509Certificate cacert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded())); // Set attributes on CA-cert try { final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i]; // We construct a friendly name for the CA, and try with some parts from the DN if they exist. String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN"); // On the ones below we +i to make it unique, O might not be otherwise if (cafriendly == null) { cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O"); if (cafriendly == null) { cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU"); if (cafriendly == null) { cafriendly = "CA_unknown" + i; } else { cafriendly = cafriendly + i; } } else { cafriendly = cafriendly + i; } } caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(cafriendly)); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } } } // Set attributes on user-cert try { final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0]; certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); // in this case we just set the local key id to that of the public key certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(chain[0].getPublicKey())); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } // "Clean" private key, i.e. remove any old attributes final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC"); final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded())); // Set attributes for private key try { final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk; // in this case we just set the local key id to that of the public key keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(chain[0].getPublicKey())); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } // store the key and the certificate chain final KeyStore store = KeyStore.getInstance("PKCS12", "BC"); store.load(null, null); store.setKeyEntry(alias, pk, null, chain); if (log.isTraceEnabled()) { log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } return store; }
From source file:com.netscape.cms.servlet.test.DRMTest.java
/** * Verify the generated asymmetric key pair. * * @param keyAlgorithm - Algorithm used to generate keys. * @param privateKey - binary data of the private key. * @param publicKey - binary data of he public key. * @return/*from w w w. j a va2s .co m*/ * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws InvalidKeyException * @throws SignatureException * @throws IOException */ public static boolean isKeyPairValid(String keyAlgorithm, byte[] privateKey, byte[] publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, IOException { String algorithm = keyAlgorithm.toUpperCase(); String signingAlgorithm = "SHA1with" + algorithm; KeyFactory factory = KeyFactory.getInstance(algorithm); PrivateKey priKey = factory.generatePrivate(new PKCS8EncodedKeySpec(privateKey)); PublicKey pubKey = factory.generatePublic(new X509EncodedKeySpec(publicKey)); Signature sig = Signature.getInstance(signingAlgorithm); sig.initSign(priKey); String s = "Data to test asymmetric keys."; sig.update(s.getBytes()); // Sign the data with the private key. byte[] realSig = sig.sign(); Signature sig2 = Signature.getInstance(signingAlgorithm); sig2.initVerify(pubKey); sig2.update(s.getBytes()); // Verify the signature with the public key. return sig2.verify(realSig); }
From source file:uk.bowdlerize.API.java
@Deprecated private String SignHeaders(String dataToSign, boolean isUser) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchProviderException, SignatureException { PKCS8EncodedKeySpec spec;/* w w w .java 2 s. c o m*/ if (isUser) { spec = new PKCS8EncodedKeySpec( Base64.decode(settings.getString(SETTINGS_USER_PRIVATE_KEY, "").getBytes(), 0)); } else { spec = new PKCS8EncodedKeySpec( Base64.decode(settings.getString(SETTINGS_PROBE_PRIVATE_KEY, "").getBytes(), 0)); } KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); PrivateKey pk = kf.generatePrivate(spec); byte[] signed = null; //Log.e("algorithm", pk.getAlgorithm()); Signature instance = Signature.getInstance("SHA1withRSA"); instance.initSign(pk); instance.update(dataToSign.getBytes()); signed = instance.sign(); Log.e("privateKey", settings.getString(SETTINGS_USER_PRIVATE_KEY, "")); Log.e("privateKey", settings.getString(SETTINGS_PROBE_PRIVATE_KEY, "")); //Log.e("Signature",Base64.encodeToString(signed, Base64.NO_WRAP)); return Base64.encodeToString(signed, Base64.NO_WRAP); }
From source file:com.mhise.util.MHISEUtil.java
public static PrivateKey readKey(Context context) throws Exception { String keyFile = "privateKey.key"; FileInputStream fis = context.openFileInput(keyFile); int kl = fis.available(); byte[] kb = new byte[kl]; fis.read(kb);/*from w ww . ja v a2 s. c o m*/ fis.close(); KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(kb); PrivateKey pk = kf.generatePrivate(ks); return pk; }
From source file:org.ejbca.ui.cli.CMPKeyUpdateStressTest.java
@Override protected void execute(String[] args) { final String hostName; final String keystoreFile; final String keystorePassword; final String certNameInKeystore; final int numberOfThreads; final int waitTime; final int port; final String urlPath; final String resultFilePrefix; if (args.length < 5) { System.out.println(args[0] + " <host name> <keystore (p12)> <keystore password> <friendlyname in keystore> [<number of threads>] [<wait time (ms) between each thread is started>] [<port>] [<URL path of servlet. use 'null' to get EJBCA (not proxy) default>] [<certificate file prefix. set this if you want all received certificates stored on files>]"); System.out.println(//from ww w . j a va 2s .c o m "EJBCA build configuration requirements: cmp.operationmode=normal, cmp.allowraverifypopo=true, cmp.allowautomatickeyupdate=true, cmp.allowupdatewithsamekey=true"); // System.out.println("EJBCA build configuration optional: cmp.ra.certificateprofile=KeyId cmp.ra.endentityprofile=KeyId (used when the KeyId argument should be used as profile name)."); System.out.println( "Ejbca expects the following: There exists an end entity with a generated certificate. The end entity's certificate and its private key are stored in the keystore used " + "in the commandline. The end entity's certificate's 'friendly name' in the keystore is the one used in the command line. Such keystore can be obtained, for example, by specifying " + "the token to be 'P12' when creating the end entity and then download the keystore by choosing 'create keystore' from the public web"); return; } hostName = args[1]; keystoreFile = args[2]; keystorePassword = args[3]; certNameInKeystore = args[4]; numberOfThreads = args.length > 5 ? Integer.parseInt(args[5].trim()) : 1; waitTime = args.length > 6 ? Integer.parseInt(args[6].trim()) : 0; port = args.length > 7 ? Integer.parseInt(args[7].trim()) : 8080; // isHttp = true; urlPath = args.length > 8 && args[8].toLowerCase().indexOf("null") < 0 ? args[8].trim() : null; resultFilePrefix = args.length > 9 ? args[9].trim() : null; CryptoProviderTools.installBCProviderIfNotAvailable(); Certificate cacert = null; Certificate extracert = null; PrivateKey oldCertKey = null; FileInputStream file_inputstream; try { file_inputstream = new FileInputStream(keystoreFile); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(file_inputstream, keystorePassword.toCharArray()); Key key = keyStore.getKey(certNameInKeystore, keystorePassword.toCharArray()); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); oldCertKey = keyFactory.generatePrivate(keySpec); //extracert = keyStore.getCertificate(certNameInKeystore); Certificate[] certs = keyStore.getCertificateChain(certNameInKeystore); extracert = certs[0]; cacert = certs[1]; } catch (FileNotFoundException e2) { e2.printStackTrace(); System.exit(-1); } catch (KeyStoreException e) { e.printStackTrace(); System.exit(-1); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.exit(-1); } catch (CertificateException e) { e.printStackTrace(); System.exit(-1); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } catch (UnrecoverableKeyException e) { e.printStackTrace(); System.exit(-1); } catch (InvalidKeySpecException e) { e.printStackTrace(); System.exit(-1); } try { new StressTest(hostName, port, numberOfThreads, waitTime, urlPath, resultFilePrefix, keystorePassword, cacert, oldCertKey, extracert); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java
/** * Extracts private key from PEM contents * /*from ww w . j av a2 s. com*/ * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException */ private static PrivateKey extractPrivateKeyFromPemContents(String pemContents) throws InvalidKeySpecException, NoSuchAlgorithmException { Matcher matcher = _privateKey.matcher(pemContents); if (!matcher.find()) { throw new IllegalArgumentException("No private key found in PEM contents."); } byte[] privateKeyBytes = _base64.decode(matcher.group(1)); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance(ALGO_RSA); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; }