Example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

Introduction

In this page you can find the example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider.

Prototype

public BouncyCastleProvider() 

Source Link

Document

Construct a new provider.

Usage

From source file:com.mansoor.uncommon.configuration.util.EncryptionUtil.java

License:Apache License

private static void loadProvider() {
    if (Security.getProvider(EncryptionUtil.BC) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*  w  w  w . j a v a 2s.com*/
}

From source file:com.msopentech.thali.utilities.universal.test.ThaliPublicKeyComparerTests.java

License:Open Source License

private KeyPair generateEllpticCurve() throws NoSuchAlgorithmException {
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyPairGenerator = new KeyPairGeneratorSpi.ECDH();
    return keyPairGenerator.generateKeyPair();

}

From source file:com.mutable.drmPlugin.server.TestServer.java

License:Open Source License

/**
 * The constructor creating all helpers. The RegistrationDatabase and RoDatabase
 * helpers are expected from the abstract method initializeData().
 *
 *///from ww  w  .j  a va2s  .  com
public TestServer() {
    try {
        initializeData(); // sets the databases
    } catch (Exception e) {
        e.printStackTrace();
    }
    tracker = new ProtocolTracker();
    noncer = new NonceCreator();
    certer = new CertificateVerifier(getRiContext().getTrustedDeviceCerts());
    hasher = new Hasher();
    triggerer = new TriggerCreator(this);
    righter = new RoIdCreator(this);
    sessioner = new SessionIdCreator(this);
    Security.addProvider(new BouncyCastleProvider());

}

From source file:com.mycompany.mavenproject1.P12KeyContainer.java

public void init(FileInputStream stream, String password)
        throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
    Security.addProvider(new BouncyCastleProvider());

    PKCS12KeyStoreSpi.BCPKCS12KeyStore keyStore = new PKCS12KeyStoreSpi.BCPKCS12KeyStore();
    keyStore.engineLoad(stream, password.toCharArray());

    String alias = (String) keyStore.engineAliases().nextElement();
    privateKey = keyStore.engineGetKey(alias, password.toCharArray());

    certificate = keyStore.engineGetCertificate(alias);
}

From source file:com.mycompany.mavenproject1.Signer.java

public void init(P12KeyContainer keyContainer)
        throws CertificateEncodingException, OperatorCreationException, CMSException {

    Security.addProvider(new BouncyCastleProvider());

    List certList = new ArrayList();
    X509Certificate cert = (X509Certificate) keyContainer.certificate;
    certList.add(cert);/*from w  ww .  jav  a 2 s .c  o  m*/
    Store certsStore = new JcaCertStore(certList);
    generator = new CMSSignedDataGenerator();

    JcaSimpleSignerInfoGeneratorBuilder genInfo = new JcaSimpleSignerInfoGeneratorBuilder();
    genInfo.setProvider("BC");
    genInfo.setDirectSignature(true);

    SignerInfoGenerator signerInfoGenerator = genInfo.build("GOST3411withECGOST3410",
            (PrivateKey) keyContainer.privateKey, cert);

    generator.addSignerInfoGenerator(signerInfoGenerator);
    generator.addCertificates(certsStore);
}

From source file:com.navnorth.learningregistry.LRSigner.java

License:Apache License

/**
 * Encodes the provided message with the private key and pass phrase set in configuration
 *
 * @param message Message to encode//from   ww  w . j  a v a  2  s . c  o m
 * @return Encoded message
 * @throws LRException SIGNING_FAILED if the document cannot be signed, NO_KEY if the key cannot be obtained
 */
private String signEnvelopeData(String message) throws LRException {
    // Throw an exception if any of the required fields are null
    if (passPhrase == null || publicKeyLocation == null || privateKey == null) {
        throw new LRException(LRException.NULL_FIELD);
    }

    // Add the provider here so that after signing, we can remove the provider.
    // This allows using this code from multiple separate class loaders while Bouncy Castle is on a separate class loader
    BouncyCastleProvider provider = new BouncyCastleProvider();
    Security.addProvider(provider);

    try {

        // Get an InputStream for the private key
        InputStream privateKeyStream = getPrivateKeyStream(privateKey);

        // Get an OutputStream for the result
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        ArmoredOutputStream aOut = new ArmoredOutputStream(result);

        // Get the pass phrase
        char[] privateKeyPassword = passPhrase.toCharArray();

        try {
            // Get the private key from the InputStream
            PGPSecretKey sk = readSecretKey(privateKeyStream);
            PGPPrivateKey pk = sk.extractPrivateKey(
                    new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(privateKeyPassword));
            PGPSignatureGenerator sGen = new PGPSignatureGenerator(
                    new JcaPGPContentSignerBuilder(sk.getPublicKey().getAlgorithm(), PGPUtil.SHA256)
                            .setProvider("BC"));
            PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

            // Clear sign the message
            java.util.Iterator it = sk.getPublicKey().getUserIDs();
            if (it.hasNext()) {
                spGen.setSignerUserID(false, (String) it.next());
                sGen.setHashedSubpackets(spGen.generate());
            }
            aOut.beginClearText(PGPUtil.SHA256);
            sGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, pk);
            byte[] msg = message.getBytes();
            sGen.update(msg, 0, msg.length);
            aOut.write(msg, 0, msg.length);
            BCPGOutputStream bOut = new BCPGOutputStream(aOut);
            aOut.endClearText();
            sGen.generate().encode(bOut);
            aOut.close();

            String strResult = result.toString("utf8");

            // for whatever reason, bouncycastle is failing to put a linebreak before "-----BEGIN PGP SIGNATURE"
            strResult = strResult.replaceAll("([a-z0-9])-----BEGIN PGP SIGNATURE-----",
                    "$1\n-----BEGIN PGP SIGNATURE-----");

            return strResult;
        } catch (Exception e) {
            throw new LRException(LRException.SIGNING_FAILED, e);
        } finally {
            try {
                if (privateKeyStream != null) {
                    privateKeyStream.close();
                }

                result.close();
            } catch (IOException e) {
                //Could not close the streams
            }
        }
    } finally {
        Security.removeProvider(provider.getName());
    }
}

From source file:com.navnorth.learningregistry.LRVerify.java

License:Apache License

/**
 * Verfies that the provided message and signature using the public key
 *
 * @param isSignature InputStream of the signature
 * @param isMessage InputStream of the message
 * @param isPublicKey InputStream of the public key
 * @throws LRException/*  ww w.  ja  v  a2s.  co m*/
 */
private static boolean Verify(InputStream isSignature, InputStream isMessage, InputStream isPublicKey)
        throws LRException {
    // Get the public key ring collection from the public key input stream
    PGPPublicKeyRingCollection pgpRings = null;

    try {
        pgpRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(isPublicKey));
    } catch (Exception e) {
        throw new LRException(LRException.INVALID_PUBLIC_KEY);
    }

    // Add the Bouncy Castle security provider
    Security.addProvider(new BouncyCastleProvider());

    // Build an output stream from the message for verification
    boolean verify = false;
    int ch;
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ArmoredInputStream aIn = null;

    try {
        aIn = new ArmoredInputStream(isMessage);
        // We are making no effort to clean the input for this example
        // If this turns into a fully-featured verification utility in a future version, this will need to be handled
        while ((ch = aIn.read()) >= 0 && aIn.isClearText()) {
            bOut.write((byte) ch);
        }

        bOut.close();
    } catch (Exception e) {
        throw new LRException(LRException.MESSAGE_INVALID);
    }

    // Build an object factory from the signature input stream and try to get an object out of it
    Object o = null;
    try {
        PGPObjectFactory pgpFact = new PGPObjectFactory(PGPUtil.getDecoderStream(isSignature));
        o = pgpFact.nextObject();
    } catch (Exception e) {
        throw new LRException(LRException.SIGNATURE_INVALID);
    }

    // Check if the object we fetched is a signature list and if it is, get the signature and use it to verfiy
    try {
        if (o instanceof PGPSignatureList) {
            PGPSignatureList list = (PGPSignatureList) o;
            if (list.size() > 0) {
                PGPSignature sig = list.get(0);

                PGPPublicKey publicKey = pgpRings.getPublicKey(sig.getKeyID());
                sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);

                sig.update(bOut.toByteArray());
                verify = sig.verify();
            }
        }
    } catch (Exception e) {
        throw new LRException(LRException.SIGNATURE_NOT_FOUND);
    }

    return verify;
}

From source file:com.netflix.msl.crypto.JsonWebKeyTest.java

License:Open Source License

@BeforeClass
public static void setup() throws NoSuchAlgorithmException {
    Security.addProvider(new BouncyCastleProvider());

    final KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA");
    keypairGenerator.initialize(512);//  ww w .  j  a va2s. c  om
    final KeyPair keypair = keypairGenerator.generateKeyPair();
    PRIVATE_KEY = (RSAPrivateKey) keypair.getPrivate();
    PUBLIC_KEY = (RSAPublicKey) keypair.getPublic();

    final byte[] keydata = new byte[16];
    random.nextBytes(keydata);
    SECRET_KEY = new SecretKeySpec(keydata, JcaAlgorithm.AES);
}

From source file:com.netflix.msl.crypto.RsaCryptoContextSuite.java

License:Open Source License

@BeforeClass
public static synchronized void setup() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidParameterSpecException, NoSuchProviderException, MslEncodingException, MslCryptoException {
    if (random == null) {
        ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
        Security.addProvider(new BouncyCastleProvider());

        final KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA");
        keypairGenerator.initialize(512);
        final KeyPair keypairA = keypairGenerator.generateKeyPair();
        privateKeyA = keypairA.getPrivate();
        publicKeyA = keypairA.getPublic();

        final KeyPair keypairB = keypairGenerator.generateKeyPair();
        privateKeyB = keypairB.getPrivate();
        publicKeyB = keypairB.getPublic();

        random = new Random();
    }// w  ww . ja  v  a 2 s .c  o m
}

From source file:com.netflix.msl.keyx.AsymmetricWrappedExchangeSuite.java

License:Open Source License

@BeforeClass
public static synchronized void setup() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        MslEncodingException, MslCryptoException {
    if (ctx == null) {
        Security.addProvider(new BouncyCastleProvider());

        final ECCurve curve = new ECCurve.Fp(EC_Q, EC_A, EC_B);
        final AlgorithmParameterSpec paramSpec = new ECParameterSpec(curve,
                curve.decodePoint(EC_G.toByteArray()), EC_N);
        final KeyPairGenerator eccGenerator = KeyPairGenerator.getInstance("ECIES");
        eccGenerator.initialize(paramSpec);
        final KeyPair eccKeyPair = eccGenerator.generateKeyPair();
        ECC_PUBLIC_KEY = eccKeyPair.getPublic();
        ECC_PRIVATE_KEY = eccKeyPair.getPrivate();

        final KeyPairGenerator rsaGenerator = KeyPairGenerator.getInstance("RSA");
        rsaGenerator.initialize(2048);/*w w  w. j ava2  s  .c  o  m*/
        final KeyPair rsaKeyPair = rsaGenerator.generateKeyPair();
        RSA_PUBLIC_KEY = rsaKeyPair.getPublic();
        RSA_PRIVATE_KEY = rsaKeyPair.getPrivate();

        ctx = new MockMslContext(EntityAuthenticationScheme.PSK, false);
        MASTER_TOKEN = MslTestUtils.getMasterToken(ctx, 1, 1);
        ENCRYPTION_KEY = MASTER_TOKEN.getEncryptionKey().getEncoded();
        HMAC_KEY = MASTER_TOKEN.getHmacKey().getEncoded();
    }
}