/** 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(); } }
/** * Basic constructor - specify the contents of the PKIArchiveControl structure. * * @param privateKeyInfo the private key to be archived. * @param generalName the general name to be associated with the private key. */ public PKIArchiveControlBuilder(PrivateKeyInfo privateKeyInfo, GeneralName generalName) { EncKeyWithID encKeyWithID = new EncKeyWithID(privateKeyInfo, generalName); try { this.keyContent = new CMSProcessableByteArray(CRMFObjectIdentifiers.id_ct_encKeyWithID, encKeyWithID.getEncoded()); } catch (IOException e) { throw new IllegalStateException("unable to encode key and general name info"); } this.envGen = new CMSEnvelopedDataGenerator(); }
public PrivateKeyInfo decryptPrivateKeyInfo(InputDecryptorProvider inputDecryptorProvider) throws PKCSException { try { InputDecryptor decrytor = inputDecryptorProvider.get(encryptedPrivateKeyInfo.getEncryptionAlgorithm()); ByteArrayInputStream encIn = new ByteArrayInputStream(encryptedPrivateKeyInfo.getEncryptedData()); return PrivateKeyInfo.getInstance(Streams.readAll(decrytor.getInputStream(encIn))); } catch (Exception e) { throw new PKCSException("unable to read encrypted data: " + e.getMessage(), e); } }
private EncKeyWithID(ASN1Sequence seq) { this.privKeyInfo = PrivateKeyInfo.getInstance(seq.getObjectAt(0)); if (seq.size() > 1) { if (!(seq.getObjectAt(1) instanceof DERUTF8String)) { this.identifier = GeneralName.getInstance(seq.getObjectAt(1)); } else { this.identifier = (ASN1Encodable)seq.getObjectAt(1); } } else { this.identifier = null; } }
protected PrivateKey engineGeneratePrivate( KeySpec keySpec) throws InvalidKeySpecException { if (keySpec instanceof PKCS8EncodedKeySpec) { try { PrivateKeyInfo info = PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()); PrivateKey key = BouncyCastleProvider.getPrivateKey(info); if (key != null) { return key; } throw new InvalidKeySpecException("no factory found for OID: " + info.getPrivateKeyAlgorithm().getAlgorithm()); } catch (Exception e) { throw new InvalidKeySpecException(e.toString()); } } throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName()); }
BCGOST3410PrivateKey( PrivateKeyInfo info) throws IOException { GOST3410PublicKeyAlgParameters params = new GOST3410PublicKeyAlgParameters((ASN1Sequence)info.getAlgorithmId().getParameters()); ASN1OctetString derX = ASN1OctetString.getInstance(info.parsePrivateKey()); byte[] keyEnc = derX.getOctets(); byte[] keyBytes = new byte[keyEnc.length]; for (int i = 0; i != keyEnc.length; i++) { keyBytes[i] = keyEnc[keyEnc.length - 1 - i]; // was little endian } this.x = new BigInteger(1, keyBytes); this.gost3410Spec = GOST3410ParameterSpec.fromPublicKeyAlg(params); }
public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) throws IOException { ASN1ObjectIdentifier algOid = keyInfo.getPrivateKeyAlgorithm().getAlgorithm(); if (algOid.equals(PKCSObjectIdentifiers.dhKeyAgreement)) { return new BCDHPrivateKey(keyInfo); } else if (algOid.equals(X9ObjectIdentifiers.dhpublicnumber)) { return new BCDHPrivateKey(keyInfo); } else { throw new IOException("algorithm identifier " + algOid + " in key not recognised"); } }
protected PrivateKey engineGeneratePrivate( KeySpec keySpec) throws InvalidKeySpecException { if (keySpec instanceof PKCS8EncodedKeySpec) { try { return generatePrivate(PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded())); } catch (Exception e) { throw new InvalidKeySpecException("encoded key spec not recognised"); } } else { throw new InvalidKeySpecException("key spec not recognised"); } }
public PrivateKey generatePrivate(PrivateKeyInfo info) throws IOException { ASN1ObjectIdentifier algOid = info.getPrivateKeyAlgorithm().getAlgorithm(); if (algOid.equals(PKCSObjectIdentifiers.dhKeyAgreement)) { return new BCElGamalPrivateKey(info); } else if (algOid.equals(X9ObjectIdentifiers.dhpublicnumber)) { return new BCElGamalPrivateKey(info); } else if (algOid.equals(OIWObjectIdentifiers.elGamalAlgorithm)) { return new BCElGamalPrivateKey(info); } else { throw new IOException("algorithm identifier " + algOid + " in key not recognised"); } }
public PrivateKey getPrivateKey(PrivateKeyInfo privateKeyInfo) throws PEMException { try { String algorithm = privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm().getId(); if (X9ObjectIdentifiers.id_ecPublicKey.getId().equals(algorithm)) { algorithm = "ECDSA"; } KeyFactory keyFactory = helper.createKeyFactory(algorithm); return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded())); } catch (Exception e) { throw new PEMException("unable to convert key pair: " + e.getMessage(), e); } }
public Object parseObject(PemObject obj) throws IOException { try { PrivateKeyInfo info = PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(obj.getContent())); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(obj.getContent()); KeyFactory keyFact = KeyFactory.getInstance(info.getPrivateKeyAlgorithm().getAlgorithm().getId(), provider); return keyFact.generatePrivate(keySpec); } catch (Exception e) { throw new PEMException("problem parsing PRIVATE KEY: " + e.toString(), e); } }
static PrivateKey generate(Path path) throws IOException { try (Reader in = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { PEMParser parser = new PEMParser(in); Object keyPair = parser.readObject(); if (!(keyPair instanceof PEMKeyPair)) { throw new IllegalStateException(String.format("%s contains an artifact that is not a key pair: %s", path, keyPair)); } PrivateKeyInfo privateKeyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo(); if (privateKeyInfo == null) { throw new IllegalStateException(String.format("%s does not contain a private key", path)); } return CONVERTER.getPrivateKey(privateKeyInfo); } }
/** * 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); } }
private 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; }
public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) throws IOException { ASN1ObjectIdentifier algOid = keyInfo.getPrivateKeyAlgorithm().getAlgorithm(); if (RSAUtil.isRsaOid(algOid)) { RSAPrivateKey rsaPrivKey = RSAPrivateKey.getInstance(keyInfo.parsePrivateKey()); if (rsaPrivKey.getCoefficient().intValue() == 0) { return new BCRSAPrivateKey(rsaPrivKey); } else { return new BCRSAPrivateCrtKey(keyInfo); } } else { throw new IOException("algorithm identifier " + algOid + " in key not recognised"); } }
private void populateFromPrivKeyInfo(PrivateKeyInfo info) throws IOException { X962Parameters params = X962Parameters.getInstance(info.getPrivateKeyAlgorithm().getParameters()); ECCurve curve = EC5Util.getCurve(configuration, params); ecSpec = EC5Util.convertToSpec(params, curve); ASN1Encodable privKey = info.parsePrivateKey(); if (privKey instanceof ASN1Integer) { ASN1Integer derD = ASN1Integer.getInstance(privKey); this.d = derD.getValue(); } else { org.bouncycastle.asn1.sec.ECPrivateKey ec = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(privKey); this.d = ec.getKey(); this.publicKey = ec.getPublicKey(); } }
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; }
/** * <p> * Encode (serialise) a private key in order to store it or transport it over a network. * </p><p> * <b>Important: You should keep your private key secret!</b> Thus, you might want to encrypt the result before * storing it to a file or sending it somewhere! * </p> * @param privateKey the private key to be encoded; must not be <code>null</code>. * @return the encoded (serialised) form of the private key. Can be passed to {@link #decodePrivateKey(byte[])} to * reverse this method. * @see #decodePrivateKey(byte[]) * @see #encodePublicKey(CipherParameters) */ public byte[] encodePrivateKey(final CipherParameters privateKey) { if (privateKey == null) throw new IllegalArgumentException("privateKey == null"); // TODO use a class-based map or similar registry! try { if (privateKey instanceof RSAPrivateCrtKeyParameters) { final RSAPrivateCrtKeyParameters rsaPrivateKey = (RSAPrivateCrtKeyParameters) privateKey; final PrivateKeyInfo info = new PrivateKeyInfo( new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPrivateKey( rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent(), rsaPrivateKey.getExponent(), rsaPrivateKey.getP(), rsaPrivateKey.getQ(), rsaPrivateKey.getDP(), rsaPrivateKey.getDQ(), rsaPrivateKey.getQInv()).toASN1Primitive() ); return info.getEncoded(); } } catch (final IOException x) { throw new RuntimeException(x); } throw new UnsupportedOperationException("privateKey.class=\"" + privateKey.getClass().getName() + "\" not yet supported!"); }
public static PrivateKey readPrivateKey(Reader reader) throws IOException { try (PEMParser parser = new PEMParser(reader)) { Object object = parser.readObject(); if (!(object instanceof PEMKeyPair)) throw new IOException("File does not contain a key"); PEMKeyPair pair = (PEMKeyPair) object; // TODO merge messy conversion logic with that below */ AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(pair.getPrivateKeyInfo()); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(privateKey); KeyFactory keyFactory = new DefaultJcaJceHelper().createKeyFactory("RSA"); // TODO should we really assume RSA? return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded())); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { throw new IOException(ex); } }
/** * 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; }
private PrivateKey readPrivateKey(String privateKeyPath, String keyPassword) throws IOException { FileReader fileReader = new FileReader(privateKeyPath); PEMParser keyReader = new PEMParser(fileReader); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); PEMDecryptorProvider decryptionProv = new JcePEMDecryptorProviderBuilder().build(keyPassword.toCharArray()); Object keyPair = keyReader.readObject(); PrivateKeyInfo keyInfo; if (keyPair instanceof PEMEncryptedKeyPair) { PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptionProv); keyInfo = decryptedKeyPair.getPrivateKeyInfo(); } else { keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo(); } keyReader.close(); return converter.getPrivateKey(keyInfo); }