org.bouncycastle.asn1.pkcs.PrivateKeyInfo Java Examples

The following examples show how to use org.bouncycastle.asn1.pkcs.PrivateKeyInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Ed25519PrivateKey.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Construct an Ed25519PrivateKey from a raw byte array.
 *
 * @throws BadKeyException if the key bytes are of an incorrect length for a raw
 *                         private key or private key + public key, or do not represent a DER encoded Ed25519
 *                         private key.
 */
public static Ed25519PrivateKey fromBytes(byte[] keyBytes) {
    if (keyBytes.length == Ed25519.SECRET_KEY_SIZE) {
        // if the decoded bytes matches the length of a private key, try that
        return new Ed25519PrivateKey(new Ed25519PrivateKeyParameters(keyBytes, 0));
    } else if (keyBytes.length == Ed25519.SECRET_KEY_SIZE + Ed25519.PUBLIC_KEY_SIZE) {
        // some legacy code delivers raw private and public key pairs concatted together
        return new Ed25519PrivateKey(
            // this is how we read only the first 32 bytes
            new Ed25519PrivateKeyParameters(keyBytes, 0),
            // read the remaining 32 bytes as the public key
            new Ed25519PublicKeyParameters(keyBytes, Ed25519.SECRET_KEY_SIZE));
    } else {
        // decode a properly DER-encoded private key descriptor
        PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(keyBytes);
        return fromPrivateKeyInfo(privateKeyInfo);
    }
}
 
Example #2
Source File: DockerCertificates.java    From docker-client with Apache License 2.0 6 votes vote down vote up
private PrivateKey readPrivateKey(final Path file)
    throws IOException, InvalidKeySpecException, DockerCertificateException {
  try (final BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());
       final PEMParser pemParser = new PEMParser(reader)) {

    final Object readObject = pemParser.readObject();

    if (readObject instanceof PEMKeyPair) {
      final PEMKeyPair clientKeyPair = (PEMKeyPair) readObject;
      return generatePrivateKey(clientKeyPair.getPrivateKeyInfo());
    } else if (readObject instanceof PrivateKeyInfo) {
      return generatePrivateKey((PrivateKeyInfo) readObject);
    }

    throw new DockerCertificateException("Can not generate private key from file: "
        + file.toString());
  }
}
 
Example #3
Source File: SM2CertUtil.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
public static BCECPrivateKey getPrivateKeyFromPfx(byte[] pfxDER, String passwd) throws Exception {
    InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passwd.toCharArray());
    PKCS12PfxPdu pfx = new PKCS12PfxPdu(pfxDER);

    ContentInfo[] infos = pfx.getContentInfos();
    if (infos.length != 2) {
        throw new Exception("Only support one pair ContentInfo");
    }

    for (int i = 0; i != infos.length; i++) {
        if (!infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);
            PKCS12SafeBag[] bags = dataFact.getSafeBags();
            PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
            PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
            BCECPrivateKey privateKey = BCECUtil.convertPKCS8ToECPrivateKey(info.getEncoded());
            return privateKey;
        }
    }

    throw new Exception("Not found Private Key in this pfx");
}
 
Example #4
Source File: KeyReader.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
public PKCS8EncodedKeySpec readPrivateKey(FileInputStream fis, Optional<String> keyPassword)
        throws IOException {
    PEMParser keyReader = new PEMParser(new InputStreamReader(fis));

    PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(keyPassword.get().toCharArray());

    Object keyPair = keyReader.readObject();
    keyReader.close();

    PrivateKeyInfo keyInfo;

    if (keyPair instanceof PEMEncryptedKeyPair) {
        PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptorProvider);
        keyInfo = decryptedKeyPair.getPrivateKeyInfo();
    } else {
        keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
    }

    return new PKCS8EncodedKeySpec(keyInfo.getEncoded());
}
 
Example #5
Source File: CertificateUtils.java    From docker-java with Apache License 2.0 6 votes vote down vote up
/**
 * Return private key ("key.pem") from Reader
 */
@CheckForNull
public static PrivateKey loadPrivateKey(final Reader reader) throws IOException, NoSuchAlgorithmException,
        InvalidKeySpecException {
    try (PEMParser pemParser = new PEMParser(reader)) {
        Object readObject = pemParser.readObject();
        while (readObject != null) {
            PrivateKeyInfo privateKeyInfo = getPrivateKeyInfoOrNull(readObject);
            if (privateKeyInfo != null) {
                return new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
            }
            readObject = pemParser.readObject();
        }
    }

    return null;
}
 
Example #6
Source File: PemUtils.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
public static PrivateKeyInfo readPrivateKey(Reader input, @Nullable String passphrase) throws IOException {
    final PemReader pemReader = new PemReader(input);

    PemObject readObject = null;

    for (;;) {
        PemObject nextObject = pemReader.readPemObject();

        if (nextObject == null) break;
        readObject = nextObject;

        String objType = readObject.getType();

        if (passphrase != null && !passphrase.isEmpty() && objType.equals(TYPE_ENCRYPTED_PRIVATE_KEY)) {
            return decryptPrivateKey(readObject.getContent(), passphrase);
        } else if (objType.equals(TYPE_PRIVATE_KEY)) {
            return PrivateKeyInfo.getInstance(readObject.getContent());
        }
    }

    if (readObject != null && readObject.getType().equals(TYPE_ENCRYPTED_PRIVATE_KEY)) {
        throw new BadKeyException("PEM file contained an encrypted private key but no passphrase was given");
    }

    throw new BadKeyException("PEM file did not contain a private key");
}
 
Example #7
Source File: KeyReader.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
public PKCS8EncodedKeySpec readPrivateKey(FileInputStream fis, Optional<String> keyPassword)
        throws IOException {
    PEMParser keyReader = new PEMParser(new InputStreamReader(fis));

    PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(keyPassword.get().toCharArray());

    Object keyPair = keyReader.readObject();
    keyReader.close();

    PrivateKeyInfo keyInfo;

    if (keyPair instanceof PEMEncryptedKeyPair) {
        PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptorProvider);
        keyInfo = decryptedKeyPair.getPrivateKeyInfo();
    } else {
        keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
    }

    return new PKCS8EncodedKeySpec(keyInfo.getEncoded());
}
 
Example #8
Source File: ZipUtils.java    From isu with GNU General Public License v3.0 6 votes vote down vote up
/** Read a PKCS#8 format private key. */
private static PrivateKey readPrivateKey(InputStream input)
throws IOException, GeneralSecurityException {
    try {
        byte[] buffer = new byte[4096];
        int size = input.read(buffer);
        byte[] bytes = Arrays.copyOf(buffer, size);
        /* Check to see if this is in an EncryptedPrivateKeyInfo structure. */
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
        /*
         * Now it's in a PKCS#8 PrivateKeyInfo structure. Read its Algorithm
         * OID and use that to construct a KeyFactory.
         */
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(spec.getEncoded()));
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
        return KeyFactory.getInstance(algOid).generatePrivate(spec);
    } finally {
        input.close();
    }
}
 
Example #9
Source File: Ed25519PrivateKey.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
private static Ed25519PrivateKey fromPrivateKeyInfo(PrivateKeyInfo privateKeyInfo) {
    Ed25519PrivateKeyParameters privKeyParams;
    Ed25519PublicKeyParameters pubKeyParams = null;

    try {
        ASN1Encodable privateKey = privateKeyInfo.parsePrivateKey();
        privKeyParams = new Ed25519PrivateKeyParameters(((ASN1OctetString) privateKey).getOctets(), 0);

        ASN1BitString pubKeyData = privateKeyInfo.getPublicKeyData();

        if (pubKeyData != null) {
            pubKeyParams = new Ed25519PublicKeyParameters(pubKeyData.getOctets(), 0);
        }

    } catch (IOException e) {
        throw new BadKeyException(e);
    }

    if (pubKeyParams != null) {
        return new Ed25519PrivateKey(privKeyParams, pubKeyParams);
    } else {
        return new Ed25519PrivateKey(privKeyParams);
    }
}
 
Example #10
Source File: SSLFactory.java    From ts-reaktive with MIT License 6 votes vote down vote up
/**
 * Reads a base64-format PEM key and returns a Java PrivateKey for it.
 * @param privateKey PEM-encoded private key
 */
public static PrivateKey readPrivateKey(String privateKey) {
    try (StringReader keyReader = new StringReader(privateKey);
         PEMParser pemReader = new PEMParser(keyReader)) {
        
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        Object keyPair = pemReader.readObject();
        if (keyPair instanceof PrivateKeyInfo) {
            return converter.getPrivateKey((PrivateKeyInfo) keyPair);
        } else {
            return converter.getPrivateKey(((PEMKeyPair) keyPair).getPrivateKeyInfo());
        }
    } catch (IOException x) {
        // Shouldn't occur, since we're only reading from strings
        throw new RuntimeException(x);            
    }
}
 
Example #11
Source File: BasicKeyStore.java    From env-keystore with MIT License 6 votes vote down vote up
protected static PrivateKey getPrivateKeyFromPEM(final Reader keyReader)
    throws IOException {
  final JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();

  final PEMParser pem = new PEMParser(keyReader);

  PrivateKey key;
  Object pemContent = pem.readObject();
  if (pemContent instanceof PEMKeyPair) {
    PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent;
    KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
    key = keyPair.getPrivate();
  } else if (pemContent instanceof PrivateKeyInfo) {
    PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemContent;
    key = jcaPEMKeyConverter.getPrivateKey(privateKeyInfo);
  } else {
    throw new IllegalArgumentException("Unsupported private key format '" + pemContent.getClass().getSimpleName() + '"');
  }

  pem.close();
  return key;
}
 
Example #12
Source File: PrivateKeyConverter.java    From jlogstash-input-plugin with Apache License 2.0 6 votes vote down vote up
private PrivateKey loadKeyPair() throws IOException {
    PEMParser reader = new PEMParser(file);
    Object pemObject;

    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    //PEMDecryptorProvider decryptionProv = new JcePEMDecryptorProviderBuilder().build(passphrase);

    while((pemObject = reader.readObject()) != null) {
        logger.debug("PemObject type: " + pemObject.getClass().getName());

        if(pemObject instanceof PEMKeyPair) {
            logger.debug("it match");
            PrivateKeyInfo pki = ((PEMKeyPair) pemObject).getPrivateKeyInfo();
            logger.debug("content: " + pki.getEncoded("UTF-8"));
            return converter.getPrivateKey(pki);
        } else {
            logger.debug("Dont match");
        }
    }

    logger.debug("fsdfsfs");
    return null;
}
 
Example #13
Source File: TlsHelper.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the parsed {@link KeyPair} from the provided {@link Reader}. The incoming format can be PKCS #8 or PKCS #1.
 *
 * @param pemKeyPairReader a reader with access to the serialized key pair
 * @return the key pair
 * @throws IOException if there is an error reading the key pair
 */
public static KeyPair parseKeyPairFromReader(Reader pemKeyPairReader) throws IOException {
    // Instantiate PEMParser from Reader
    try (PEMParser pemParser = new PEMParser(pemKeyPairReader)) {
        // Read the object (deserialize)
        Object parsedObject = pemParser.readObject();

        // If this is an ASN.1 private key, it's in PKCS #8 format and wraps the actual RSA private key
        if (PrivateKeyInfo.class.isInstance(parsedObject)) {
            if (isVerbose()) {
                logger.info("Provided private key is in PKCS #8 format");
            }
            PEMKeyPair keyPair = convertPrivateKeyFromPKCS8ToPKCS1((PrivateKeyInfo) parsedObject);
            return getKeyPair(keyPair);
        } else if (PEMKeyPair.class.isInstance(parsedObject)) {
            // Already in PKCS #1 format
            return getKeyPair((PEMKeyPair)parsedObject);
        } else {
            logger.warn("Expected one of %s or %s but got %s", PrivateKeyInfo.class, PEMKeyPair.class, parsedObject.getClass());
            throw new IOException("Expected private key in PKCS #1 or PKCS #8 unencrypted format");
        }
    }
}
 
Example #14
Source File: TlsHelper.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link PEMKeyPair} object with direct access to the public and private keys given a PKCS #8 private key.
 *
 * @param privateKeyInfo the PKCS #8 private key info
 * @return the PKCS #1 public and private key pair
 * @throws IOException if there is an error converting the key pair
 */
private static PEMKeyPair convertPrivateKeyFromPKCS8ToPKCS1(PrivateKeyInfo privateKeyInfo) throws IOException {
    // Parse the key wrapping to determine the internal key structure
    ASN1Encodable asn1PrivateKey = privateKeyInfo.parsePrivateKey();

    // Convert the parsed key to an RSA private key
    RSAPrivateKey keyStruct = RSAPrivateKey.getInstance(asn1PrivateKey);

    // Create the RSA public key from the modulus and exponent
    RSAPublicKey pubSpec = new RSAPublicKey(
        keyStruct.getModulus(), keyStruct.getPublicExponent());

    // Create an algorithm identifier for forming the key pair
    AlgorithmIdentifier algId = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);
    if (isVerbose()) {
        logger.info("Converted private key from PKCS #8 to PKCS #1 RSA private key");
    }

    // Create the key pair container
    return new PEMKeyPair(new SubjectPublicKeyInfo(algId, pubSpec), new PrivateKeyInfo(algId, keyStruct));
}
 
Example #15
Source File: DKIMSign.java    From james-project with Apache License 2.0 6 votes vote down vote up
private PrivateKey extractPrivateKey(InputStream rawKey, char[] passphrase) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    try (InputStreamReader pemReader = new InputStreamReader(rawKey)) {
        try (PEMParser pemParser = new PEMParser(pemReader)) {
            Object pemObject = pemParser.readObject();
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
            KeyPair keyPair;
            if (pemObject instanceof PrivateKeyInfo) {
                return converter.getPrivateKey((PrivateKeyInfo)pemObject);
            }
            if (pemObject instanceof PEMEncryptedKeyPair) {
                PEMEncryptedKeyPair pemEncryptedKeyPair = (PEMEncryptedKeyPair) pemObject;
                PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase);
                keyPair = converter.getKeyPair(pemEncryptedKeyPair.decryptKeyPair(decProv));
            } else {
                keyPair = converter.getKeyPair((PEMKeyPair) pemObject);
            }

            KeyFactory keyFac = KeyFactory.getInstance("RSA");
            RSAPrivateCrtKeySpec privateKeySpec = keyFac.getKeySpec(keyPair.getPrivate(), RSAPrivateCrtKeySpec.class);

            return keyFac.generatePrivate(privateKeySpec);
        }
    }
}
 
Example #16
Source File: TlsUtils.java    From nomad-java-sdk with Mozilla Public License 2.0 5 votes vote down vote up
private static PrivateKey loadPemKey(final String path) throws IOException {
    try (final FileInputStream in = new FileInputStream(path)) {
        try (final InputStreamReader reader = new InputStreamReader(in, US_ASCII)) {
            try (PEMParser parser = new PEMParser(reader)) {
                Object key = parser.readObject();
                if (key instanceof PEMKeyPair) {
                    return new JcaPEMKeyConverter().getKeyPair((PEMKeyPair) key).getPrivate();
                } else if (key instanceof PrivateKeyInfo) {
                    return new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) key);
                } else throw new IOException("unsupported private key format");
            }
        }
    }
}
 
Example #17
Source File: AccessTokenRetrieverServiceImpl.java    From okta-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Get Private key from input PEM file.
 *
 * @param reader
 * @return {@link PrivateKey}
 * @throws IOException
 */
PrivateKey getPrivateKeyFromPEM(Reader reader) throws IOException {
    PrivateKey privateKey;

    try (PEMParser pemParser = new PEMParser(reader)) {
        JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();
        Object pemContent = pemParser.readObject();

        if (pemContent == null) {
            throw new IllegalArgumentException("Invalid Private Key PEM file");
        }

        if (pemContent instanceof PEMKeyPair) {
            PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent;
            KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
            privateKey = keyPair.getPrivate();
        } else if (pemContent instanceof PrivateKeyInfo) {
            PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemContent;
            privateKey = jcaPEMKeyConverter.getPrivateKey(privateKeyInfo);
        } else {
            throw new IllegalArgumentException("Unsupported Private Key format '" +
                pemContent.getClass().getSimpleName() + '"');
        }
    }

    return privateKey;
}
 
Example #18
Source File: PemUtils.java    From hedera-sdk-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public static void writeEncryptedPrivateKey(PrivateKeyInfo pkInfo, Writer out, String passphrase) throws IOException {
    byte[] salt = CryptoUtils.randomBytes(CryptoUtils.SALT_LEN);

    KeyParameter derivedKey = CryptoUtils.deriveKeySha256(
        passphrase, salt, CryptoUtils.ITERATIONS, CryptoUtils.CBC_DK_LEN);

    byte[] iv = CryptoUtils.randomBytes(CryptoUtils.IV_LEN);

    Cipher cipher = CryptoUtils.initAesCbc128Encrypt(derivedKey, iv);

    byte[] encryptedKey = CryptoUtils.runCipher(cipher, pkInfo.getEncoded());

    // I wanted to just do this with BC's PKCS8Generator and KcePKCSPBEOutputEncryptorBuilder
    // but it tries to init AES instance of `Cipher` with a `PBKDF2Key` and the former complains

    // So this is basically a reimplementation of that minus the excess OO
    PBES2Parameters parameters = new PBES2Parameters(
        new KeyDerivationFunc(
            PKCSObjectIdentifiers.id_PBKDF2,
            new PBKDF2Params(
                salt,
                CryptoUtils.ITERATIONS,
                CryptoUtils.CBC_DK_LEN,
                new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA256))),
        new EncryptionScheme(NISTObjectIdentifiers.id_aes128_CBC,
            ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(
        new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, parameters),
        encryptedKey);

    PemWriter writer = new PemWriter(out);
    writer.writeObject(new PemObject(TYPE_ENCRYPTED_PRIVATE_KEY, encryptedPrivateKeyInfo.getEncoded()));
    writer.flush();
}
 
Example #19
Source File: BouncyCastleSecurityProviderTool.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
@Override
public PrivateKey decodePemEncodedPrivateKey(Reader privateKeyReader, String password) {
    try (PEMParser pemParser = new PEMParser(privateKeyReader)) {
        Object keyPair = pemParser.readObject();

        // retrieve the PrivateKeyInfo from the returned keyPair object. if the key is encrypted, it needs to be
        // decrypted using the specified password first.
        PrivateKeyInfo keyInfo;
        if (keyPair instanceof PEMEncryptedKeyPair) {
            if (password == null) {
                throw new ImportException("Unable to import private key. Key is encrypted, but no password was provided.");
            }

            PEMDecryptorProvider decryptor = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());

            PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptor);

            keyInfo = decryptedKeyPair.getPrivateKeyInfo();
        } else {
            keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
        }

        return new JcaPEMKeyConverter().getPrivateKey(keyInfo);
    } catch (IOException e) {
        throw new ImportException("Unable to read PEM-encoded PrivateKey", e);
    }
}
 
Example #20
Source File: KeyStoreUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
static PrivateKey loadPrivateKey(String keyPath) throws IOException, GeneralSecurityException {
    try (Reader reader = new FileReader(keyPath);
         PEMParser parser = new PEMParser(reader)) {
        Object readObject;
        while ((readObject = parser.readObject()) != null) {
            if (readObject instanceof PEMKeyPair) {
                PEMKeyPair keyPair = (PEMKeyPair) readObject;
                return generatePrivateKey(keyPair.getPrivateKeyInfo());
            } else if (readObject instanceof PrivateKeyInfo) {
                return generatePrivateKey((PrivateKeyInfo) readObject);
            }
        }
    }
    throw new GeneralSecurityException("Cannot generate private key from file: " + keyPath);
}
 
Example #21
Source File: AzureKeyVaultClientAuthenticator.java    From ranger with Apache License 2.0 5 votes vote down vote up
private KeyCert readPem(String path, String password) throws IOException, CertificateException, OperatorCreationException, PKCSException {
	Security.addProvider(new BouncyCastleProvider());
	PEMParser pemParser = new PEMParser(new FileReader(new File(path)));
	PrivateKey privateKey = null;
	X509Certificate cert = null;
	Object object = pemParser.readObject();
	
	while (object != null) {
		JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
		if (object instanceof X509CertificateHolder) {
			cert = new JcaX509CertificateConverter().getCertificate((X509CertificateHolder) object);
		}
		if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
			PKCS8EncryptedPrivateKeyInfo pinfo = (PKCS8EncryptedPrivateKeyInfo) object;
			InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray());
			PrivateKeyInfo info = pinfo.decryptPrivateKeyInfo(provider);
			privateKey = converter.getPrivateKey(info);
		} 
		if (object instanceof PrivateKeyInfo) {
			privateKey = converter.getPrivateKey((PrivateKeyInfo) object);
		}
		object = pemParser.readObject();
	}
	KeyCert keycert = new KeyCert();
	keycert.setCertificate(cert);
	keycert.setKey(privateKey);
	pemParser.close();
	return keycert;
}
 
Example #22
Source File: BouncyCastleOpenSSLKey.java    From swift-k with Apache License 2.0 5 votes vote down vote up
protected PrivateKey getKey(String alg, byte [] data) 
throws GeneralSecurityException {
if (alg.equals("RSA")) {
    try {
	ByteArrayInputStream bis = new ByteArrayInputStream(data);
	DERInputStream derin = new DERInputStream(bis);
	DERObject keyInfo = derin.readObject();
	
	DERObjectIdentifier rsa_oid = PKCSObjectIdentifiers.rsaEncryption;    	   
	AlgorithmIdentifier rsa = new AlgorithmIdentifier(rsa_oid);
	PrivateKeyInfo pkeyinfo = new PrivateKeyInfo(rsa, keyInfo);
	DERObject derkey = pkeyinfo.getDERObject();		
	
	byte[] keyData = BouncyCastleUtil.toByteArray(derkey);

	// The DER object needs to be mangled to 
	// create a proper ProvateKeyInfo object 
	PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyData);
	KeyFactory kfac = KeyFactory.getInstance("RSA");
	
	return kfac.generatePrivate(spec);
    } catch (IOException e) {
	// that should never happen
	return null;
    }
    
} else {
    return null;
}
   }
 
Example #23
Source File: KeyStoreUtil.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
static PrivateKey loadPrivateKey(String keyPath) throws IOException, GeneralSecurityException {
    try (Reader reader = new FileReader(keyPath);
        PEMParser parser = new PEMParser(reader)) {
        Object readObject;
        while ((readObject = parser.readObject()) != null) {
            if (readObject instanceof PEMKeyPair) {
                PEMKeyPair keyPair = (PEMKeyPair) readObject;
                return generatePrivateKey(keyPair.getPrivateKeyInfo());
            } else if (readObject instanceof PrivateKeyInfo) {
                return generatePrivateKey((PrivateKeyInfo) readObject);
            }
        }
    }
    throw new GeneralSecurityException("Cannot generate private key from file: " + keyPath);
}
 
Example #24
Source File: GPCrypto.java    From GlobalPlatformPro with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static PrivateKey pem2PrivateKey(InputStream in) throws IOException {
    try (PEMParser pem = new PEMParser(new InputStreamReader(in, StandardCharsets.US_ASCII))) {
        Object ohh = pem.readObject();
        if (ohh instanceof PEMKeyPair) {
            PEMKeyPair kp = (PEMKeyPair) ohh;
            return new JcaPEMKeyConverter().getKeyPair(kp).getPrivate();
        } else if (ohh instanceof PrivateKeyInfo) {
            return new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) ohh);
        } else throw new IllegalArgumentException("Can not read PEM");
    }
}
 
Example #25
Source File: CertificateInfo.java    From xipki with Apache License 2.0 5 votes vote down vote up
public CertificateInfo(CertWithDbId cert, PrivateKeyInfo privateKey, NameId issuer,
    X509Cert issuerCert, NameId profile, NameId requestor) {
  this.profile = Args.notNull(profile, "profile");
  this.cert = Args.notNull(cert, "cert");
  this.privateKey = privateKey;
  this.issuer = Args.notNull(issuer, "issuer");
  this.issuerCert = Args.notNull(issuerCert, "issuerCert");
  this.requestor = Args.notNull(requestor, "requestor");
}
 
Example #26
Source File: PrivateKeyCryptor.java    From xipki with Apache License 2.0 5 votes vote down vote up
PKCS8EncryptedPrivateKeyInfo encrypt(PrivateKey privateKey) {
  Args.notNull(privateKey, "privateKey");
  PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(privateKey.getEncoded());
  PKCS8EncryptedPrivateKeyInfoBuilder builder = new PKCS8EncryptedPrivateKeyInfoBuilder(
      privateKeyInfo);
  synchronized (encryptor) {
    return builder.build(encryptor);
  }
}
 
Example #27
Source File: Actions.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
protected Object execute0() throws Exception {
  EnrollCertResult result = enroll();

  X509Cert cert = null;
  PrivateKeyInfo privateKeyInfo = null;
  if (result != null) {
    String id = result.getAllIds().iterator().next();
    CertifiedKeyPairOrError certOrError = result.getCertOrError(id);
    cert = certOrError.getCertificate();
    privateKeyInfo = certOrError.getPrivateKeyInfo();
  }

  if (cert == null) {
    throw new CmdFailure("no certificate received from the server");
  }

  if (privateKeyInfo == null) {
    throw new CmdFailure("no private key received from the server");
  }

  if (StringUtil.isNotBlank(certOutputFile)) {
    saveVerbose("saved certificate to file", certOutputFile,
        encodeCert(cert.getEncoded(), certOutform));
  }

  PrivateKey privateKey = BouncyCastleProvider.getPrivateKey(privateKeyInfo);

  KeyStore ks = KeyStore.getInstance("PKCS12");
  char[] pwd = getPassword();
  ks.load(null, pwd);
  ks.setKeyEntry("main", privateKey, pwd, new Certificate[] {cert.toJceCert()});
  ByteArrayOutputStream bout = new ByteArrayOutputStream();
  ks.store(bout, pwd);
  saveVerbose("saved key to file", p12OutputFile, bout.toByteArray());

  return null;
}
 
Example #28
Source File: Actions.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
protected Object execute0() throws Exception {
  EnrollCertResult result = enroll();

  X509Cert cert = null;
  PrivateKeyInfo privateKeyInfo = null;
  if (result != null) {
    String id = result.getAllIds().iterator().next();
    CertifiedKeyPairOrError certOrError = result.getCertOrError(id);
    cert = certOrError.getCertificate();
    privateKeyInfo = certOrError.getPrivateKeyInfo();
  }

  if (cert == null) {
    throw new CmdFailure("no certificate received from the server");
  }

  if (privateKeyInfo == null) {
    throw new CmdFailure("no private key received from the server");
  }

  if (StringUtil.isNotBlank(certOutputFile)) {
    saveVerbose("saved certificate to file", certOutputFile,
        encodeCert(cert.getEncoded(), certOutform));
  }

  PrivateKey privateKey = BouncyCastleProvider.getPrivateKey(privateKeyInfo);

  KeyStore ks = KeyStore.getInstance("PKCS12");
  char[] pwd = getPassword();
  ks.load(null, pwd);
  ks.setKeyEntry("main", privateKey, pwd, new Certificate[] {cert.toJceCert()});
  ByteArrayOutputStream bout = new ByteArrayOutputStream();
  ks.store(bout, pwd);
  saveVerbose("saved key to file", p12OutputFile, bout.toByteArray());

  return null;
}
 
Example #29
Source File: X509Ca.java    From xipki with Apache License 2.0 5 votes vote down vote up
public GrantedCertTemplate(Extensions extensions, IdentifiedCertprofile certprofile,
    Date grantedNotBefore, Date grantedNotAfter, X500Name requestedSubject,
    SubjectPublicKeyInfo grantedPublicKey, PrivateKeyInfo privateKey,
    ConcurrentContentSigner signer, String warning) {
  this.extensions = extensions;
  this.certprofile = certprofile;
  this.grantedNotBefore = grantedNotBefore;
  this.grantedNotAfter = grantedNotAfter;
  this.requestedSubject = requestedSubject;
  this.grantedPublicKey = grantedPublicKey;
  this.privateKey = privateKey;
  this.signer = signer;
  this.warning = warning;
}
 
Example #30
Source File: Denominator.java    From denominator with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(Object input) {
  if (input instanceof String && input.toString().contains("BEGIN RSA PRIVATE KEY")) {
    try {
      PEMKeyPair pemKeyPair = (PEMKeyPair) new PEMParser(new StringReader(input.toString())).readObject();
      PrivateKeyInfo privateKeyInfo = pemKeyPair.getPrivateKeyInfo();
      KeyFactory keyFact = KeyFactory.getInstance(
          privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm().getId(), new BouncyCastleProvider());
      return keyFact.generatePrivate(new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded()));
    } catch (Exception ex) {
      return input;
    }
  }
  return input;
}