List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME
String PROVIDER_NAME
To view the source code for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.
Click Source Link
From source file:com.guardtime.tsp.Verifier.java
License:Apache License
private static GTVerificationResult verifyPkSignature(TimeSignature timeSignature, PublicKey publicKey) { GTVerificationResult result = new GTVerificationResult(); // Check arguments if (publicKey == null) { return result; }/* ww w .j a va 2s .c o m*/ // Set BouncyCastle provider String provider = BouncyCastleProvider.PROVIDER_NAME; if (Security.getProvider(provider) == null) { Security.addProvider(new BouncyCastleProvider()); } try { // Create and initialize PK signature SignatureInfo pkSignature = timeSignature.getPkSignature(); Signature signature = Signature.getInstance(pkSignature.getSignatureAlgorithm(), provider); signature.initVerify(publicKey); signature.update(timeSignature.getPublishedData().getDerEncoded()); // Verify PK signature if (!signature.verify(pkSignature.getSignatureValue())) { result.updateErrors(GTVerificationResult.PUBLIC_KEY_SIGNATURE_FAILURE); } } catch (SignatureException e) { result.updateErrors(GTVerificationResult.PUBLIC_KEY_SIGNATURE_FAILURE); } catch (NoSuchProviderException e) { result.updateErrors(GTVerificationResult.PUBLIC_KEY_SIGNATURE_FAILURE); } catch (NoSuchAlgorithmException e) { result.updateErrors(GTVerificationResult.PUBLIC_KEY_SIGNATURE_FAILURE); } catch (InvalidKeyException e) { result.updateErrors(GTVerificationResult.PUBLIC_KEY_SIGNATURE_FAILURE); } return result; }
From source file:com.helger.security.keystore.KeyStoreHelperTest.java
License:Apache License
private static X509Certificate _createX509V1Certificate(final KeyPair aKeyPair) throws Exception { // generate the certificate final PublicKey aPublicKey = aKeyPair.getPublic(); final PrivateKey aPrivateKey = aKeyPair.getPrivate(); final ContentSigner aContentSigner = new JcaContentSignerBuilder("SHA256WithRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(aPrivateKey); final X509CertificateHolder aCertHolder = new JcaX509v1CertificateBuilder( new X500Principal("CN=Test Certificate"), BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000), new X500Principal("CN=Test Certificate"), aPublicKey).build(aContentSigner); // Convert to JCA X509Certificate return new JcaX509CertificateConverter().getCertificate(aCertHolder); }
From source file:com.infinities.skyport.util.KeyStoreCreator.java
License:Apache License
public KeyStore buildKeyStore(String keyStoreType, String pass, byte[] content, String alias) throws IOException { InputStream inputStream = null; try {//from w w w. j a v a 2 s. c o m Security.addProvider(new BouncyCastleProvider()); KeyStore ks = KeyStore.getInstance(keyStoreType, BouncyCastleProvider.PROVIDER_NAME); char[] password = pass.toCharArray(); inputStream = new ByteArrayInputStream(content); ks.load(inputStream, password); logger.debug("Certificate entry has been added to the keystore"); return ks; } catch (Exception e) { throw new IOException("Error while importing a trusted certificate with alias: " + alias, e); } }
From source file:com.jaspersoft.jasperserver.api.security.encryption.EncryptionManager.java
License:Open Source License
/** * Certificate (version 1) generated using Bouncy Castle lib. * * Reference: http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation * * @param keyPair//from w w w. j a v a 2 s .c o m * @return */ private static Certificate createCertificate(KeyPair keyPair) { try { Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.YEAR, 100); X509V1CertificateGenerator certGenerator = new X509V1CertificateGenerator(); final X509Principal dnName = new X509Principal("CN=Jaspersoft Inc."); certGenerator.setSubjectDN(dnName); certGenerator.setIssuerDN(dnName); certGenerator.setNotAfter(expiry.getTime()); certGenerator.setNotBefore(new Date()); certGenerator.setPublicKey(keyPair.getPublic()); certGenerator.setSerialNumber(BigInteger.valueOf(expiry.getTimeInMillis())); certGenerator.setSignatureAlgorithm("MD5withRSA"); return certGenerator.generate(keyPair.getPrivate(), BouncyCastleProvider.PROVIDER_NAME); } catch (Exception e) { logger.error("Error creating certificate.", e); throw new RuntimeException("Error creating certificate.", e); } }
From source file:com.linecorp.armeria.internal.crypto.BouncyCastleKeyFactoryProviderTest.java
License:Apache License
/** * Tests if everything works even if Bouncy Castle is loaded already. *///from w w w. jav a 2s . co m @Test public void bouncyCastlePreInstalled() { Assume.assumeTrue(Arrays.stream(Security.getProviders()) .noneMatch(p -> BouncyCastleProvider.PROVIDER_NAME.equals(p.getName()))); Security.addProvider(new BouncyCastleProvider()); try { BouncyCastleKeyFactoryProvider.call(this::loadPkcs5); BouncyCastleKeyFactoryProvider.call(this::loadPkcs8); } finally { Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); } }
From source file:com.linkedin.mitm.services.AbstractX509CertificateService.java
License:Open Source License
protected X509Certificate createCertificate(PrivateKey privateKey, X509v3CertificateBuilder x509v3CertificateBuilder) throws OperatorCreationException, CertificateException { ContentSigner contentSigner = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privateKey); X509Certificate x509Certificate = new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(x509v3CertificateBuilder.build(contentSigner)); return x509Certificate; }
From source file:com.lyndir.lhunath.opal.crypto.gpg.GPG.java
License:Apache License
/** * PGP Encrypt a stream./* ww w.j ava2 s. c o m*/ * * @param plainTextStream The stream that contains the plain-text data. * @param publicKey The public key to use for encryption. * @param armoured {@code true}: ASCII armor the encrypted data. * * @return The encrypted data stream. * * @throws NoSuchProviderException * @throws IOException * @throws PGPException */ public static InputStream encrypt(final InputStream plainTextStream, final PGPPublicKey publicKey, final boolean armoured) throws IOException, NoSuchProviderException, PGPException { /* Compress and extract literal data packets that can be encrypted. */ PGPEncryptedDataGenerator encryptedDataGenerator = null; try (ByteArrayOutputStream decryptedStream = new ByteArrayOutputStream(); ByteArrayOutputStream encryptedByteStream = new ByteArrayOutputStream()) { PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); PGPCompressedDataGenerator compressor = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZLIB); OutputStream literalStream = literalDataGenerator.open(compressor.open(decryptedStream), PGPLiteralData.BINARY, "", new Date(), new byte[4096]); ByteStreams.copy(plainTextStream, literalStream); compressor.close(); /* Encrypt compressed data. */ encryptedDataGenerator = new PGPEncryptedDataGenerator(SymmetricKeyAlgorithmTags.CAST5, new SecureRandom(), BouncyCastleProvider.PROVIDER_NAME); encryptedDataGenerator.addMethod(publicKey); /* Create the encrypted output stream, armour if necessary. */ OutputStream encryptedStream = encryptedByteStream; if (armoured) encryptedStream = new ArmoredOutputStream(encryptedStream); /* Create and write out the encrypted file. */ OutputStream encryptionStream = encryptedDataGenerator.open(encryptedStream, new byte[4096]); ByteStreams.copy(new ByteArrayInputStream(decryptedStream.toByteArray()), encryptionStream); return new ByteArrayInputStream(encryptedByteStream.toByteArray()); } finally { if (encryptedDataGenerator != null) encryptedDataGenerator.close(); } }
From source file:com.lyndir.lhunath.opal.crypto.gpg.GPG.java
License:Apache License
/** * Decrypt a PGP encrypted stream.// ww w.j a va 2s .c om * * @param encryptedStream The stream that contains the encrypted data. * @param privateKey The private key to use for decrypting the data. * @param passPhrase The passphrase the private key is encrypted with. * * @return The plain-text stream. * * @throws NoSuchProviderException * @throws IOException * @throws PGPException */ public static InputStream decrypt(final InputStream encryptedStream, final PGPSecretKey privateKey, final String passPhrase) throws IOException, PGPException, NoSuchProviderException { /* Open the encrypted file. */ InputStream encryptedDataStream = PGPUtil.getDecoderStream(encryptedStream); PGPObjectFactory encryptedDataFactory = new PGPObjectFactory(encryptedDataStream); /* Find the PGP encrypted data. */ Object encryptedDataObjects = null; do try { encryptedDataObjects = encryptedDataFactory.nextObject(); } catch (final IOException e) { logger.warn(e.getMessage()); } while (!(encryptedDataObjects instanceof PGPEncryptedDataList) && encryptedDataObjects != null); if (encryptedDataObjects == null) throw new PGPException("No encrypted objects found."); @SuppressWarnings("unchecked") Iterator<PGPPublicKeyEncryptedData> encryptedDataIterator = ((PGPEncryptedDataList) encryptedDataObjects) .getEncryptedDataObjects(); /* Extract the public key out of the data and find the matching private key required to decrypt the data. */ PGPPublicKeyEncryptedData encryptedData = null; while (encryptedDataIterator.hasNext()) { encryptedData = encryptedDataIterator.next(); if (encryptedData.getKeyID() == privateKey.getKeyID()) break; } if (encryptedData == null) throw new PGPException("No encrypted data found."); /* Decrypt the data. */ InputStream unencryptedStream = encryptedData.getDataStream( privateKey.extractPrivateKey(passPhrase.toCharArray(), BouncyCastleProvider.PROVIDER_NAME), BouncyCastleProvider.PROVIDER_NAME); PGPObjectFactory pgpFactory = new PGPObjectFactory(unencryptedStream); Object unencryptedObject = pgpFactory.nextObject(); /* Possibly decompress the decrypted data. */ if (unencryptedObject instanceof PGPCompressedData) { PGPCompressedData compressedData = (PGPCompressedData) unencryptedObject; pgpFactory = new PGPObjectFactory(compressedData.getDataStream()); unencryptedObject = pgpFactory.nextObject(); } /* Verify integrity. */ if (encryptedData.isIntegrityProtected() && !encryptedData.verify()) throw new PGPException("Message integrity check failed."); /* Check to see if the data is valid decrypted data. */ if (unencryptedObject == null) throw new PGPException("No encrypted data found."); if (unencryptedObject instanceof PGPOnePassSignatureList) throw new PGPException("Encrypted data is a signature, not an encrypted message."); if (!(unencryptedObject instanceof PGPLiteralData)) throw new PGPException("Message type unrecognized: " + unencryptedObject.getClass()); /* Write out decrypted data. */ PGPLiteralData unencryptedData = (PGPLiteralData) unencryptedObject; return unencryptedData.getInputStream(); }
From source file:com.lyndir.lhunath.opal.crypto.gpg.GPG.java
License:Apache License
/** * PGP sign a stream./*from w w w .ja va2s . com*/ * * @param data The stream that contains the data to sign. * @param privateKey The private key to use for signing. * @param passPhrase The passphrase that the private key is locked with. * @param armoured {@code true}: ASCII armor the signature. * * @return The signature. * * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws SignatureException * @throws FileNotFoundException * @throws PGPException * @throws IOException */ public static InputStream sign(final InputStream data, final PGPSecretKey privateKey, final String passPhrase, final boolean armoured) throws NoSuchAlgorithmException, NoSuchProviderException, PGPException, SignatureException, IOException { /* Build the signature generator. */ PGPSignatureGenerator signer = new PGPSignatureGenerator(privateKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1, BouncyCastleProvider.PROVIDER_NAME); signer.initSign(PGPSignature.BINARY_DOCUMENT, privateKey.extractPrivateKey(passPhrase.toCharArray(), BouncyCastleProvider.PROVIDER_NAME)); /* Write the data into the generator. */ byte[] buffer = new byte[4096]; for (int read; (read = data.read(buffer)) >= 0;) signer.update(buffer, 0, read); /* Create the signature output stream, armour if necessary. */ try (ByteArrayOutputStream signatureByteStream = new ByteArrayOutputStream(); OutputStream signatureStream = armoured ? new ArmoredOutputStream(signatureByteStream) : signatureByteStream) { /* Create and write out the signature. */ PGPSignature signature = signer.generate(); signature.encode(signatureStream); return new ByteArrayInputStream(signatureByteStream.toByteArray()); } }
From source file:com.opentrust.spi.pdf.PDFEnvelopedSignature.java
License:Mozilla Public License
/** * Verifies a signature using the sub-filter adbe.x509.rsa_sha1. * @param contentsKey the /Contents key//from www . ja va 2 s. co m * @param certsKey the /Cert key * @param provider the provider or <code>null</code> for the default provider */ public PDFEnvelopedSignature(byte[] contentsKey, byte[] certsKey, String provider, AcroFields acroFields, String signatureFieldName) { try { log.debug(Channel.TECH, "Verifying a adbe.x509.rsa_sha1 signature"); this.acroFields = acroFields; this.signatureFieldName = signatureFieldName; this.subFilter = SF_ADBE_X509_RSA_SHA1; this.dictionaryCert = certsKey; X509CertParser cr = new X509CertParser(); cr.engineInit(new ByteArrayInputStream(certsKey)); certs = cr.engineReadAll(); signCert = (X509Certificate) certs.iterator().next(); crls = new ArrayList(); ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(contentsKey)); pkcs1SigValue = ((DEROctetString) in.readObject()).getOctets(); Cipher c = Cipher.getInstance("RSA/NONE/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME); c.init(Cipher.DECRYPT_MODE, signCert); byte[] raw = c.doFinal(pkcs1SigValue); ASN1Sequence in3 = (ASN1Sequence) ASN1Object.fromByteArray(raw); DigestInfo di = DigestInfo.getInstance(in3); dataDigestAlgorithm = di.getAlgorithmId().getAlgorithm().getId(); keyAndParameterAlgorithm = ID_RSA; if (provider == null) sig = Signature.getInstance(getSignatureAlgorithm()); else sig = Signature.getInstance(getSignatureAlgorithm(), provider); sig.initVerify(signCert.getPublicKey()); } catch (Exception e) { throw new ExceptionConverter(e); } }