Search in sources :

Example 1 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project camel by apache.

the class PGPKeyAccessDataFormat method doStart.

@Override
protected void doStart() throws Exception {
    //NOPMD
    if (Security.getProvider(BC) == null && BC.equals(getProvider())) {
        LOG.debug("Adding BouncyCastleProvider as security provider");
        Security.addProvider(new BouncyCastleProvider());
    } else {
        LOG.debug("Using custom provider {} which is expected to be enlisted manually.", getProvider());
    }
}
Also used : BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 2 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project kafka by apache.

the class TestSslUtils method generateCertificate.

/**
     * Create a self-signed X.509 Certificate.
     * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
     *
     * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
     * @param pair the KeyPair
     * @param days how many days from now the Certificate is valid for
     * @param algorithm the signing algorithm, eg "SHA1withRSA"
     * @return the self-signed certificate
     * @throws CertificateException thrown if a security error or an IO error occurred.
     */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateException {
    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());
        X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
        X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
Also used : ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) EOFException(java.io.EOFException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X509v1CertificateBuilder(org.bouncycastle.cert.X509v1CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 3 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project OpenAttestation by OpenAttestation.

the class CertificateUtils method generateSelfSignedX509Certificate.

/**
	 * Generate a self signed X509 certificate with Bouncy Castle.
	 * @throws SignatureException 
	 * @throws IllegalStateException 
	 * @throws InvalidKeyException 
	 * @throws CertificateEncodingException 
	 */
public static X509Certificate generateSelfSignedX509Certificate() throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, InvalidKeyException, IllegalStateException, SignatureException {
    Security.addProvider(new BouncyCastleProvider());
    int validityDays = 3652;
    // GENERATE THE PUBLIC/PRIVATE RSA KEY PAIR
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
    keyPairGenerator.initialize(1024, new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    // GENERATE THE X509 CERTIFICATE
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal dnName = new X500Principal("CN=OATServer");
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setSubjectDN(dnName);
    // use the same
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis()));
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);
    certGen.setNotAfter(expiry.getTime());
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");
    return cert;
}
Also used : KeyPair(java.security.KeyPair) X509V1CertificateGenerator(org.bouncycastle.x509.X509V1CertificateGenerator) Calendar(java.util.Calendar) SecureRandom(java.security.SecureRandom) X500Principal(javax.security.auth.x500.X500Principal) KeyPairGenerator(java.security.KeyPairGenerator) X509Certificate(java.security.cert.X509Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 4 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project OpenAttestation by OpenAttestation.

the class ProvisionTPM method takeOwnership.

/**
	 * Entry point into the program
	 * @throws Exception 
	 */
public static void takeOwnership() throws Exception {
    // throws InvalidKeyException, CertificateEncodingException, UnrecoverableKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, NoSuchProviderException, KeyStoreException, CertificateException, IOException, javax.security.cert.CertificateException {
    //get properties file info
    final String OWNER_AUTH = "TpmOwnerAuth";
    final String EC_VALIDITY = "EcValidityDays";
    final String EC_STORAGE = "ecStorage";
    final String PRIVACY_CA_URL = "PrivacyCaUrl";
    final String TRUST_STORE = "TrustStore";
    final String PRIVACY_CA_CERT = "PrivacyCaCertFile";
    final String EC_LOCATION = "ecLocation";
    String ecStorage = "";
    String ecStorageFileName = "";
    String PrivacyCaUrl = "";
    int EcValidityDays = 0;
    String PrivacyCaCertFile = "";
    byte[] TpmOwnerAuth = null;
    byte[] encryptCert = null;
    byte[] pubEkMod = null;
    X509Certificate pcaCert = null;
    PublicKey publicKey = null;
    //This is for logging purpose
    String propertiesFileName = ResourceFinder.getLocation("hisprovisioner.properties");
    FileInputStream PropertyFile = null;
    String tpmOwnerAuth = "";
    String homeFolder = "";
    try {
        File propFile = ResourceFinder.getFile("hisprovisioner.properties");
        PropertyFile = new FileInputStream(propFile);
        Properties HisProvisionerProperties = new Properties();
        HisProvisionerProperties.load(new InputStreamReader(PropertyFile, "UTF-8"));
        homeFolder = propFile.getAbsolutePath();
        homeFolder = homeFolder.substring(0, homeFolder.indexOf("hisprovisioner.properties"));
        log.info("Home folder : " + homeFolder);
        EcValidityDays = Integer.parseInt(HisProvisionerProperties.getProperty(EC_VALIDITY, ""));
        tpmOwnerAuth = HisProvisionerProperties.getProperty(OWNER_AUTH, "");
        if (tpmOwnerAuth != null) {
            TpmOwnerAuth = Hex.decodeHex(tpmOwnerAuth.toCharArray());
        }
        //else if (tpmOwnerAuth.length() == 40) {
        //    log.info("owner authentication is hex code formatted");
        //    TpmOwnerAuth = TpmUtils.hexStringToByteArray(tpmOwnerAuth);
        //} else {
        //    log.info("illegal owner authentication detected! accepted owner authentication is 20 or 40 long characters");
        //}
        //TpmOwnerAuth = TpmUtils.hexStringToByteArray(HisProvisionerProperties.getProperty(OWNER_AUTH, ""));
        PrivacyCaUrl = HisProvisionerProperties.getProperty(PRIVACY_CA_URL, "");
        PrivacyCaCertFile = HisProvisionerProperties.getProperty(PRIVACY_CA_CERT, "");
        ecStorage = HisProvisionerProperties.getProperty(EC_STORAGE, "NVRAM");
        ecStorageFileName = HisProvisionerProperties.getProperty(EC_LOCATION, ".") + System.getProperty("file.separator") + "EC.cer";
        log.info("ecStorageFileName:" + ecStorageFileName);
    } catch (FileNotFoundException e) {
        throw new PrivacyCAException("Error finding HIS Provisioner properties file (HISprovisionier.properties)", e);
    } catch (IOException e) {
        throw new PrivacyCAException("Error loading HIS Provisioner properties file (HISprovisionier.properties)", e);
    } catch (NumberFormatException e) {
        throw new PrivacyCAException("Error while reading EcValidityDays", e);
    } finally {
        if (PropertyFile != null) {
            try {
                PropertyFile.close();
            } catch (IOException e) {
                log.log(Level.SEVERE, "Error while closing the property file ", e);
            }
        }
    }
    String errorString = "Properties file \"" + propertiesFileName + "\" contains errors:\n";
    boolean hasErrors = false;
    if (EcValidityDays == 0) {
        errorString += " - \"EcValidityDays\" value must be the number of validity days for the Endorsement Credential\n";
        hasErrors = true;
    }
    if (TpmOwnerAuth == null) {
        // || TpmOwnerAuth.length != 20){
        errorString += " - \"TpmOwnerAuth\" value must be set representing the TPM owner auth\n";
        hasErrors = true;
    }
    if (hasErrors) {
        throw new PrivacyCAException(errorString);
    }
    //Provision the TPM
    log.info("Performing TPM provisioning...");
    Security.addProvider(new BouncyCastleProvider());
    SecretKey deskey = TpmUtils.generateSecretKey();
    // Take Ownership
    byte[] nonce = null;
    try {
        nonce = TpmUtils.createRandomBytes(20);
        TpmModule.takeOwnership(TpmOwnerAuth, nonce);
    } catch (TpmModuleException e) {
        if (e.toString().contains(".takeOwnership returned nonzero error: 4")) {
            Logger.getLogger(ProvisionTPM.class.getName()).info("Ownership is already taken : ");
            if (!System.getProperty("forceCreateEk", "false").equals("true")) {
                // feature to help with bug #554 and allow admin to force creating an ek (in case it failed the first time due to a non-tpm error such as java missing classes exception
                return;
            }
        } else
            throw e;
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Create Endorsement Certificate
    try {
        nonce = TpmUtils.createRandomBytes(20);
        pubEkMod = TpmModule.getEndorsementKeyModulus(TpmOwnerAuth, nonce);
    } catch (TpmModuleException e) {
        System.out.println("Error getting PubEK: " + e.toString());
    } catch (Exception e) {
        System.out.println("Error getting PubEK: " + e.toString());
    }
    try {
        pcaCert = TpmUtils.certFromFile(homeFolder + PrivacyCaCertFile);
        if (pcaCert != null) {
            publicKey = (RSAPublicKey) pcaCert.getPublicKey();
        }
    } catch (Exception e) {
        System.out.println("print out error message: " + e.toString());
        e.printStackTrace();
    }
    try {
        IHisPrivacyCAWebService2 hisPrivacyCAWebService2 = HisPrivacyCAWebServices2ClientInvoker.getHisPrivacyCAWebService2(PrivacyCaUrl);
        encryptCert = hisPrivacyCAWebService2.requestGetEC(TpmUtils.encryptDES(pubEkMod, deskey), TpmUtils.encryptRSA(deskey.getEncoded(), publicKey), EcValidityDays);
    } catch (Exception e) {
        System.out.println("FAILED");
        e.printStackTrace();
        System.exit(1);
    }
    //Decrypt and generate endorsement certificate 
    X509Certificate ekCert = null;
    try {
        if (encryptCert != null) {
            ekCert = TpmUtils.certFromBytes(TpmUtils.decryptDES(encryptCert, deskey));
        }
    } catch (java.security.cert.CertificateException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    // Store the new EC in NV-RAM or in the file
    try {
        if (ecStorage.equalsIgnoreCase("file")) {
            File ecFile = new File(ecStorageFileName);
            FileOutputStream ecFileOut = new FileOutputStream(ecFile);
            ecFileOut.write(ekCert.getEncoded());
            ecFileOut.flush();
            ecFileOut.close();
        } else {
            TpmModule.setCredential(TpmOwnerAuth, "EC", ekCert.getEncoded());
        }
        System.out.println(ekCert.getEncoded().length);
    } catch (TpmModuleException e) {
        System.out.println("Error getting PubEK: " + e.toString());
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("DONE");
    //System.exit(0);
    return;
}
Also used : FileNotFoundException(java.io.FileNotFoundException) CertificateException(javax.security.cert.CertificateException) Properties(java.util.Properties) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) IHisPrivacyCAWebService2(gov.niarl.his.webservices.hisPrivacyCAWebService2.IHisPrivacyCAWebService2) InputStreamReader(java.io.InputStreamReader) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) FileInputStream(java.io.FileInputStream) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) TpmModuleException(gov.niarl.his.privacyca.TpmModule.TpmModuleException) FileNotFoundException(java.io.FileNotFoundException) CertificateException(javax.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) CertificateEncodingException(java.security.cert.CertificateEncodingException) SecretKey(javax.crypto.SecretKey) FileOutputStream(java.io.FileOutputStream) TpmModuleException(gov.niarl.his.privacyca.TpmModule.TpmModuleException) File(java.io.File)

Example 5 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project OpenAttestation by OpenAttestation.

the class Diagnostic method main.

public static void main(String[] args) {
    checkBouncycastlePresent();
    Security.addProvider(new BouncyCastleProvider());
    checkBouncycastleAlgorithms();
}
Also used : BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)34 IOException (java.io.IOException)12 KeyPair (java.security.KeyPair)9 X509Certificate (java.security.cert.X509Certificate)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 KeyPairGenerator (java.security.KeyPairGenerator)6 KeyStore (java.security.KeyStore)6 SecureRandom (java.security.SecureRandom)5 Date (java.util.Date)5 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)5 File (java.io.File)4 FileOutputStream (java.io.FileOutputStream)4 SecretKey (javax.crypto.SecretKey)4 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)4 Before (org.junit.Before)4 KeyStoreException (java.security.KeyStoreException)3 NoSuchProviderException (java.security.NoSuchProviderException)3 CertificateException (java.security.cert.CertificateException)3 X500Name (org.bouncycastle.asn1.x500.X500Name)3 Test (org.junit.Test)3