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:eu.contrail.security.DelegatedUserCertClientTest.java

License:Apache License

@BeforeClass
public static void setUpClass() throws Exception {

    Security.addProvider(new BouncyCastleProvider());

}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1Info.java

License:Open Source License

/**
 * Generate different encrypted PKCS1 vectors
 * //from  w w w  .  ja  v a 2s  .c om
 * @param publicKey
 *            Public key
 * @param keySize
 *            Key size
 * @return Hashmap of encrypted padded keys and according payload type
 */
private HashMap<PayloadType, byte[]> generatePkcs1Vectors(RSAPublicKey publicKey, int keySize) {
    // Generate random key
    Random random = new Random();
    byte[] keyBytes = new byte[keySize];
    random.nextBytes(keyBytes);

    int rsaKeyLength = publicKey.getModulus().bitLength() / 8;

    HashMap<PayloadType, byte[]> encryptedKeys = new HashMap<>();

    try {
        Security.addProvider(new BouncyCastleProvider());
        Cipher rsa = Cipher.getInstance("RSA/NONE/NoPadding");
        rsa.init(Cipher.ENCRYPT_MODE, publicKey);

        // create plain padded key and encrypt them
        encryptedKeys.put(PayloadType.NO_NULL_BYTE, rsa.doFinal(getEK_NoNullByte(rsaKeyLength, keyBytes)));
        encryptedKeys.put(PayloadType.NULL_BYTE_IN_PADDING,
                rsa.doFinal(getEK_NullByteInPadding(rsaKeyLength, keyBytes)));
        encryptedKeys.put(PayloadType.NULL_BYTE_IN_PKCS_PADDING,
                rsa.doFinal(getEK_NullByteInPkcsPadding(rsaKeyLength, keyBytes)));
        encryptedKeys.put(PayloadType.SYMMETRIC_KEY_OF_SIZE_16,
                rsa.doFinal(getEK_SymmetricKeyOfSize16(rsaKeyLength, keyBytes)));
        encryptedKeys.put(PayloadType.SYMMETRIC_KEY_OF_SIZE_24,
                rsa.doFinal(getEK_SymmetricKeyOfSize24(rsaKeyLength, keyBytes)));
        encryptedKeys.put(PayloadType.SYMMETRIC_KEY_OF_SIZE_32,
                rsa.doFinal(getEK_SymmetricKeyOfSize32(rsaKeyLength, keyBytes)));
        encryptedKeys.put(PayloadType.SYMMETRIC_KEY_OF_SIZE_40,
                rsa.doFinal(getEK_SymmetricKeyOfSize40(rsaKeyLength, keyBytes)));
        encryptedKeys.put(PayloadType.SYMMETRIC_KEY_OF_SIZE_8,
                rsa.doFinal(getEK_SymmetricKeyOfSize8(rsaKeyLength, keyBytes)));
        encryptedKeys.put(PayloadType.WRONG_FIRST_BYTE,
                rsa.doFinal(getEK_WrongFirstByte(rsaKeyLength, keyBytes)));
        encryptedKeys.put(PayloadType.WRONG_SECOND_BYTE,
                rsa.doFinal(getEK_WrongSecondByte(rsaKeyLength, keyBytes)));
        encryptedKeys.put(PayloadType.ORIGINAL, rsa.doFinal(getPaddedKey(rsaKeyLength, keyBytes)));

    } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
            | NoSuchPaddingException e) {
        loggerInstance.log(getClass(), "Error during key encryption: " + e.getMessage(), Logger.LogLevel.ERROR);
    }

    return encryptedKeys;
}

From source file:eu.dety.burp.joseph.utilities.Crypto.java

License:Open Source License

/**
 * Decrypt AES ciphertext/*from   w ww.  ja  v  a  2 s .c om*/
 *
 * @param header
 *            JOSE header
 * @param key
 *            Symmetric key as byte array
 * @param iv
 *            Initialization Vector as byte array
 * @param cipherBytes
 *            Ciphertext as byte array
 * @param authTag
 *            Authentication tag as byte array
 * @throws DecryptionFailedException
 * @return Decrypted message as byte array
 */
public static byte[] decryptAES(String header, byte[] key, byte[] iv, byte[] cipherBytes, byte[] authTag)
        throws DecryptionFailedException {
    byte[] decryptedContent;

    String encAlg = Decoder.getValueByBase64String(header, "enc").toUpperCase();

    int keyLen = getAesKeyLengthByJoseAlgorithm(encAlg, 32);
    String cipherInstance;

    switch (encAlg) {
    case "A128CBC-HS256":
        cipherInstance = "AES/CBC/PKCS5Padding";
        break;
    case "A192CBC-HS384":
        cipherInstance = "AES/CBC/PKCS5Padding";
        break;
    case "A256CBC-HS512":
        cipherInstance = "AES/CBC/PKCS5Padding";
        break;
    case "A128GCM":
        cipherInstance = "AES/GCM/NoPadding";
        break;
    case "A192GCM":
        cipherInstance = "AES/GCM/NoPadding";
        break;
    case "A256GCM":
        cipherInstance = "AES/GCM/NoPadding";
        break;
    default:
        throw new DecryptionFailedException("Could not determine encryption algorithm or it is not supported");
    }

    byte[] keyBytes = Arrays.copyOfRange(key, key.length - keyLen, key.length);

    SecretKey aesKey = new SecretKeySpec(keyBytes, "AES");
    Cipher cipher;

    try {
        // TODO move this to some general library initialization code
        removeCryptoStrengthRestriction();

        cipher = Cipher.getInstance(cipherInstance, new BouncyCastleProvider());
        cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));

        if (encAlg.contains("GCM")) {
            cipher.updateAAD(header.getBytes());

            // Concatenate ciphertext and authentication tag byte arrays
            byte[] concat = new byte[cipherBytes.length + authTag.length];
            System.arraycopy(cipherBytes, 0, concat, 0, cipherBytes.length);
            System.arraycopy(authTag, 0, concat, cipherBytes.length, authTag.length);

            decryptedContent = cipher.doFinal(concat);
        } else {
            decryptedContent = cipher.doFinal(cipherBytes);
        }

    } catch (Exception e) {
        throw new DecryptionFailedException(e.getMessage());
    }

    return decryptedContent;

}

From source file:eu.dety.burp.joseph.utilities.CryptoTest.java

License:Open Source License

@Test
public void testAES256() throws Exception {
    Crypto.removeCryptoStrengthRestriction();

    Cipher encryptCipher = Cipher.getInstance("AES/CBC/NoPadding", new BouncyCastleProvider());
    IvParameterSpec encryptIv = new IvParameterSpec(new byte[16]);
    SecretKey encryptKey = new SecretKeySpec(new byte[32], "AES");
    encryptCipher.init(Cipher.ENCRYPT_MODE, encryptKey, encryptIv);

}

From source file:eu.ebbitsproject.peoplemanager.utils.SslUtil.java

static SSLSocketFactory getSocketFactory(final String caCrtFile) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    // load CA certificate
    PEMReader reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
    X509Certificate caCert = (X509Certificate) reader.readObject();
    reader.close();/* w ww .  j  av  a 2  s . co m*/

    // CA certificate is used to authenticate server
    KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
    caKs.load(null, null);
    caKs.setCertificateEntry("ca-certificate", caCert);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(caKs);

    // create an empty kmf (we don't actually need it)
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, null);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, "".toCharArray());

    // finally, create SSL socket factory
    SSLContext context = SSLContext.getInstance("TLSv1");
    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

From source file:eu.eidas.auth.engine.core.impl.EncryptionSW.java

License:EUPL

/**
 * Load cryptographic service provider.//from  w w  w .  j  av  a  2 s .com
 *
 * @throws SAMLEngineException the SAML engine exception
 */
private final void loadCryptServiceProvider() throws SAMLEngineException {
    LOG.debug("Loading Encryption Cryptographic Service Provider");
    try {
        // Dynamically register Bouncy Castle provider.
        boolean found = false;
        // Check if BouncyCastle is already registered as a provider
        final Provider[] providers = Security.getProviders();
        for (int i = 0; i < providers.length; i++) {
            if (providers[i].getName().equals(BouncyCastleProvider.PROVIDER_NAME)) {
                found = true;
            }
        }

        // Register only if the provider has not been previously registered
        if (!found) {
            LOG.debug("SAMLCore: Register Bouncy Castle provider.");
            Security.insertProviderAt(new BouncyCastleProvider(), Security.getProviders().length);
        } else {
            LOG.debug("SAMLCore: Bouncy Castle provider already registered.");
        }

    } catch (Exception e) {
        LOG.error("ERROR : Error loading encryption CryptographicServiceProvider", e.getMessage());
        throw new SAMLEngineException(EIDASErrors.SAML_ENGINE_LOAD_PROVIDER.errorCode(),
                EIDASErrors.SAML_ENGINE_LOAD_PROVIDER.errorMessage(), e);
    }
}

From source file:eu.eidas.auth.engine.core.impl.SignP12.java

License:EUPL

/**
 * Load cryptographic service provider./* w w w. j av a2 s .c o m*/
 * 
 * @throws SAMLEngineException the SAML engine exception
 */
public void loadCryptServiceProvider() throws SAMLEngineException {
    LOG.info("Load Cryptographic Service Provider");

    FileInputStream fis = null;
    FileInputStream fisTrustStore = null;

    try {
        // Dynamically register Bouncy Castle provider.
        boolean found = false;
        // Check if BouncyCastle is already registered as a provider
        final Provider[] providers = Security.getProviders();
        for (int i = 0; i < providers.length; i++) {
            if (providers[i].getName().equals(BouncyCastleProvider.PROVIDER_NAME)) {
                found = true;
            }
        }

        // Register only if the provider has not been previously registered
        if (!found) {
            LOG.debug("SAMLCore: Register Bouncy Castle provider.");
            Security.insertProviderAt(new BouncyCastleProvider(), Security.getProviders().length);
        }

        p12Store = KeyStore.getInstance(getProperties().getProperty("keystoreType"));

        fis = new FileInputStream(getProperties().getProperty("keystorePath"));

        p12Store.load(fis, getProperties().getProperty("keyStorePassword").toCharArray());

        trustStore = KeyStore.getInstance(getProperties().getProperty("trustStoreType"));

        fisTrustStore = new FileInputStream(getProperties().getProperty("trustStorePath"));
        trustStore.load(fisTrustStore, getProperties().getProperty("trustStorePassword").toCharArray());

    } catch (Exception e) {
        throw new SAMLEngineException("Error loading CryptographicServiceProvider", e);
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fisTrustStore);
    }
}

From source file:eu.eidas.auth.engine.core.impl.SignSW.java

License:EUPL

/**
 * Load cryptographic service provider.//w  w w .  ja  va  2s. c o  m
 *
 * @throws SAMLEngineException the SAML engine exception
 */
public final void loadCryptServiceProvider() throws SAMLEngineException {
    LOG.info("Load Cryptographic Service Provider");
    try {
        // Dynamically register Bouncy Castle provider.
        boolean found = false;
        // Check if BouncyCastle is already registered as a provider
        final Provider[] providers = Security.getProviders();
        for (int i = 0; i < providers.length; i++) {
            if (providers[i].getName().equals(BouncyCastleProvider.PROVIDER_NAME)) {
                found = true;
            }
        }

        // Register only if the provider has not been previously registered
        if (!found) {
            LOG.debug("SAMLCore: Register Bouncy Castle provider.");
            Security.insertProviderAt(new BouncyCastleProvider(), 0);
        }

        ownKeyStore = loadKeystore(null);
        metadatKeyStore = loadKeystore(PROPERTY_PREFIX_METADATA);

    } catch (Exception e) {
        LOG.info("ERROR : Error loading CryptographicServiceProvider", e.getMessage());
        LOG.debug("ERROR : Error loading CryptographicServiceProvider", e);
        throw new SAMLEngineException("Error loading CryptographicServiceProvider", e);
    }
}

From source file:eu.europa.ec.markt.dss.applet.controller.DSSAppletController.java

License:Open Source License

/**
 * The default constructor for DSSAppletController.
 *
 * @param core/*from w w w . ja  v  a  2 s.  c om*/
 * @param model
 */
protected DSSAppletController(final DSSAppletCore core, final M model) {
    super(core, model);

    Security.addProvider(new BouncyCastleProvider());

    final Parameters parameters = core.getParameters();

    serviceURL = parameters.getServiceURL();

}

From source file:eu.europa.ec.markt.dss.applet.SignatureValidationReportPanel.java

License:Open Source License

/** Creates new form SignatureValidationReport */
public SignatureValidationReportPanel(SignatureWizardModel model) {

    Security.addProvider(new BouncyCastleProvider());

    initComponents();// w  w w.java 2 s. c  om
    this.model = model;

    // ToolTipManager.sharedInstance().registerComponent(jTree1);
    TooltipHelper.registerComponentAtTooltipManager(jTree1);

    jTree1.setCellRenderer(new SignedDocumentTreeCellRenderer());
}