List of usage examples for java.security KeyFactory getInstance
public static KeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.wso2telco.gsma.authenticators.GSMAMSISDNAuthenticator.java
/** * Read private key from file./*w w w . ja v a2 s . c o m*/ * * @param fileName the file name * @return the private key * @throws IOException Signals that an I/O exception has occurred. * @throws NoSuchAlgorithmException the no such algorithm exception * @throws InvalidKeySpecException the invalid key spec exception */ public PrivateKey readPrivateKeyFromFile(String fileName) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { String publicK = readStringKey(fileName); //byte[] keyBytes = new BASE64Decoder().decodeBuffer(publicK); byte[] keyBytes = Base64.decodeBase64(publicK.getBytes()); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory fact = KeyFactory.getInstance("RSA"); return fact.generatePrivate(keySpec); }
From source file:com.floreantpos.license.FiveStarPOSLicenseManager.java
private final PublicKey readPublicKey(String uri) throws LicenseException { try {/*from www.j a v a 2s . c o m*/ InputStream inputStream = getClass().getResourceAsStream(uri); byte[] bytes = IOUtils.toByteArray(inputStream); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); return keyFactory.generatePublic(keySpec); } catch (Exception e) { throw new LicenseException("Invalid license key! Please contact our support.", e); } }
From source file:edu.internet2.middleware.openid.message.encoding.EncodingUtils.java
/** * Decode a DH public key.// w w w . j a v a 2 s . c o m * * @param encodedKey public key to decode * @param parameters DH parameters used in decoding * @return decoded public key * @throws NoSuchAlgorithmException if DH algorithm is unavailable * @throws InvalidKeySpecException if unable to build a valid DH key spec */ public static DHPublicKey decodePublicKey(String encodedKey, DHParameterSpec parameters) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] keyBytes = Base64.decodeBase64(encodedKey.getBytes()); DHPublicKeySpec keySpec = new DHPublicKeySpec(new BigInteger(keyBytes), parameters.getP(), parameters.getG()); KeyFactory keyFactory = KeyFactory.getInstance("DH"); return (DHPublicKey) keyFactory.generatePublic(keySpec); }
From source file:net.firejack.platform.web.security.x509.KeyUtils.java
public static Properties getProperties(byte[] key, byte[] data) { Properties properties = new Properties(); try {// w w w.ja v a 2 s . c o m KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(key); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); byte[] decrypt = decrypt(privateKey, data); InputStream stream = new ByteArrayInputStream(decrypt); properties.load(stream); } catch (Exception e) { logger.trace(e); } return properties; }
From source file:nl.b3p.viewer.stripes.CycloramaActionBean.java
private String getTIDFromBase64EncodedString(String base64Encoded, String token) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, UnsupportedEncodingException { String tid = null;//from w w w .ja v a 2 s . c om Base64 encoder = new Base64(); byte[] tempBytes = encoder.decode(base64Encoded.getBytes()); KeyFactory rsaKeyFac = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(tempBytes); RSAPrivateKey privKey = (RSAPrivateKey) rsaKeyFac.generatePrivate(encodedKeySpec); byte[] signature = sign(privKey, token); String base64 = new String(encoder.encode(signature)); tid = URLEncoder.encode(token + "&" + base64, URL_ENCODING); return tid; }
From source file:org.gluu.oxtrust.action.ManageCertificateAction.java
private KeyPair getKeyPair(String fileName) { KeyPair pair = null;//from w w w .j av a 2 s .com JCERSAPrivateCrtKey privateKey = null; PEMReader r = null; FileReader fileReader = null; File keyFile = new File(getTempCertDir() + fileName.replace("crt", "key")); if (keyFile.isFile()) { try { fileReader = new FileReader(keyFile); r = new PEMReader(fileReader, new PasswordFinder() { public char[] getPassword() { // Since keys are stored without a password this // function should not be called. return null; } }); Object keys = r.readObject(); if (keys == null) { log.error(" Unable to read keys from: " + keyFile.getAbsolutePath()); return null; } if (keys instanceof KeyPair) { pair = (KeyPair) keys; log.debug(keyFile.getAbsolutePath() + "contains KeyPair"); } else if (keys instanceof JCERSAPrivateCrtKey) { privateKey = (JCERSAPrivateCrtKey) keys; log.debug(keyFile.getAbsolutePath() + "contains JCERSAPrivateCrtKey"); BigInteger exponent = privateKey.getPublicExponent(); BigInteger modulus = privateKey.getModulus(); RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(modulus, exponent); PublicKey publicKey = null; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); publicKey = keyFactory.generatePublic(publicKeySpec); } catch (Exception e) { e.printStackTrace(); } pair = new KeyPair(publicKey, privateKey); } else { log.error(keyFile.getAbsolutePath() + " Contains unsupported key type: " + keys.getClass().getName()); return null; } } catch (IOException e) { log.error(e.getMessage(), e); return null; } finally { try { r.close(); fileReader.close(); } catch (Exception e) { log.error(e.getMessage(), e); return null; } } } else { log.error("Key file does not exist : " + keyFile.getAbsolutePath()); } log.debug("KeyPair successfully extracted from: " + keyFile.getAbsolutePath()); return pair; }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstXMsgRqstHandler.CFAstXMsgRqstLogInHandler.java
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { final String S_ProcName = "startElement"; ICFAstSchemaObj schemaObj = null;//from w w w.j a va 2 s.c o m try { // Common XML Attributes String attrId = null; // Request Attributes String attrLoginId = null; String attrDeviceName = null; String attrDevEncPWHash = null; String attrClusterName = null; String attrTenantName = null; // Attribute Extraction String attrLocalName; int numAttrs; int idxAttr; final String S_LocalName = "LocalName"; assert qName.equals("RqstLogIn"); CFAstXMsgRqstHandler xmsgRqstHandler = (CFAstXMsgRqstHandler) getParser(); if (xmsgRqstHandler == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "getParser()"); } schemaObj = xmsgRqstHandler.getSchemaObj(); if (schemaObj == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "getParser().getSchemaObj()"); } schemaObj.connect(); // Extract Attributes numAttrs = attrs.getLength(); for (idxAttr = 0; idxAttr < numAttrs; idxAttr++) { attrLocalName = attrs.getLocalName(idxAttr); if (attrLocalName.equals("Id")) { if (attrId != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrId = attrs.getValue(idxAttr); } else if (attrLocalName.equals("LoginId")) { if (attrLoginId != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrLoginId = attrs.getValue(idxAttr); } else if (attrLocalName.equals("DeviceName")) { if (attrDeviceName != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrDeviceName = attrs.getValue(idxAttr); } else if (attrLocalName.equals("DevEncPWHash")) { if (attrDevEncPWHash != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrDevEncPWHash = attrs.getValue(idxAttr); } else if (attrLocalName.equals("ClusterName")) { if (attrClusterName != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrClusterName = attrs.getValue(idxAttr); } else if (attrLocalName.equals("TenantName")) { if (attrTenantName != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrTenantName = attrs.getValue(idxAttr); } else { throw CFLib.getDefaultExceptionFactory().newUnrecognizedAttributeException(getClass(), S_ProcName, getParser().getLocationInfo(), attrLocalName); } } // Ensure that required attributes have values if ((attrLoginId == null) || (attrLoginId.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "LoginId"); } if ((attrDeviceName == null) || (attrDeviceName.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "DeviceName"); } if ((attrDevEncPWHash == null) || (attrDevEncPWHash.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "DevEncPWHash"); } if ((attrClusterName == null) || (attrClusterName.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "ClusterName"); } if ((attrTenantName == null) || (attrTenantName.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "TenantName"); } if (schemaObj.getAuthorization() != null) { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Back end database schema already authorized against database"); } if (schemaObj.isTransactionOpen()) { schemaObj.rollback(); } schemaObj.beginTransaction(); ICFAstSysClusterObj sysCluster = schemaObj.getSysClusterTableObj().readSysClusterByIdIdx(1, false); if (sysCluster == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "sysCluster"); } ICFAstClusterObj resolvedCluster = sysCluster.getRequiredContainerCluster(); if (resolvedCluster == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, "resolvedCluster"); } ICFAstSecUserObj authenticatingUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx(attrLoginId, true); if (authenticatingUser == null) { throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName, "Permission denied"); } ICFAstSecDeviceObj device = schemaObj.getSecDeviceTableObj() .readSecDeviceByIdIdx(authenticatingUser.getRequiredSecUserId(), attrDeviceName, true); if (device == null) { throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName, "Permission denied"); } String pubKey = device.getOptionalPubKey(); if ((pubKey == null) || (pubKey.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "DevicePublicKey"); } byte wrapped[] = Base64.decodeBase64(pubKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(wrapped); KeyFactory kf = KeyFactory.getInstance("RSA"); if (kf == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "kf"); } PublicKey decodedPublicKey = kf.generatePublic(x509KeySpec); if (decodedPublicKey == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "DecodedPublicKey"); } byte decodedDevEncPWHash[] = Base64.decodeBase64(attrDevEncPWHash); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); if (cipher == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "cipher"); } cipher.init(Cipher.DECRYPT_MODE, decodedPublicKey); byte decryptedPWHash[] = cipher.doFinal(decodedDevEncPWHash); MessageDigest msgDigest = MessageDigest.getInstance("SHA-512"); msgDigest.update(decryptedPWHash); byte hash[] = msgDigest.digest(); byte encodedDoubleHash[] = Base64.encodeBase64(hash); String hashedAndEncodedPassword = new String(encodedDoubleHash); if (!hashedAndEncodedPassword.equals(authenticatingUser.getRequiredPasswordHash())) { throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName, "Permission denied"); } ICFAstClusterObj useCluster = null; if (attrClusterName.equals("system")) { useCluster = schemaObj.getClusterTableObj().readClusterByUDomainNameIdx("system"); if (useCluster == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "ClusterSystem"); } attrTenantName = "system"; } else { useCluster = resolvedCluster; } ICFAstTenantObj useTenant = schemaObj.getTenantTableObj() .readTenantByUNameIdx(useCluster.getRequiredId(), attrTenantName); if (useTenant == null) { throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName, "No such tenant \"" + attrTenantName + "\""); } ICFAstSecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance(); ICFAstSecSessionEditObj editSystemSession = (ICFAstSecSessionEditObj) systemSession.beginEdit(); editSystemSession.setRequiredContainerSecUser(authenticatingUser); editSystemSession.setRequiredStart(Calendar.getInstance()); systemSession = editSystemSession.create(); editSystemSession.endEdit(); CFAstAuthorization auth = new CFAstAuthorization(); auth.setSecCluster(useCluster); auth.setSecTenant(useTenant); auth.setSecSession(systemSession); schemaObj.setAuthorization(auth); schemaObj.commit(); String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFAstXMsgSchemaMessageFormatter.formatRspnLoggedIn("\n\t\t\t", schemaObj.getSecCluster().getRequiredId(), schemaObj.getSecCluster().getRequiredFullDomainName(), schemaObj.getSecTenant().getRequiredId(), schemaObj.getSecTenant().getRequiredTenantName(), schemaObj.getSecSession().getRequiredContainerSecUser().getRequiredSecUserId(), schemaObj.getSecSession().getRequiredContainerSecUser().getRequiredLoginId(), schemaObj.getSecSession().getRequiredSecSessionId()) + "\n" + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); ((CFAstXMsgRqstHandler) getParser()).appendResponse(response); } catch (IllegalBlockSizeException e) { if (schemaObj != null) { schemaObj.rollback(); schemaObj.setAuthorization(null); } String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } catch (BadPaddingException e) { if (schemaObj != null) { schemaObj.rollback(); schemaObj.setAuthorization(null); } String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } catch (InvalidKeyException e) { if (schemaObj != null) { schemaObj.rollback(); schemaObj.setAuthorization(null); } String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } catch (NoSuchAlgorithmException e) { if (schemaObj != null) { schemaObj.rollback(); schemaObj.setAuthorization(null); } String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } catch (NoSuchPaddingException e) { if (schemaObj != null) { schemaObj.rollback(); schemaObj.setAuthorization(null); } String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } catch (InvalidKeySpecException e) { if (schemaObj != null) { schemaObj.rollback(); schemaObj.setAuthorization(null); } String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } catch (RuntimeException e) { if (schemaObj != null) { schemaObj.rollback(); schemaObj.setAuthorization(null); } String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } catch (Error e) { if (schemaObj != null) { schemaObj.rollback(); schemaObj.setAuthorization(null); } String response = CFAstXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFAstXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFAstXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFAstXMsgRqstHandler xmsgRqstHandler = ((CFAstXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } }
From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java
private RSAPublicKey decodeRsaPublicKeyFromBitString(DERBitString der) throws SpkacException { try {//from w w w . j av a 2 s .co m ASN1Sequence rsaPublicKey = ASN1Sequence.getInstance(der.getBytes()); BigInteger modulus = ((ASN1Integer) rsaPublicKey.getObjectAt(0)).getValue(); BigInteger publicExponent = ((ASN1Integer) rsaPublicKey.getObjectAt(1)).getValue(); KeyFactory keyFact = KeyFactory.getInstance("RSA"); return (RSAPublicKey) keyFact.generatePublic(new RSAPublicKeySpec(modulus, publicExponent)); } catch (GeneralSecurityException ex) { throw new SpkacException(res.getString("NoGenerateRsaPublicKeyFromSpkac.exception.message"), ex); } catch (Exception ex) { throw new SpkacException(res.getString("NoGenerateRsaPublicKeyFromSpkac.exception.message"), ex); } }
From source file:com.streamsets.pipeline.lib.http.oauth2.OAuth2ConfigBean.java
private static PrivateKey parseRSAKey(String key, Stage.Context context, List<Stage.ConfigIssue> issues) { String privKeyPEM = key.replace("-----BEGIN PRIVATE KEY-----\n", ""); privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", ""); privKeyPEM = privKeyPEM.replace("\n", ""); privKeyPEM = privKeyPEM.replace("\r", ""); try {//from w w w.j a v a 2s . co m // Base64 decode the data byte[] encoded = Base64.getDecoder().decode(privKeyPEM.getBytes()); // PKCS8 decode the encoded RSA private key PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded); KeyFactory kf = KeyFactory.getInstance(RSA); return kf.generatePrivate(keySpec); } catch (NoSuchAlgorithmException ex) { LOG.error(Utils.format("'{}' algorithm not available", RSA), ex); issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "algorithm", HTTP_25)); } catch (InvalidKeySpecException ex) { LOG.error(Utils.format("'{}' algorithm not available", RSA), ex); issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "key", HTTP_26)); } catch (IllegalArgumentException ex) { LOG.error("Invalid key", ex); issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "key", HTTP_27, ex.toString())); } return null; }
From source file:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java
/** * Load an encrypted PKCS #8 private key from the specified stream. The * encoding of the private key may be PEM or DER. * * @param is// ww w . j a v a 2 s . c o m * Stream load the encrypted private key from * @param password * Password to decrypt * @return The private key * @throws PrivateKeyUnencryptedException * If private key is unencrypted * @throws PrivateKeyPbeNotSupportedException * If private key PBE algorithm is not supported * @throws CryptoException * Problem encountered while loading the private key * @throws IOException * If an I/O error occurred */ public static PrivateKey loadEncrypted(InputStream is, Password password) throws CryptoException, IOException { byte[] streamContents = ReadUtil.readFully(is); // Check pkcs #8 is not unencrypted EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents)); if (encType == null) { // Not a valid PKCS #8 private key throw new CryptoException(res.getString("NotValidPkcs8.exception.message")); } if (encType == UNENCRYPTED) { throw new PrivateKeyUnencryptedException(res.getString("Pkcs8IsUnencrypted.exception.message")); } byte[] encPvk = null; // Check if stream is PEM encoded PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents)); if (pemInfo != null) { // It is - get DER from PEM encPvk = pemInfo.getContent(); } /* * If we haven't got the encrypted bytes via PEM then just use * stream contents directly (assume it is DER encoded) */ if (encPvk == null) { // Read in encrypted private key bytes encPvk = streamContents; } try { // Create encrypted private key information from bytes EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(encPvk); // Get wrapping algorithm String encAlg = epki.getAlgName(); // Check algorithm is supported if (!checkSupportedForDecrypt(encAlg)) { throw new PrivateKeyPbeNotSupportedException(encAlg, MessageFormat .format(res.getString("PrivateKeyWrappingAlgUnsupported.exception.message"), encAlg)); } // Create algorithm parameters and decryption key AlgorithmParameters encAlgParams = epki.getAlgParameters(); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray()); SecretKeyFactory keyFact = SecretKeyFactory.getInstance(encAlg); SecretKey pbeKey = keyFact.generateSecret(pbeKeySpec); // Create cipher to create Cipher cipher = Cipher.getInstance(encAlg); // Do decryption cipher.init(Cipher.DECRYPT_MODE, pbeKey, encAlgParams); PKCS8EncodedKeySpec privateKeySpec = epki.getKeySpec(cipher); // Get encoding of private key byte[] pvkBytes = privateKeySpec.getEncoded(); // Determine private key algorithm from key bytes String privateKeyAlgorithm = getPrivateKeyAlgorithm(pvkBytes); // Use Key Factory to create private key from encoding KeyFactory keyFactory = KeyFactory.getInstance(privateKeyAlgorithm); PrivateKey pvk = keyFactory.generatePrivate(privateKeySpec); return pvk; } catch (GeneralSecurityException ex) { throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex); } }