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.googlecode.arit.test.TestServlet.java

License:Apache License

@Override
public void init() throws ServletException {
    new Timer().schedule(new TimerTask() {
        @Override/*from w w w  .ja  v a2 s .  co m*/
        public void run() {
            // Do nothing
        }
    }, 0, 1000);
    new EmbeddedDriver();
    threadLocal.set(this);
    try {
        ManagementFactory.getPlatformMBeanServer().registerMBean(new Echo(), new ObjectName("Test:type=Echo"));
    } catch (JMException ex) {
        throw new ServletException(ex);
    }
    try {
        helloWorldStub = (HelloWorld) UnicastRemoteObject.exportObject(new HelloWorldServer(), 0);
    } catch (RemoteException ex) {
        throw new ServletException(ex);
    }
    Security.addProvider(new BouncyCastleProvider());
}

From source file:com.guardtime.ksi.hashing.DataHasher.java

License:Apache License

/**
 * Create new data hasher for specified algorithm.
 *
 * @param algorithm//www. ja  v  a2s .  c  o m
 *         HashAlgorithm describing the algorithm to be used in hashing.
 * @throws HashException
 *         when hash algorithm is unknown or input algorithm is null
 */
public DataHasher(HashAlgorithm algorithm) throws HashException {
    if (algorithm == null) {
        throw new HashException("Invalid algorithm added to hasher: null");
    }

    /*
    If an algorithm is given which is not implemented, an HashAlgorithmNotImplementedException is thrown
    The developer must ensure that only implemented algorithms are used.
     */
    if (HashAlgorithm.Status.NOT_IMPLEMENTED.equals(algorithm.getStatus())) {
        throw new HashAlgorithmNotImplementedException(
                "Hash algorithm " + algorithm.name() + " is not implemented");
    }

    this.algorithm = algorithm;

    String provider = BouncyCastleProvider.PROVIDER_NAME;
    if (Security.getProvider(provider) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }

    try {
        messageDigest = MessageDigest.getInstance(algorithm.getName(), provider);
    } catch (NoSuchAlgorithmException e) {
        throw new HashException("Hash algorithm not supported: " + algorithm.getName());
    } catch (NoSuchProviderException e) {
        throw new HashException("Cryptographic provider not found: " + provider, e);
    }
}

From source file:com.guardtime.tsp.GTDataHash.java

License:Apache License

/**
 * Class constructor.//w w  w .  j a v  a 2s .  c  om
 * <p>
 * Creates new hash object.
 *
 * @param hashAlgorithm hash algorithm to use in this hash object.
 * @param hashedMessage hash value. If set to {@code null}, hash object will
 *          be created with open hash calculator; otherwise, hash algorithm
 *          and hash value correspondence will be checked.
 *
 * @throws RuntimeException if required cryptographic provider is not set.
 */
private GTDataHash(GTHashAlgorithm hashAlgorithm, byte[] hashedMessage) {
    if (hashAlgorithm == null) {
        throw new IllegalArgumentException("invalid hash algorithm: null");
    }

    this.hashAlgorithm = hashAlgorithm;
    this.hashedMessage = hashedMessage;

    if (hashedMessage == null) { // No hashed message -- initialize new digest
        String provider = BouncyCastleProvider.PROVIDER_NAME;
        if (Security.getProvider(provider) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }

        try {
            this.messageDigest = MessageDigest.getInstance(hashAlgorithm.getName(), provider);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Hash algorithm not supported: " + hashAlgorithm.getName());
        } catch (NoSuchProviderException e) {
            throw new RuntimeException("Cryptographic provider not found: " + provider, e);
        }

        setBufferSize(DEFAULT_BUFFER_SIZE);
    } else if (hashAlgorithm.getHashLength() != hashedMessage.length) {
        throw new IllegalArgumentException("hash length does not match with that defined in hash algorithm");
    } else { // Hashed message set -- no digest needed
        this.messageDigest = null;
    }
}

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;
    }// w ww  .  jav  a2s  .co  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.hack23.cia.encryption.properties.EncryptProperty.java

License:Apache License

/**
 * Gets the encryptor./*  w  w w  .java 2 s.  c  o m*/
 *
 * @param symmetricKey
 *            the symmetric key
 * @return the encryptor
 */
private StandardPBEStringEncryptor getEncryptor(final String symmetricKey) {
    Security.addProvider(new BouncyCastleProvider());
    final StandardPBEStringEncryptor mySecondEncryptor = new StandardPBEStringEncryptor();
    mySecondEncryptor.setProviderName(BC_PROVIDER_NAME);
    mySecondEncryptor.setAlgorithm(PBEWITHSHA256AND128BITAES_CBC_BC);
    mySecondEncryptor.setPassword(symmetricKey);
    return mySecondEncryptor;
}

From source file:com.hkt.client.swingexp.app.license.DecryptAES.java

/**
 * Khi ti Gii m AES//from   w w w. j  a  va2s. c  om
 * keyBytes: key User truy?n vo  lm kha gii m(dng byte)
 * dataEncrypted: d liu cn gii m
 */
public DecryptAES(String key, String dataNeedEncrypt) {
    Security.addProvider(new BouncyCastleProvider());
    base32 = new Base32();
    initCipher(key, dataNeedEncrypt);
}

From source file:com.hp.ov.sdk.certs.CertificateStoreManager.java

License:Apache License

private static KeyManagerFactory getInitiazedKeyManager(final RabbitMqClientCert certDto) {
    KeyManagerFactory kmf = null;
    Security.addProvider(new BouncyCastleProvider());
    try {//  w  w  w . j  a  va2  s.c om
        // Read client certificate and private key.
        final byte[] encoded = BaseEncoding.base64().withSeparator("\n", 65)
                .decode(certDto.getBase64SSLKeyData());

        final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey privateKey = kf.generatePrivate(keySpec);

        final String strClientCert = certDto.getBase64SSLCertData();
        final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        final Certificate cert = certFactory
                .generateCertificate(new ByteArrayInputStream(strClientCert.getBytes(StandardCharsets.UTF_8)));

        // Add both client cert and private key to the keyStore.
        final KeyStore ks = KeyStore.getInstance("jks");
        ks.load(null, "password".toCharArray());
        ks.setEntry("rabbitmq-client", new KeyStore.PrivateKeyEntry(privateKey, new Certificate[] { cert }),
                new KeyStore.PasswordProtection("password".toCharArray()));

        kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, "password".toCharArray());
    } catch (final CertificateException e) {
        throw new SDKCertificateException(SDKErrorEnum.certificateError, null, null, null, SdkConstants.CERTS,
                e);
    } catch (final KeyStoreException e) {
        throw new SDKCertificateException(SDKErrorEnum.certificateError, null, null, null, SdkConstants.CERTS,
                e);
    } catch (final NoSuchAlgorithmException e) {
        throw new SDKCertificateException(SDKErrorEnum.certificateError, null, null, null, SdkConstants.CERTS,
                e);
    } catch (final IOException e) {
        throw new SDKCertificateException(SDKErrorEnum.certificateError, null, null, null, SdkConstants.CERTS,
                e);
    } catch (final UnrecoverableKeyException e) {
        throw new SDKCertificateException(SDKErrorEnum.certificateError, null, null, null, SdkConstants.CERTS,
                e);
    } catch (final InvalidKeySpecException e) {
        throw new SDKCertificateException(SDKErrorEnum.certificateError, null, null, null, SdkConstants.CERTS,
                e);
    }

    return kmf;
}

From source file:com.hp.ov.sdk.certs.CertificateStoreManager.java

License:Apache License

private static TrustManagerFactory getInitiazedTrustManager(final String caCert) {
    Security.addProvider(new BouncyCastleProvider());
    TrustManagerFactory tmf = null;
    try {// w  w  w .  j av a2 s.c o  m
        final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

        // Add CA certificate to TrustStore.
        final KeyStore tks = KeyStore.getInstance("jks");
        tks.load(null, "password".toCharArray());
        final Certificate caCErt = certFactory
                .generateCertificate(new ByteArrayInputStream(caCert.getBytes(StandardCharsets.UTF_8)));

        tks.setEntry("ca-cert", new KeyStore.TrustedCertificateEntry(caCErt), null);
        tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(tks);
    } catch (final CertificateException e) {
        throw new SDKCertificateException(SDKErrorEnum.certificateError, null, null, null, SdkConstants.CERTS,
                e);
    } catch (final KeyStoreException e) {
        throw new SDKCertificateException(SDKErrorEnum.certificateError, null, null, null, SdkConstants.CERTS,
                e);
    } catch (final NoSuchAlgorithmException e) {
        throw new SDKCertificateException(SDKErrorEnum.certificateError, null, null, null, SdkConstants.CERTS,
                e);
    } catch (final IOException e) {
        throw new SDKCertificateException(SDKErrorEnum.certificateError, null, null, null, SdkConstants.CERTS,
                e);
    }

    return tmf;
}

From source file:com.htlab.license.MyRSACoder.java

/**
 * ?/*  www.ja  v a  2 s .c om*/
 */
public static Map<String, Object> initKeys(String seed) throws Exception {

    Map<String, Object> keyMap = new HashMap<String, Object>();
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM, KEY_PROVIDER);

    keyPairGenerator.initialize(1024, new SecureRandom(seed.getBytes()));
    KeyPair pair = keyPairGenerator.generateKeyPair();
    RSAPublicKey rsaPublicKey = (RSAPublicKey) pair.getPublic();
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) pair.getPrivate();

    KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM, KEY_PROVIDER);
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(rsaPublicKey.getModulus().toString()),
            new BigInteger(rsaPublicKey.getPublicExponent().toString()));
    RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(rsaPrivateKey.getModulus().toString()),
            new BigInteger(rsaPrivateKey.getPrivateExponent().toString()));

    PublicKey publicKey = factory.generatePublic(pubKeySpec);
    PrivateKey privateKey = factory.generatePrivate(priKeySpec);

    System.out.println("" + pubKeySpec.getModulus() + "----" + pubKeySpec.getPublicExponent());
    System.out.println("?" + priKeySpec.getModulus() + "----" + priKeySpec.getPrivateExponent());
    keyMap.put("publicKey", publicKey);
    keyMap.put("privateKey", privateKey);

    return keyMap;
}

From source file:com.hypersocket.certs.X509CertificateUtils.java

License:Open Source License

public static void main(String[] args) throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    // X509CertificateUtils.validateChain(X509CertificateUtils
    // .loadCertificateChainFromPEM(new FileInputStream(
    // "/Users/lee/gd_bundle.crt")), X509CertificateUtils
    // .loadCertificateFromPEM(new FileInputStream(
    // "/Users/lee/javassh.com.crt")));
    ///*  ww w .ja  va 2s. c o m*/
    // X509CertificateUtils.loadKeyPairFromPFX(new
    // FileInputStream("/home/lee//Dropbox/Company Files/Nervepoint Technologies Limited/Certificates/Domain Wildcard/nervepoint-www-wildcard.pfx"),
    // "bluemars73".toCharArray());

    //      X509CertificateUtils.generatePrivateKey("RSA", 1024);
    //      X509CertificateUtils.generatePrivateKey("RSA", 2048);
    //      X509CertificateUtils.generatePrivateKey("RSA", 4096);
    //      X509CertificateUtils.generatePrivateKey("RSA", 8192);

    //      X509CertificateUtils.generatePrivateKey("DSA", 1024);
    //      X509CertificateUtils.generatePrivateKey("DSA", 2048);
    //      X509CertificateUtils.generatePrivateKey("DSA", 4096);
    //      X509CertificateUtils.generatePrivateKey("DSA", 8192);

}