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
}
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");
}
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;
}
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");
}
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);
}
}
Aggregations