Search in sources :

Example 21 with JcaPEMKeyConverter

use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project athenz by yahoo.

the class Crypto method loadPrivateKey.

public static PrivateKey loadPrivateKey(Reader reader, String pwd) throws CryptoException {
    try (PEMParser pemReader = new PEMParser(reader)) {
        PrivateKey privKey = null;
        X9ECParameters ecParam = null;
        Object pemObj = pemReader.readObject();
        if (pemObj instanceof ASN1ObjectIdentifier) {
            // make sure this is EC Parameter we're handling. In which case
            // we'll store it and read the next object which should be our
            // EC Private Key
            ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj;
            ecParam = ECNamedCurveTable.getByOID(ecOID);
            // /CLOVER:OFF
            if (ecParam == null) {
                throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ((ASN1ObjectIdentifier) pemObj).getId());
            }
            // /CLOVER:ON
            pemObj = pemReader.readObject();
        } else if (pemObj instanceof X9ECParameters) {
            ecParam = (X9ECParameters) pemObj;
            pemObj = pemReader.readObject();
        }
        if (pemObj instanceof PEMKeyPair) {
            PrivateKeyInfo pKeyInfo = ((PEMKeyPair) pemObj).getPrivateKeyInfo();
            JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            privKey = pemConverter.getPrivateKey(pKeyInfo);
        // /CLOVER:OFF
        } else if (pemObj instanceof PKCS8EncryptedPrivateKeyInfo) {
            // /CLOVER:ON
            PKCS8EncryptedPrivateKeyInfo pKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemObj;
            if (pwd == null) {
                throw new CryptoException("No password specified to decrypt encrypted private key");
            }
            // Decrypt the private key with the specified password
            InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider(BC_PROVIDER).build(pwd.toCharArray());
            PrivateKeyInfo privateKeyInfo = pKeyInfo.decryptPrivateKeyInfo(pkcs8Prov);
            JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            privKey = pemConverter.getPrivateKey(privateKeyInfo);
        }
        if (ecParam != null && privKey != null && ECDSA.equals(privKey.getAlgorithm())) {
            ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed());
            KeyFactory keyFactory = KeyFactory.getInstance(getECDSAAlgo(), getKeyFactoryProvider());
            ECPrivateKeySpec keySpec = new ECPrivateKeySpec(((BCECPrivateKey) privKey).getS(), ecSpec);
            privKey = keyFactory.generatePrivate(keySpec);
        }
        return privKey;
    // /CLOVER:OFF
    } catch (PEMException e) {
        LOG.error("loadPrivateKey: Caught PEMException, problem with format of key detected.");
        throw new CryptoException(e);
    } catch (NoSuchProviderException e) {
        LOG.error("loadPrivateKey: Caught NoSuchProviderException, check to make sure the provider is loaded correctly.");
        throw new CryptoException(e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("loadPrivateKey: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider.");
        throw new CryptoException(e);
    } catch (InvalidKeySpecException e) {
        LOG.error("loadPrivateKey: Caught InvalidKeySpecException, invalid key spec is being used.");
        throw new CryptoException(e);
    } catch (OperatorCreationException e) {
        LOG.error("loadPrivateKey: Caught OperatorCreationException when creating JceOpenSSLPKCS8DecryptorProviderBuilder.");
        throw new CryptoException(e);
    } catch (PKCSException e) {
        LOG.error("loadPrivateKey: Caught PKCSException when decrypting private key.");
        throw new CryptoException(e);
    } catch (IOException e) {
        LOG.error("loadPrivateKey: Caught IOException, while trying to read key.");
        throw new CryptoException(e);
    }
// /CLOVER:ON
}
Also used : BCECPrivateKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey) ECPrivateKeySpec(org.bouncycastle.jce.spec.ECPrivateKeySpec) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) PKCSException(org.bouncycastle.pkcs.PKCSException) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) PEMException(org.bouncycastle.openssl.PEMException) PemObject(org.bouncycastle.util.io.pem.PemObject) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 22 with JcaPEMKeyConverter

use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project java by kubernetes-client.

the class SSLUtils method loadKey.

public static PrivateKey loadKey(InputStream keyInputStream, String clientKeyAlgo) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Try PKCS7 / EC
    if (clientKeyAlgo.equals("EC")) {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        PEMParser pemParser = new PEMParser(new InputStreamReader(keyInputStream));
        Object pemObject;
        while ((pemObject = pemParser.readObject()) != null) {
            if (pemObject instanceof PEMKeyPair) {
                return new JcaPEMKeyConverter().getKeyPair(((PEMKeyPair) pemObject)).getPrivate();
            }
        }
    }
    byte[] keyBytes = decodePem(keyInputStream);
    // Try PKCS1 / RSA
    if (clientKeyAlgo.equals("RSA")) {
        RSAPrivateCrtKeySpec keySpec = decodePKCS1(keyBytes);
        return KeyFactory.getInstance("RSA").generatePrivate(keySpec);
    }
    // Try PKCS8
    // TODO: There _has_ to be a better way to do this, but I spent >
    // 2 hours trying to find it and failed...
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    try {
        return KeyFactory.getInstance("RSA").generatePrivate(spec);
    } catch (InvalidKeySpecException ex) {
    // ignore if it's not RSA
    }
    try {
        return KeyFactory.getInstance("ECDSA").generatePrivate(spec);
    } catch (InvalidKeySpecException ex) {
    // ignore if it's not DSA
    }
    throw new InvalidKeySpecException("Unknown type of PKCS8 Private Key, tried RSA and ECDSA");
}
Also used : RSAPrivateCrtKeySpec(java.security.spec.RSAPrivateCrtKeySpec) PEMParser(org.bouncycastle.openssl.PEMParser) InputStreamReader(java.io.InputStreamReader) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) InvalidKeySpecException(java.security.spec.InvalidKeySpecException)

Example 23 with JcaPEMKeyConverter

use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project leopard by tanhaichao.

the class tls_sigature method CheckTLSSignature.

/**
 * @brief 校验 tls 票据
 * @param urlSig 返回 tls 票据
 * @param strAppid3rd 填写与 sdkAppid 一致的字符串形式的值
 * @param skdAppid 应的 appid
 * @param identifier 用户 id
 * @param accountType 创建应用后在配置页面上展示的 acctype
 * @param publicKey 用于校验 tls 票据的公钥内容,但是需要先将公钥文件转换为 java 原生 api 使用的格式,下面是推荐的命令
 *         openssl pkcs8 -topk8 -in ec_key.pem -outform PEM -out p8_priv.pem -nocrypt
 * @return 如果出错 CheckTLSSignatureResult 中的 verifyResult 为 false,错误信息在 errMsg,校验成功为 true
 * @throws DataFormatException
 */
@Deprecated
public static CheckTLSSignatureResult CheckTLSSignature(String urlSig, String strAppid3rd, long skdAppid, String identifier, long accountType, String publicKey) throws DataFormatException {
    CheckTLSSignatureResult result = new CheckTLSSignatureResult();
    Security.addProvider(new BouncyCastleProvider());
    // DeBaseUrl64 urlSig to json
    Base64 decoder = new Base64();
    // byte [] compressBytes = decoder.decode(urlSig.getBytes());
    byte[] compressBytes = base64_url.base64DecodeUrl(urlSig.getBytes(Charset.forName("UTF-8")));
    // System.out.println("#compressBytes Passing in[" + compressBytes.length + "] " + Hex.encodeHexString(compressBytes));
    // Decompression
    Inflater decompression = new Inflater();
    decompression.setInput(compressBytes, 0, compressBytes.length);
    byte[] decompressBytes = new byte[1024];
    int decompressLength = decompression.inflate(decompressBytes);
    decompression.end();
    String jsonString = new String(Arrays.copyOfRange(decompressBytes, 0, decompressLength));
    // System.out.println("#Json String passing in : \n" + jsonString);
    // Get TLS.Sig from json
    JSONObject jsonObject = new JSONObject(jsonString);
    String sigTLS = jsonObject.getString("TLS.sig");
    // debase64 TLS.Sig to get serailString
    byte[] signatureBytes = decoder.decode(sigTLS.getBytes(Charset.forName("UTF-8")));
    try {
        String sigTime = jsonObject.getString("TLS.time");
        String sigExpire = jsonObject.getString("TLS.expire_after");
        // + Long.parseLong(sigTime) + "-" + Long.parseLong(sigExpire));
        if (System.currentTimeMillis() / 1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) {
            result.errMessage = new String("TLS sig is out of date ");
            System.out.println("Timeout");
            return result;
        }
        // Get Serial String from json
        String SerialString = "TLS.appid_at_3rd:" + strAppid3rd + "\n" + "TLS.account_type:" + accountType + "\n" + "TLS.identifier:" + identifier + "\n" + "TLS.sdk_appid:" + skdAppid + "\n" + "TLS.time:" + sigTime + "\n" + "TLS.expire_after:" + sigExpire + "\n";
        // System.out.println("#SerialString : \n" + SerialString);
        Reader reader = new CharArrayReader(publicKey.toCharArray());
        PEMParser parser = new PEMParser(reader);
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        Object obj = parser.readObject();
        parser.close();
        PublicKey pubKeyStruct = converter.getPublicKey((SubjectPublicKeyInfo) obj);
        Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
        signature.initVerify(pubKeyStruct);
        signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
        boolean bool = signature.verify(signatureBytes);
        // System.out.println("#jdk ecdsa verify : " + bool);
        result.verifyResult = bool;
    } catch (Exception e) {
        e.printStackTrace();
        result.errMessage = "Failed in checking sig";
    }
    return result;
}
Also used : Base64(org.apache.commons.codec.binary.Base64) PublicKey(java.security.PublicKey) CharArrayReader(java.io.CharArrayReader) Reader(java.io.Reader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) IOException(java.io.IOException) DataFormatException(java.util.zip.DataFormatException) CharArrayReader(java.io.CharArrayReader) JSONObject(org.json.JSONObject) PEMParser(org.bouncycastle.openssl.PEMParser) Signature(java.security.Signature) Inflater(java.util.zip.Inflater) JSONObject(org.json.JSONObject) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 24 with JcaPEMKeyConverter

use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project karaf by apache.

the class KeyPairLoader method getKeyPair.

public static KeyPair getKeyPair(InputStream is, String password) throws GeneralSecurityException, IOException {
    try (PEMParser parser = new PEMParser(new InputStreamReader(is))) {
        Object o = parser.readObject();
        JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        if (o instanceof PEMEncryptedKeyPair) {
            if (password == null) {
                throw new GeneralSecurityException("A password must be supplied to read an encrypted key pair");
            }
            JcePEMDecryptorProviderBuilder decryptorBuilder = new JcePEMDecryptorProviderBuilder();
            PEMDecryptorProvider pemDecryptor = decryptorBuilder.build(password.toCharArray());
            o = pemConverter.getKeyPair(((PEMEncryptedKeyPair) o).decryptKeyPair(pemDecryptor));
        } else if (o instanceof PKCS8EncryptedPrivateKeyInfo) {
            if (password == null) {
                throw new GeneralSecurityException("A password must be supplied to read an encrypted key pair");
            }
            JceOpenSSLPKCS8DecryptorProviderBuilder jce = new JceOpenSSLPKCS8DecryptorProviderBuilder();
            try {
                InputDecryptorProvider decProv = jce.build(password.toCharArray());
                o = ((PKCS8EncryptedPrivateKeyInfo) o).decryptPrivateKeyInfo(decProv);
            } catch (OperatorCreationException | PKCSException ex) {
                LOGGER.debug("Error decrypting key pair", ex);
                throw new GeneralSecurityException("Error decrypting key pair", ex);
            }
        }
        if (o instanceof PEMKeyPair) {
            return pemConverter.getKeyPair((PEMKeyPair) o);
        } else if (o instanceof KeyPair) {
            return (KeyPair) o;
        } else if (o instanceof PrivateKeyInfo) {
            PrivateKey privateKey = pemConverter.getPrivateKey((PrivateKeyInfo) o);
            PublicKey publicKey = convertPrivateToPublicKey(privateKey);
            if (publicKey != null) {
                return new KeyPair(publicKey, privateKey);
            }
        }
    }
    throw new GeneralSecurityException("Failed to parse input stream");
}
Also used : KeyPair(java.security.KeyPair) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) PrivateKey(java.security.PrivateKey) InputStreamReader(java.io.InputStreamReader) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 25 with JcaPEMKeyConverter

use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project karaf by apache.

the class SshKeyFormatTest method getKeyPair.

public static KeyPair getKeyPair(InputStream is) throws GeneralSecurityException, IOException {
    try (PEMParser parser = new PEMParser(new InputStreamReader(is))) {
        Object o = parser.readObject();
        JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        return pemConverter.getKeyPair((PEMKeyPair) o);
    }
}
Also used : PEMParser(org.bouncycastle.openssl.PEMParser) InputStreamReader(java.io.InputStreamReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)

Aggregations

JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)55 PEMParser (org.bouncycastle.openssl.PEMParser)48 PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)31 PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)26 IOException (java.io.IOException)20 InputStreamReader (java.io.InputStreamReader)19 PrivateKey (java.security.PrivateKey)19 Reader (java.io.Reader)15 JcePEMDecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder)14 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)14 StringReader (java.io.StringReader)13 PEMEncryptedKeyPair (org.bouncycastle.openssl.PEMEncryptedKeyPair)13 InputStream (java.io.InputStream)12 InputDecryptorProvider (org.bouncycastle.operator.InputDecryptorProvider)12 PEMDecryptorProvider (org.bouncycastle.openssl.PEMDecryptorProvider)11 JceOpenSSLPKCS8DecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder)11 BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)10 KeyPair (java.security.KeyPair)9 PemObject (org.bouncycastle.util.io.pem.PemObject)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6