List of usage examples for org.apache.commons.ssl PKCS8Key PKCS8Key
public PKCS8Key(final byte[] encoded, char[] password) throws GeneralSecurityException, IOException
From source file:cl.nic.dte.extension.AutorizacionTypeExtensionHandler.java
@SuppressWarnings("unchecked") public static PrivateKey getPrivateKey(AutorizacionType auth, char[] password) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, IOException { List<PEMItem> items = PEMUtil.decode(auth.getRSASK().getBytes()); for (PEMItem item : items) { if ("RSA PRIVATE KEY".equals(item.pemType)) { try { PKCS8Key pkcs8 = new PKCS8Key(item.getDerBytes(), password); return Utilities.readPrivateKey(pkcs8.getDecryptedBytes(), "RSA", password); } catch (GeneralSecurityException e) { throw new InvalidKeySpecException(e); }/* ww w. ja va2s.c o m*/ } } return null; }
From source file:mx.bigdata.cfdi.security.KeyLoader.java
private static byte[] getBytes(InputStream in, char[] passwd) throws Exception { try {/* w w w .j a va2 s .co m*/ PKCS8Key pkcs8 = new PKCS8Key(in, passwd); return pkcs8.getDecryptedBytes(); } finally { in.close(); } }
From source file:com.valco.utility.FacturasUtility.java
private static java.security.PrivateKey getPrivateKey(byte[] bytesClave, String clave) throws GeneralSecurityException { PKCS8Key pkcs8 = null;/*from w w w.j a v a 2 s.c o m*/ pkcs8 = new PKCS8Key(bytesClave, clave.toCharArray()); java.security.PrivateKey pk; pk = pkcs8.getPrivateKey(); return pk; }
From source file:facturatron.facturacion.PAC.finkok.ClassicKeyLoader.java
private static byte[] getCertBytes(InputStream in, char[] passwd) throws KeyException, IOException { byte[] bytes = null; try {/*www. j av a 2 s . c om*/ PKCS8Key pkcs8 = new PKCS8Key(in, passwd); bytes = pkcs8.getDecryptedBytes(); } catch (GeneralSecurityException e) { throw new KeyException("La contrasea del certificado no es correcta", e.getCause()); } finally { in.close(); } return bytes; }
From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java
/** * Mtodo que valida el password y que la llave privada corresponda a la * llave publica// ww w . ja v a2s . c o m * * @return true si el password y llave privada corresponden, en otro caso * false */ public boolean validaCorrespondencias() { try { PKCS8Key pkcs8 = new PKCS8Key(this.clavePrivada, this.password.toCharArray()); //valida el pass PrivateKey pk = pkcs8.getPrivateKey(); //valida que la llave privada corresponda a la llave publica X509Certificate cert = X509Certificate.getInstance(this.clavePublica); Signature firma = Signature.getInstance("SHA1withRSA"); firma.initSign(pk); byte[] firmado = firma.sign(); firma.initVerify(cert.getPublicKey()); if (firma.verify(firmado)) { return this.correcto; } else { return this.error; } } catch (GeneralSecurityException e) { return this.error; } catch (CertificateException e) { return this.error; } }
From source file:fr.aliasource.webmail.common.message.Mime4jFormatter.java
private PrivateKey loadPK() { PrivateKey privateKey = null; File f = new File("/etc/minig/dkim_pk.pem"); if (!f.exists()) { return privateKey; }// ww w.j a v a 2 s. c o m try { PKCS8Key pkcs8 = new PKCS8Key(new FileInputStream(f), null); privateKey = pkcs8.getPrivateKey(); } catch (Exception e) { logger.error("Error loading private key for DKIM signing", e); } return privateKey; }
From source file:com.ibm.mqlight.api.security.KeyStoreUtils.java
/** * Creates a {@link PrivateKey} instance from the passed private key PEM format file and certificate chain. * * @param pemKeyFile//from w ww . ja v a2 s . c om * A PEM format file containing the private key. * @param passwordChars * The password that protects the private key. * @return the private key, created by this method. * @throws IOException if the file cannot be read. * @throws GeneralSecurityException if a cryptography problem is encountered. */ public static PrivateKey createPrivateKey(File pemKeyFile, char[] passwordChars) throws IOException, GeneralSecurityException { final String methodName = "createPrivateKey"; logger.entry(methodName, pemKeyFile); // Read the private key from the PEM format file final PemFile privateKeyPemFile = new PemFile(pemKeyFile); final byte[] privateKeyBytes = privateKeyPemFile.getPrivateKeyBytes(); final PrivateKey privateKey; if (privateKeyPemFile.containsEncryptedPrivateKey()) { // We should be able to do the follows (using standard JDK classes): // EncryptedPrivateKeyInfo encryptPrivateKeyInfo = new EncryptedPrivateKeyInfo(privateKeyBytes); // Cipher cipher = Cipher.getInstance(encryptPrivateKeyInfo.getAlgName()); // PBEKeySpec pbeKeySpec = new PBEKeySpec(passwordChars); // SecretKeyFactory secFac = SecretKeyFactory.getInstance(encryptPrivateKeyInfo.getAlgName()); // Key pbeKey = secFac.generateSecret(pbeKeySpec); // AlgorithmParameters algParams = encryptPrivateKeyInfo.getAlgParameters(); // cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams); // KeySpec keySpec = encryptPrivateKeyInfo.getKeySpec(cipher); // privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec); // but this can fail with a: "Unsupported key protection algorithm" if key was generated with openssl // // Instead we use the Apache commons SSL PKCS8Key class from Julius Davies (see not-yet-commons-ssl in Maven) // which seems more reliable final PKCS8Key key = new PKCS8Key(privateKeyBytes, passwordChars); privateKey = key.getPrivateKey(); } else { final KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); InvalidKeySpecException keyFactoryException = null; PrivateKey key = null; for (String alg : new String[] { "RSA", "DSA", "DiffieHellman", "EC" }) { try { key = KeyFactory.getInstance(alg).generatePrivate(keySpec); break; } catch (InvalidKeySpecException e) { if (keyFactoryException == null) keyFactoryException = e; } } if (key == null) throw keyFactoryException; privateKey = key; } logger.exit(methodName, privateKey); return privateKey; }
From source file:org.apache.james.jdkim.mailets.DKIMSign.java
public void init() throws MessagingException { signatureTemplate = getInitParameter("signatureTemplate"); String privateKeyString = getInitParameter("privateKey"); String privateKeyPassword = getInitParameter("privateKeyPassword", null); forceCRLF = getInitParameter("forceCRLF", true); try {//from w w w.j a va 2 s. co m PKCS8Key pkcs8 = new PKCS8Key(new ByteArrayInputStream(privateKeyString.getBytes()), privateKeyPassword != null ? privateKeyPassword.toCharArray() : null); privateKey = pkcs8.getPrivateKey(); // privateKey = DKIMSigner.getPrivateKey(privateKeyString); } catch (NoSuchAlgorithmException e) { throw new MessagingException("Unknown private key algorythm: " + e.getMessage(), e); } catch (InvalidKeySpecException e) { throw new MessagingException( "PrivateKey should be in base64 encoded PKCS8 (der) format: " + e.getMessage(), e); } catch (GeneralSecurityException e) { throw new MessagingException("General security exception: " + e.getMessage(), e); } }
From source file:org.apache.karaf.itests.ssh.SshKeyFormatTest.java
@Test public void usePemKey() throws Exception { SshClient client = SshClient.setUpDefaultClient(); URL testPemURL = Resources.getResource(SshKeyFormatTest.class, "test.pem"); ByteSource source = Resources.asByteSource(testPemURL); PKCS8Key pkcs8 = new PKCS8Key(source.openStream(), null); String sshPort = getSshPort(); client.setServerKeyVerifier(new RequiredServerKeyVerifier(pkcs8.getPublicKey())); client.start();//from w w w . j av a 2s.c o m ConnectFuture future = client.connect("karaf", "localhost", Integer.parseInt(sshPort)); future.await(); ClientSession session = future.getSession(); Set<ClientSessionEvent> ret = EnumSet.of(ClientSessionEvent.WAIT_AUTH); while (ret.contains(ClientSessionEvent.WAIT_AUTH)) { session.addPasswordIdentity("karaf"); session.auth().verify(); ret = session.waitFor( EnumSet.of(ClientSessionEvent.WAIT_AUTH, ClientSessionEvent.CLOSED, ClientSessionEvent.AUTHED), 0); } if (ret.contains(ClientSessionEvent.CLOSED)) { throw new Exception("Could not open SSH channel"); } session.close(true); }
From source file:org.apache.karaf.shell.ssh.keygenerator.OpenSSHGeneratorKeyFileProviderTest.java
@Test public void convertSimpleKey() throws Exception { File temp = File.createTempFile(this.getClass().getCanonicalName(), ".pem"); temp.deleteOnExit();/*www .j a v a 2 s .c o m*/ SimpleGeneratorHostKeyProvider simpleGenerator = new SimpleGeneratorHostKeyProvider(temp); simpleGenerator.setKeySize(2048); simpleGenerator.setAlgorithm("DSA"); List<KeyPair> keys = simpleGenerator.loadKeys(); KeyPair simpleKeyPair = keys.stream().findFirst().get(); Assert.assertEquals("DSA", simpleKeyPair.getPrivate().getAlgorithm()); OpenSSHKeyPairProvider provider = new OpenSSHKeyPairProvider(temp, "DSA", 2048); KeyPair convertedKeyPair = provider.loadKeys().iterator().next(); Assert.assertEquals("DSA", convertedKeyPair.getPrivate().getAlgorithm()); Assert.assertArrayEquals(simpleKeyPair.getPrivate().getEncoded(), convertedKeyPair.getPrivate().getEncoded()); Assert.assertArrayEquals(simpleKeyPair.getPublic().getEncoded(), convertedKeyPair.getPublic().getEncoded()); //also test that the original file has been replaced PKCS8Key pkcs8 = new PKCS8Key(Files.newInputStream(temp.toPath()), null); KeyPair keyPair = new KeyPair(pkcs8.getPublicKey(), pkcs8.getPrivateKey()); Assert.assertArrayEquals(simpleKeyPair.getPrivate().getEncoded(), keyPair.getPrivate().getEncoded()); }