org.bouncycastle.openssl.PEMKeyPair Java Examples

The following examples show how to use org.bouncycastle.openssl.PEMKeyPair. 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: CertUtil.java    From littleca with Apache License 2.0 7 votes vote down vote up
/**
 * 密文pem格式私钥读取
 *
 * @param privateKeyPemPath
 * @param password
 * @return
 * @throws Exception
 */
public static PrivateKey readPrivateKeyPem(String privateKeyPemPath, String password) throws CertException {
    try {
        if (null == password) {
            throw new CertException("password can't be null ");
        }
        PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(privateKeyPemPath)));
        Object readObject = pemParser.readObject();
        if (readObject instanceof PEMEncryptedKeyPair) {
            PEMEncryptedKeyPair keyPair = (PEMEncryptedKeyPair) readObject;
            PEMDecryptorProvider keyDecryptorProvider = new BcPEMDecryptorProvider(password.toCharArray());
            PEMKeyPair decryptKeyPair = keyPair.decryptKeyPair(keyDecryptorProvider);
            return new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                    .getKeyPair(decryptKeyPair).getPrivate();
        }
        throw new CertException("read privateKey failed");
    } catch (Exception e) {
        throw new CertException("read privateKey failed", e);
    }
}
 
Example #2
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 #3
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 #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: 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 #6
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 #7
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 #8
Source File: CertificateSupplierModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
@PemFile
static PrivateKey providePemPrivateKey(@PemFile ImmutableList<Object> pemObjects) {
  JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
  Function<PEMKeyPair, PrivateKey> privateKeyConverter =
      pemKeyPair -> {
        try {
          return converter.getKeyPair(pemKeyPair).getPrivate();
        } catch (PEMException e) {
          throw new RuntimeException(
              String.format("Error converting private key: %s", pemKeyPair), e);
        }
      };
  ImmutableList<PrivateKey> privateKeys =
      filterAndConvert(pemObjects, PEMKeyPair.class, privateKeyConverter);
  checkState(
      privateKeys.size() == 1,
      "The pem file must contain exactly one private key, but %s keys are found",
      privateKeys.size());
  return privateKeys.get(0);
}
 
Example #9
Source File: JwtCreatorCallout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 6 votes vote down vote up
private static PrivateKey generatePrivateKey(PrivateKeyInfo info)
    throws InvalidKeySpecException, GeneralSecurityException, NoSuchAlgorithmException, IOException, PEMException
{
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    PEMParser pr = new PEMParser(new StringReader(new String(info.keyBytes, StandardCharsets.UTF_8)));
    Object o = pr.readObject();

    if (o == null || !((o instanceof PEMKeyPair) || (o instanceof PEMEncryptedKeyPair))) {
        throw new IllegalStateException("Didn't find OpenSSL key");
    }
    KeyPair kp;
    if (o instanceof PEMEncryptedKeyPair) {
        JcePEMDecryptorProviderBuilder bcDecProvider = new JcePEMDecryptorProviderBuilder().setProvider("BC");
        char[] charArray = info.password.toCharArray();
        PEMDecryptorProvider decProv = bcDecProvider.build(charArray);
        kp = converter.getKeyPair(((PEMEncryptedKeyPair)o).decryptKeyPair(decProv));
    }
    else {
        kp = converter.getKeyPair((PEMKeyPair)o);
    }

    PrivateKey privKey = kp.getPrivate();
    return privKey;
}
 
Example #10
Source File: PrivateKeyProvider.java    From XS2A-Sandbox with Apache License 2.0 6 votes vote down vote up
/**
 * Load private key from classpath.
 *
 * @param filename Name of the key file. Suffix should be .key
 * @return PrivateKey
 */
public PrivateKey getKeyFromClassPath(String filename) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    InputStream stream = loader.getResourceAsStream("certificates/" + filename);
    if (stream == null) {
        throw new CertificateException("Could not read private key from classpath:" + "certificates/" + filename);
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    try {
        Security.addProvider(new BouncyCastleProvider());
        PEMParser pp = new PEMParser(br);
        PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
        KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
        pp.close();
        return kp.getPrivate();
    } catch (IOException ex) {
        throw new CertificateException("Could not read private key from classpath", ex);
    }
}
 
Example #11
Source File: CertUtils.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static PrivateKey handleECKey(InputStream keyInputStream) throws IOException {
  // Let's wrap the code to a callable inner class to avoid NoClassDef when loading this class.
  try {
    return new Callable<PrivateKey>() {
      @Override
      public PrivateKey call() {
        try {
          if (Security.getProvider("BC") == null) {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
          }
          PEMKeyPair keys = (PEMKeyPair) new PEMParser(new InputStreamReader(keyInputStream)).readObject();
          return new
            JcaPEMKeyConverter().
            getKeyPair(keys).
            getPrivate();
        } catch (IOException exception) {
          exception.printStackTrace();
        }
        return null;
      }
    }.call();
  } catch (NoClassDefFoundError e) {
    throw new KubernetesClientException("JcaPEMKeyConverter is provided by BouncyCastle, an optional dependency. To use support for EC Keys you must explicitly add this dependency to classpath.");
  }
}
 
Example #12
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 #13
Source File: GPCrypto.java    From GlobalPlatformPro with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static PublicKey pem2PublicKey(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).getPublic();
        } else if (ohh instanceof SubjectPublicKeyInfo) {
            return new JcaPEMKeyConverter().getPublicKey((SubjectPublicKeyInfo) ohh);
        } else if (ohh instanceof X509CertificateHolder) {
            X509CertificateHolder certHolder = (X509CertificateHolder) ohh;
            try {
                return new JcaX509CertificateConverter().getCertificate(certHolder).getPublicKey();
            } catch (CertificateException ce) {
                throw new IllegalArgumentException("Can not read PEM: " + ce.getMessage());
            }
        } else throw new IllegalArgumentException("Can not read PEM");
    }
}
 
Example #14
Source File: KeyStoreUtil.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public static KeyPair createKeyPair(String clientKey) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
    try (Reader reader = new StringReader(clientKey)) {
        try (PEMParser pemParser = new PEMParser(reader)) {

            PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();

            byte[] pemPrivateKeyEncoded = pemKeyPair.getPrivateKeyInfo().getEncoded();
            byte[] pemPublicKeyEncoded = pemKeyPair.getPublicKeyInfo().getEncoded();

            KeyFactory factory = KeyFactory.getInstance("RSA");

            KeySpec publicKeySpec = new X509EncodedKeySpec(pemPublicKeyEncoded);
            PublicKey publicKey = factory.generatePublic(publicKeySpec);

            KeySpec privateKeySpec = new PKCS8EncodedKeySpec(pemPrivateKeyEncoded);
            PrivateKey privateKey = factory.generatePrivate(privateKeySpec);

            return new KeyPair(publicKey, privateKey);
        }
    }
}
 
Example #15
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 #16
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 #17
Source File: OcspHandler.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public OcspHandler(String responderCertPath, String responderKeyPath)
        throws OperatorCreationException, GeneralSecurityException, IOException {
    final Certificate certificate = CertificateFactory.getInstance("X509")
            .generateCertificate(X509OCSPResponderTest.class.getResourceAsStream(responderCertPath));

    chain = new X509CertificateHolder[] {new X509CertificateHolder(certificate.getEncoded())};

    final AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(certificate.getPublicKey().getEncoded());

    subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey);

    final InputStream keyPairStream = X509OCSPResponderTest.class.getResourceAsStream(responderKeyPath);

    try (final PEMParser keyPairReader = new PEMParser(new InputStreamReader(keyPairStream))) {
        final PEMKeyPair keyPairPem = (PEMKeyPair) keyPairReader.readObject();
        privateKey = PrivateKeyFactory.createKey(keyPairPem.getPrivateKeyInfo());
    }
}
 
Example #18
Source File: PEMProcessor.java    From eosio-java with MIT License 6 votes vote down vote up
/**
 * Gets the algorithm used to generate the key from its PEM format.
 *
 * @return The algorithm used to generate the key.
 * @throws PEMProcessorError if the algorithm fetch leads to an exception.
 */
@NotNull
public AlgorithmEmployed getAlgorithm() throws PEMProcessorError {

    Object pemObjectParsed = parsePEMObject();

    String oid;
    if (pemObjectParsed instanceof SubjectPublicKeyInfo) {
        oid = ((SubjectPublicKeyInfo) pemObjectParsed).getAlgorithm().getParameters()
                .toString();
    } else if (pemObjectParsed instanceof PEMKeyPair) {
        oid = ((PEMKeyPair) pemObjectParsed).getPrivateKeyInfo().getPrivateKeyAlgorithm()
                .getParameters().toString();
    } else {
        throw new PEMProcessorError(ErrorConstants.DER_TO_PEM_CONVERSION);
    }

    if (SECObjectIdentifiers.secp256r1.getId().equals(oid)) {
        return AlgorithmEmployed.SECP256R1;
    } else if (SECObjectIdentifiers.secp256k1.getId().equals(oid)) {
        return AlgorithmEmployed.SECP256K1;
    } else {
        throw new PEMProcessorError(ErrorConstants.UNSUPPORTED_ALGORITHM + oid);
    }
}
 
Example #19
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static byte[] getPublicKeyDer(String privateKeyPem) {
    try (PEMParser pemParser = new PEMParser(new StringReader(clarifyPemKey(privateKeyPem)))) {
        PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
        return pemKeyPair.getPublicKeyInfo().getEncoded();
    } catch (IOException e) {
        throw new SecurityException(e);
    }
}
 
Example #20
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 #21
Source File: KeyUtil.java    From curiostack with MIT License 5 votes vote down vote up
public static PrivateKey loadPrivateKey(byte[] encodedKey) {
  try (PEMParser parser = newParser(encodedKey)) {
    Object obj;
    while ((obj = parser.readObject()) != null) {
      if (obj instanceof PEMKeyPair) {
        return newConverter().getKeyPair((PEMKeyPair) obj).getPrivate();
      } else if (obj instanceof PrivateKeyInfo) {
        return newConverter().getPrivateKey((PrivateKeyInfo) obj);
      }
    }
    throw new IllegalStateException("Could not find private key.");
  } catch (IOException e) {
    throw new UncheckedIOException("Could not load private key.", e);
  }
}
 
Example #22
Source File: BouncyCastleSecurityProviderTool.java    From browserup-proxy with Apache License 2.0 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 #23
Source File: HttpsUtils.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Create a KeyStore from standard PEM files.
 * @param privateKeyPem the private key PEM file
 * @param certificatePem the certificate(s) PEM file
 * @param password to set to protect the private key
 */
public static KeyStore createKeyStore(InputStream certificatePem, InputStream privateKeyPem, final String password) throws Exception {
    final X509Certificate[] cert = createCertificates(certificatePem);
    final KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(null);
    // Import private key
    PEMKeyPair pem = CertUtils.getPEM(privateKeyPem);
    boolean isGM = pem.getPrivateKeyInfo().getPrivateKeyAlgorithm().getParameters().toString().equals(SM2Priv.SM2OID);

    final PrivateKey key = CertUtils.getPrivateKeyFromPEM(pem, isGM);
    keystore.setKeyEntry("tlsCertPriv", key, password.toCharArray(), cert);
    return keystore;
}
 
Example #24
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 #25
Source File: CertKeyPair.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * create cert key pair instance.
 * @param pubFile cert inputStream
 * @param privFile private key inputStream
 * @throws Exception -
 */
public CertKeyPair(InputStream pubFile, InputStream privFile) throws Exception {
    PEMKeyPair pem = CertUtils.getPEM(privFile);
    this.isGM = pem.getPrivateKeyInfo().getPrivateKeyAlgorithm().getParameters().toString().equals(SM2Priv.SM2OID);
    String pubPem = FileUtil.readFile(pubFile);
    this.privateKey = CertUtils.getPrivateKeyFromPEM(pem, isGM);
    this.publicKey = ByteUtil.toHex(pubPem.getBytes(Utils.DEFAULT_CHARSET));
}
 
Example #26
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 #27
Source File: NetconfSessionMinaImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Deprecated
private void startSession() throws IOException {
    final ConnectFuture connectFuture;
    connectFuture = client.connect(deviceInfo.name(),
            deviceInfo.ip().toString(),
            deviceInfo.port())
            .verify(connectTimeout, TimeUnit.SECONDS);
    session = connectFuture.getSession();
    //Using the device ssh key if possible
    if (deviceInfo.getKey() != null) {
        try (PEMParser pemParser = new PEMParser(new CharArrayReader(deviceInfo.getKey()))) {
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
            try {
                KeyPair kp = converter.getKeyPair((PEMKeyPair) pemParser.readObject());
                session.addPublicKeyIdentity(kp);
            } catch (IOException e) {
                throw new NetconfException("Failed to authenticate session with device " +
                        deviceInfo + "check key to be a valid key", e);
            }
        }
    } else {
        session.addPasswordIdentity(deviceInfo.password());
    }
    session.auth().verify(connectTimeout, TimeUnit.SECONDS);
    Set<ClientSession.ClientSessionEvent> event = session.waitFor(
            ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
                    ClientSession.ClientSessionEvent.CLOSED,
                    ClientSession.ClientSessionEvent.AUTHED), 0);

    if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
        log.debug("Session closed {} {}", event, session.isClosed());
        throw new NetconfException("Failed to authenticate session with device " +
                deviceInfo + "check the user/pwd or key");
    }
    openChannel();
}
 
Example #28
Source File: SslKeyStore.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private static PrivateKey fromPkcs1(byte[] content) throws Exception {
   JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
   converter.setProvider("BC");
   PEMParser pemParser = new PEMParser(new StringReader(new String(content)));

   return converter.getKeyPair((PEMKeyPair) pemParser.readObject()).getPrivate();
}
 
Example #29
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static KeyPair fromPrivateKeyPem(String privateKeyContent) {
    BufferedReader br = new BufferedReader(new StringReader(privateKeyContent));
    Security.addProvider(new BouncyCastleProvider());
    try (PEMParser pp = new PEMParser(br)) {
        PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
        return new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
    } catch (IOException e) {
        LOGGER.info("Cannot parse KeyPair from private key pem content, skip it. {}", e.getMessage(), e);
    }
    return null;
}
 
Example #30
Source File: CertUtils.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * judge is guomi cert.
 * @param pem pem inputStream
 * @return is guomi cert
 * @throws Exception -
 */
public static PEMKeyPair getPEM(InputStream pem) throws Exception {
    PEMParser pemRd = openPEMResource(pem);
    if (pemRd == null) {
        throw new Exception("Open pem error");
    }
    PEMKeyPair pemPair = (PEMKeyPair) pemRd.readObject();
    return pemPair;
}