List of usage examples for org.bouncycastle.openssl.jcajce JcaPEMKeyConverter getPublicKey
public PublicKey getPublicKey(SubjectPublicKeyInfo publicKeyInfo) throws PEMException
From source file:co.lqnt.lockbox.key.PublicKey.java
License:Open Source License
/** * Get the JCE public key.//from ww w . j a v a 2 s .c om * * @param keyConverter The key converter to use. * * @return The JCE public key. */ public java.security.PublicKey jcePublicKey(final JcaPEMKeyConverter keyConverter) { java.security.PublicKey jcePublicKey; try { jcePublicKey = keyConverter.getPublicKey(this.bcPublicKeyInfo()); } catch (PEMException e) { throw new RuntimeException(e); } return jcePublicKey; }
From source file:com.google.examples.JOSEToolBase.java
License:Apache License
public static PublicKey decodePublicKey(String publicKeyString) throws KeyParseException { try {/*from w w w. j a v a2 s . co m*/ JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); publicKeyString = reformIndents(publicKeyString); PEMParser pemParser = new PEMParser(new StringReader(publicKeyString)); Object object = pemParser.readObject(); if (object == null) { throw new KeyParseException("unable to read anything when decoding public key"); } return converter.getPublicKey((org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) object); } catch (KeyParseException exc0) { throw exc0; } catch (Exception exc1) { throw new KeyParseException("cannot instantiate public key", exc1); } }
From source file:com.trustly.api.security.KeyChain.java
License:Open Source License
/** * Loads the Trustly public key.//ww w .j ava 2 s .c o m * @param testEnvironment whether to load the key for test environment or not. */ private void loadTrustlyPublicKey(final boolean testEnvironment) { try { final File file = testEnvironment ? new File(TEST_TRUSTLY_PUBLIC_KEY_PATH) : new File(LIVE_TRUSTLY_PUBLIC_KEY_PATH); final PEMParser pemParser = new PEMParser(new FileReader(file)); final PemObject object = pemParser.readPemObject(); final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider()); final byte[] encoded = object.getContent(); final SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(encoded)); trustlyPublicKey = converter.getPublicKey(subjectPublicKeyInfo); } catch (final IOException e) { throw new TrustlyAPIException("Failed to load Trustly public key", e); } }
From source file:com.yahoo.athenz.auth.util.Crypto.java
License:Apache License
public static PublicKey loadPublicKey(Reader r) throws CryptoException { try (org.bouncycastle.openssl.PEMParser pemReader = new org.bouncycastle.openssl.PEMParser(r)) { PublicKey pubKey = null;// w ww . ja va2s . c om Object pemObj = pemReader.readObject(); JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter(); SubjectPublicKeyInfo keyInfo = null; X9ECParameters ecParam = null; 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 Public Key ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj; ecParam = ECNamedCurveTable.getByOID(ecOID); if (ecParam == null) { throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ((ASN1ObjectIdentifier) pemObj).getId()); } pemObj = pemReader.readObject(); } else if (pemObj instanceof X9ECParameters) { ecParam = (X9ECParameters) pemObj; pemObj = pemReader.readObject(); } if (pemObj instanceof org.bouncycastle.cert.X509CertificateHolder) { keyInfo = ((org.bouncycastle.cert.X509CertificateHolder) pemObj).getSubjectPublicKeyInfo(); } else { keyInfo = (SubjectPublicKeyInfo) pemObj; } pubKey = pemConverter.getPublicKey(keyInfo); if (ecParam != null && ECDSA.equals(pubKey.getAlgorithm())) { ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed()); KeyFactory keyFactory = KeyFactory.getInstance(ECDSA, BC_PROVIDER); ECPublicKeySpec keySpec = new ECPublicKeySpec(((BCECPublicKey) pubKey).getQ(), ecSpec); pubKey = (PublicKey) keyFactory.generatePublic(keySpec); } return pubKey; } catch (PEMException e) { throw new CryptoException(e); } catch (NoSuchProviderException e) { LOG.error( "loadPublicKey: Caught NoSuchProviderException, check to make sure the provider is loaded correctly."); throw new CryptoException(e); } catch (NoSuchAlgorithmException e) { LOG.error( "loadPublicKey: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider."); throw new CryptoException(e); } catch (InvalidKeySpecException e) { LOG.error("loadPublicKey: Caught InvalidKeySpecException, invalid key spec is being used."); throw new CryptoException("InvalidKeySpecException"); } catch (IOException e) { throw new CryptoException(e); } }
From source file:com.yahoo.athenz.auth.util.Crypto.java
License:Apache License
public static String extractX509CSRPublicKey(PKCS10CertificationRequest certReq) { JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter(); PublicKey publicKey = null;/*w w w. j a v a 2 s. c o m*/ try { publicKey = pemConverter.getPublicKey(certReq.getSubjectPublicKeyInfo()); } catch (PEMException ex) { LOG.error("extractX509CSRPublicKey: unable to get public key: {}", ex.getMessage()); return null; } return convertToPEMFormat(publicKey); }
From source file:edu.wisc.doit.tcrypt.KeyReadingAndWritingTest.java
License:Apache License
@Test public void testCreateWriteAndReadBackKey() throws Exception { // Create ServiceKey final KeyPair kp = this.keysKeeper.createServiceKey("example.com", 2048, "username"); assertNotNull(kp);//from w ww .j a v a 2 s. co m // Step 3: Read ServiceKey from filesystem ServiceKey foundKey = keysKeeper.getServiceKey("example.com"); assertNotNull(foundKey); // Compare original ServiceKey content with new ServiceKey read from filesystem assertEquals("example.com", foundKey.getServiceName()); assertEquals("username", foundKey.getCreatedByNetId()); assertEquals(2048, foundKey.getKeyLength()); //Verify created in same minute assertEquals(DateTime.now().minuteOfHour().roundFloorCopy(), foundKey.getDayCreated().minuteOfHour().roundFloorCopy()); assertNotNull(foundKey.getFileEncrypter()); assertNotNull(foundKey.getTokenEncrypter()); final File keyFile = foundKey.getKeyFile(); assertNotNull(keyFile); @SuppressWarnings("resource") PEMParser pemParser = new PEMParser(new FileReader(keyFile)); Object object = pemParser.readObject(); JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); final PublicKey actualPublicKey = converter.getPublicKey((SubjectPublicKeyInfo) object); assertArrayEquals(kp.getPublic().getEncoded(), actualPublicKey.getEncoded()); }
From source file:jenkins.bouncycastle.api.PEMEncodable.java
License:Open Source License
/** * Creates a {@link PEMEncodable} by decoding PEM formated data from a {@link String} * //from w w w . j a v a2 s .c o m * @param pem {@link String} with the PEM data * @param passphrase passphrase for the encrypted PEM data. null if PEM data is not passphrase protected. The caller * is responsible for zeroing out the char[] after use to ensure the password does not stay in memory, e.g. with * <code>Arrays.fill(passphrase, (char)0)</code> * @return {@link PEMEncodable} object * @throws IOException launched if a problem exists reading the PEM information * @throws UnrecoverableKeyException in case PEM is passphrase protected and none or wrong is provided */ @Nonnull public static PEMEncodable decode(@Nonnull String pem, @Nullable final char[] passphrase) throws IOException, UnrecoverableKeyException { try (PEMParser parser = new PEMParser(new StringReader(pem));) { Object object = parser.readObject(); JcaPEMKeyConverter kConv = new JcaPEMKeyConverter().setProvider("BC"); // handle supported PEM formats. if (object instanceof PEMEncryptedKeyPair) { if (passphrase != null) { PEMDecryptorProvider dp = new JcePEMDecryptorProviderBuilder().build(passphrase); PEMEncryptedKeyPair ekp = (PEMEncryptedKeyPair) object; return new PEMEncodable(kConv.getKeyPair(ekp.decryptKeyPair(dp))); } else { throw new UnrecoverableKeyException(); } } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) { if (passphrase != null) { InputDecryptorProvider dp = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase); PKCS8EncryptedPrivateKeyInfo epk = (PKCS8EncryptedPrivateKeyInfo) object; return new PEMEncodable(kConv.getPrivateKey(epk.decryptPrivateKeyInfo(dp))); } else { throw new UnrecoverableKeyException(); } } else if (object instanceof PEMKeyPair) { return new PEMEncodable(kConv.getKeyPair((PEMKeyPair) object)); } else if (object instanceof PrivateKeyInfo) { PrivateKey pk = kConv.getPrivateKey((PrivateKeyInfo) object); // JENKINS-35661 in this case we know how to get the public key too if (pk instanceof RSAPrivateCrtKey) { // obtain public key spec from the private key RSAPrivateCrtKey rsaPK = (RSAPrivateCrtKey) pk; RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaPK.getModulus(), rsaPK.getPublicExponent()); KeyFactory kf = KeyFactory.getInstance("RSA"); return new PEMEncodable(new KeyPair(kf.generatePublic(pubKeySpec), rsaPK)); } return new PEMEncodable(pk); } else if (object instanceof SubjectPublicKeyInfo) { return new PEMEncodable(kConv.getPublicKey((SubjectPublicKeyInfo) object)); } else if (object instanceof X509CertificateHolder) { JcaX509CertificateConverter cConv = new JcaX509CertificateConverter().setProvider("BC"); return new PEMEncodable(cConv.getCertificate((X509CertificateHolder) object)); } else { throw new IOException( "Could not parse PEM, only key pairs, private keys, public keys and certificates are supported. Received " + object.getClass().getName()); } } catch (OperatorCreationException e) { throw new IOException(e.getMessage(), e); } catch (PKCSException | InvalidKeySpecException e) { LOGGER.log(Level.WARNING, "Could not read PEM encrypted information", e); throw new UnrecoverableKeyException(); } catch (CertificateException e) { throw new IOException("Could not read certificate", e); } catch (NoSuchAlgorithmException e) { throw new AssertionError( "RSA algorithm support is mandated by Java Language Specification. See https://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html"); } }
From source file:org.apache.pulsar.client.impl.MessageCrypto.java
License:Apache License
private PublicKey loadPublicKey(byte[] keyBytes) throws Exception { Reader keyReader = new StringReader(new String(keyBytes)); PublicKey publicKey = null;/*w w w . j ava 2 s. co m*/ try (org.bouncycastle.openssl.PEMParser pemReader = new org.bouncycastle.openssl.PEMParser(keyReader)) { Object pemObj = pemReader.readObject(); JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter(); SubjectPublicKeyInfo keyInfo = null; X9ECParameters ecParam = null; 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 Public Key ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj; ecParam = ECNamedCurveTable.getByOID(ecOID); if (ecParam == null) { throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ((ASN1ObjectIdentifier) pemObj).getId()); } pemObj = pemReader.readObject(); } else if (pemObj instanceof X9ECParameters) { ecParam = (X9ECParameters) pemObj; pemObj = pemReader.readObject(); } if (pemObj instanceof org.bouncycastle.cert.X509CertificateHolder) { keyInfo = ((org.bouncycastle.cert.X509CertificateHolder) pemObj).getSubjectPublicKeyInfo(); } else { keyInfo = (SubjectPublicKeyInfo) pemObj; } publicKey = pemConverter.getPublicKey(keyInfo); if (ecParam != null && ECDSA.equals(publicKey.getAlgorithm())) { ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed()); KeyFactory keyFactory = KeyFactory.getInstance(ECDSA, BouncyCastleProvider.PROVIDER_NAME); ECPublicKeySpec keySpec = new ECPublicKeySpec(((BCECPublicKey) publicKey).getQ(), ecSpec); publicKey = (PublicKey) keyFactory.generatePublic(keySpec); } } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException e) { throw new Exception(e); } return publicKey; }
From source file:org.crsh.auth.FilePublicKeyProvider.java
License:Open Source License
public Iterable<KeyPair> loadKeys() { if (!SecurityUtils.isBouncyCastleRegistered()) { throw new IllegalStateException("BouncyCastle must be registered as a JCE provider"); }/* w w w . j a v a 2s.com*/ List<KeyPair> keys = new ArrayList<KeyPair>(); for (String file : files) { try { Object o = KeyPairUtils.readKey(new InputStreamReader(new FileInputStream(file))); if (o instanceof KeyPair) { keys.add(new KeyPair(((KeyPair) o).getPublic(), null)); } else if (o instanceof PublicKey) { keys.add(new KeyPair((PublicKey) o, null)); } else if (o instanceof PEMKeyPair) { PEMKeyPair keyPair = (PEMKeyPair) o; JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); keys.add(new KeyPair(converter.getPublicKey(keyPair.getPublicKeyInfo()), null)); } } catch (Exception e) { LOG.info("Unable to read key {}: {}", file, e); } } return keys; }
From source file:org.metaeffekt.dcc.commons.pki.KeyUtils.java
License:Apache License
public static PublicKey loadPublicKey(String file) throws IOException { PEMParser parser = new PEMParser(new FileReader(file)); try {/*from w w w . j a v a 2 s . c o m*/ SubjectPublicKeyInfo pemObject = (SubjectPublicKeyInfo) parser.readObject(); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); return converter.getPublicKey(pemObject); } finally { IOUtils.closeQuietly(parser); } }