Example usage for javax.crypto Cipher getProvider

List of usage examples for javax.crypto Cipher getProvider

Introduction

In this page you can find the example usage for javax.crypto Cipher getProvider.

Prototype

public final Provider getProvider() 

Source Link

Document

Returns the provider of this Cipher object.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");

    System.out.println(cipher.getProvider());

    cipher = Cipher.getInstance("Blowfish/ECB/NoPadding", "BC");

    System.out.println(cipher.getProvider());
}

From source file:com.evolveum.midpoint.prism.crypto.AESProtector.java

private Cipher getCipher(int cipherMode, String algorithmUri)
        throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException,
        InvalidAlgorithmParameterException {
    String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithmUri);//JCEMapper.getJCEKeyAlgorithmFromURI(algorithmUri);
    Cipher cipher;
    if (requestedJceProviderName == null) {
        cipher = Cipher.getInstance(jceAlgorithm);
    } else {//from   w  w w.  j  a v a  2 s.  co  m
        cipher = Cipher.getInstance(jceAlgorithm, requestedJceProviderName);
    }
    if (LOGGER.isTraceEnabled()) {
        String desc;
        if (cipherMode == Cipher.ENCRYPT_MODE) {
            desc = "Encrypting";
        } else if (cipherMode == Cipher.DECRYPT_MODE) {
            desc = "Decrypting";
        } else {
            desc = "Ciphering (mode " + cipherMode + ")";
        }
        LOGGER.trace("{} data by JCE algorithm {} (URI {}), cipher {}, provider {}", new Object[] { desc,
                jceAlgorithm, algorithmUri, cipher.getAlgorithm(), cipher.getProvider().getName() });
    }
    return cipher;
}

From source file:it.doqui.index.ecmengine.business.personalization.encryption.content.EncryptingContentWriterDecorator.java

public OutputStream getContentOutputStream() throws ContentIOException {
    logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] BEGIN");

    IvParameterSpec iv = null;//  w  ww  .j  a v  a2 s. c  om

    try {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec),
                    "SunJCE");
        } catch (NoSuchProviderException e) {
            logger.warn(
                    "[EncryptingContentWriterDecorator::getContentOutputStream] Unknown provider \"SunJCE\". Using default...");
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec));
        }

        if (transformationSpec.getMode() != null && !transformationSpec.getMode().equalsIgnoreCase("ECB")) {
            iv = new IvParameterSpec(transformationSpec.getIv());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        }

        logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] "
                + "Cipher initialized: ENCRYPT - " + cipher.getProvider() + " - " + cipher.getAlgorithm());

        CipherOutputStream cos = new CipherOutputStream(writer.getContentOutputStream(), cipher);

        return cos;
    } catch (NoSuchPaddingException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid padding: "
                + transformationSpec.getPadding());
        throw new EncryptionRuntimeException("Invalid padding: " + transformationSpec.getPadding(), e);
    } catch (NoSuchAlgorithmException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid algorithm: "
                + transformationSpec.getAlgorithm());
        throw new EncryptionRuntimeException("Invalid algorithm: " + transformationSpec.getAlgorithm(), e);
    } catch (InvalidKeyException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid key!");
        throw new EncryptionRuntimeException("Invalid key!", e);
    } catch (InvalidAlgorithmParameterException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid algorithm parameter: "
                + iv);
        throw new EncryptionRuntimeException("Invalid algorithm parameter: " + iv, e);
    } finally {
        logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] END");
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.encryption.content.DecryptingContentReaderDecorator.java

public InputStream getContentInputStream() throws ContentIOException {
    logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] BEGIN");

    IvParameterSpec iv = null;//from www  .  ja  va  2 s.  c o m

    try {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec),
                    "SunJCE");
        } catch (NoSuchProviderException e) {
            logger.warn(
                    "[DecryptingContentReaderDecorator::getContentInputStream] Unknown provider \"SunJCE\". Using default...");
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec));
        }

        if (transformationSpec.getMode() != null && !transformationSpec.getMode().equalsIgnoreCase("ECB")) {
            iv = new IvParameterSpec(transformationSpec.getIv());
            logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] IvParameterSpec: " + iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
        }

        logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] "
                + "Cipher initialized: DECRYPT - " + cipher.getProvider() + " - " + cipher.getAlgorithm());

        CipherInputStream cis = new CipherInputStream(reader.getContentInputStream(), cipher);
        return cis;
    } catch (NoSuchPaddingException e) {
        logger.warn("[DecryptingContentReaderDecorator::getContentInputStream] Invalid padding: "
                + transformationSpec.getPadding());
        throw new EncryptionRuntimeException("Invalid padding: " + transformationSpec.getPadding(), e);
    } catch (NoSuchAlgorithmException e) {
        logger.warn("[DecryptingContentReaderDecorator::getContentInputStream] Invalid algorithm: "
                + transformationSpec.getAlgorithm());
        throw new EncryptionRuntimeException("Invalid algorithm: " + transformationSpec.getAlgorithm(), e);
    } catch (InvalidKeyException e) {
        logger.warn("[DecryptingContentReaderDecorator::getContentInputStream] Invalid key!");
        throw new EncryptionRuntimeException("Invalid key!", e);
    } catch (InvalidAlgorithmParameterException e) {
        logger.warn(
                "[DecryptingContentReaderDecorator::getContentInputStream] Invalid algorithm parameter: " + iv);
        throw new EncryptionRuntimeException("Invalid algorithm parameter: " + iv, e);
    } finally {
        logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] END");
    }
}

From source file:org.aon.esolutions.appconfig.client.util.RSAEncryptUtil.java

/**
 * Encrypt a text using public key.//from w ww  . j a  v a  2  s .co m
 * @param text The original unencrypted text
 * @param key The public key
 * @return Encrypted text
 * @throws java.lang.Exception
 */
public static byte[] encrypt(byte[] text, Key key) throws Exception {
    byte[] cipherText = null;
    try {
        //
        // get an RSA cipher object and print the provider
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        if (_log.isDebugEnabled()) {
            _log.debug("\nProvider is: " + cipher.getProvider().getInfo());
            _log.debug("\nStart encryption with public key");
        }

        // encrypt the plaintext using the public key
        cipher.init(Cipher.ENCRYPT_MODE, key);
        cipherText = cipher.doFinal(text);
    } catch (Exception e) {
        throw e;
    }
    return cipherText;
}

From source file:org.grycap.gpf4med.security.FileEncryptionProvider.java

/**
 * Creates a new {@link FileEncryptionProvider} instance that provides encryption/decryption
 * capabilities based on the specified password.
 * @param password encryption/decryption password.
 * @return a new {@link FileEncryptionProvider} instance.
 * @throws Exception if an error occurs in the execution of the operation.
 *//*  w  w w. j  a  v  a2 s.  c  om*/
public static FileEncryptionProvider getInstance(final String password) throws Exception {
    checkArgument(StringUtils.isNotBlank(password), "Uninitialized or invalid password");
    // generate key from password
    final byte[] salt = generateSalt();
    LOGGER.trace("Generated salt: " + Hex.encodeHexString(salt));
    final SecretKey secret = generateKey(password, salt);
    LOGGER.trace("Generated key: " + Hex.encodeHexString(secret.getEncoded()));
    // create encryption cipher - bouncycastle equivalent: Cipher.getInstance("AES/CBC/PKCS5Padding", "BC")
    final Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    encryptCipher.init(Cipher.ENCRYPT_MODE, secret);
    // initialization vector needed by the CBC mode
    final AlgorithmParameters params = encryptCipher.getParameters();
    final byte[] initVector = params.getParameterSpec(IvParameterSpec.class).getIV();
    // create decryption cipher - bouncycastle equivalent: Cipher.getInstance("AES/CBC/PKCS5Padding", "BC")
    final Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    decryptCipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(initVector));
    LOGGER.trace(String.format("Encryption/decryption ciphers were created - %s",
            encryptCipher.getProvider().getInfo()));
    return new FileEncryptionProvider(encryptCipher, decryptCipher);
}

From source file:org.jumpmind.security.SecurityService.java

protected Cipher getCipher(int mode) throws Exception {
    if (secretKey == null) {
        secretKey = getSecretKey();//from   w  w w.  ja v a 2 s  .  c o  m
    }
    Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
    initializeCipher(cipher, mode);
    log.debug("Using {} algorithm provided by {}.", cipher.getAlgorithm(), cipher.getProvider().getName());
    return cipher;
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testSoftwareRSAKeyWrapping() throws Exception {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    final SecretKey secretKey = keyGenerator.generateKey();
    LOG.debug("secret key algo: " + secretKey.getAlgorithm());

    final Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.WRAP_MODE, keyPair.getPublic());
    LOG.debug("cipher security provider: " + cipher.getProvider().getName());
    LOG.debug("cipher type: " + cipher.getClass().getName());
    final byte[] wrappedKey = cipher.wrap(secretKey);

    cipher.init(Cipher.UNWRAP_MODE, keyPair.getPrivate());
    final Key resultKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

    assertArrayEquals(secretKey.getEncoded(), resultKey.getEncoded());

}

From source file:test.unit.org.owasp.webscarab.plugin.saml.SamlTest.java

@Test
public void testEncryptionAES() throws Exception {
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(128);//w  w  w  .  ja  va 2  s . co m
    SecretKey secretKey = keygen.generateKey();

    LOG.debug("secret key algo: " + secretKey.getAlgorithm());
    LOG.debug("secret key format: " + secretKey.getFormat());

    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    LOG.debug("cipher provider: " + cipher.getProvider().getName());
    byte[] result = cipher.doFinal("hello world".getBytes());
    assertNotNull(result);

    byte[] encodedSecretKey = secretKey.getEncoded();
    LOG.debug("encoded secret key size: " + encodedSecretKey.length * 8);

    // decrypt
    cipher = Cipher.getInstance("AES");
    SecretKeySpec secretKeySpec = new SecretKeySpec(encodedSecretKey, "AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] decryptedResult = cipher.doFinal(result);
    assertEquals("hello world", new String(decryptedResult));
}