Example usage for javax.crypto Cipher getInstance

List of usage examples for javax.crypto Cipher getInstance

Introduction

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

Prototype

public static final Cipher getInstance(String transformation)
        throws NoSuchAlgorithmException, NoSuchPaddingException 

Source Link

Document

Returns a Cipher object that implements the specified transformation.

Usage

From source file:com.haulmont.cuba.web.test.PasswordEncryptionTest.java

protected String encryptPassword(String password) {
    SecretKeySpec key = new SecretKeySpec(PASSWORD_KEY.getBytes(), "DES");
    IvParameterSpec ivSpec = new IvParameterSpec(PASSWORD_KEY.getBytes());
    String result;//w w  w .  jav  a  2s  .  com
    try {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
        result = new String(Hex.encodeHex(cipher.doFinal(password.getBytes())));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:adminpassword.AESDemo.java

public String encrypt(String plainText) throws Exception {

    //get salt/*from   www .j a va2s .  c  o m*/
    salt = generateSalt();
    byte[] saltBytes = salt.getBytes("UTF-8");

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, pswdIterations, keySize);

    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    //encrypt the message
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
    return new Base64().encodeAsString(encryptedTextBytes);
}

From source file:com.app.utils.StringEncrypt.java

/**
 * Funcin de tipo String que recibe una llave (key), un vector de inicializacin (iv)
 * y el texto que se desea descifrar//from w w w. jav a2 s . co  m
 * @param key la llave en tipo String a utilizar
 * @param iv el vector de inicializacin a utilizar
 * @param encrypted el texto cifrado en modo String
 * @return el texto desencriptado en modo String
 * @throws Exception puede devolver excepciones de los siguientes tipos: NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException
 */
public static String decrypt(String key, String iv, String encrypted) throws Exception {
    Cipher cipher = Cipher.getInstance(cI);
    SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), alg);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
    byte[] enc = decodeBase64(encrypted);
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
    byte[] decrypted = cipher.doFinal(enc);
    return new String(decrypted);
}

From source file:Main.java

/**
 * More flexible AES encrypt that doesn't encode
 *
 * @param key     AES key typically 128, 192 or 256 bit
 * @param iv      Initiation Vector//from w  w w.j  av a 2s.c o m
 * @param message in bytes (assumed it's already been decoded)
 * @return Encrypted cipher text (not encoded)
 * @throws GeneralSecurityException if something goes wrong during encryption
 */
public static byte[] encrypt(final SecretKeySpec key, final byte[] iv, final byte[] message)
        throws GeneralSecurityException {
    final Cipher cipher = Cipher.getInstance(AES_MODE);
    IvParameterSpec ivSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    //        cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] cipherText = cipher.doFinal(message);

    log("cipherText", cipherText);

    return cipherText;
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static String decryptStringImpl(Context context, final String encryptedText) {
    String plainText = null;/*from  ww w.j  a v a2 s . c  o  m*/
    try {
        final KeyStore keyStore = getKeyStore(context);

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(KEY_ALIAS, null);

        String algorithm = ALGORITHM_OLD;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            algorithm = ALGORITHM;
        }
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        CipherInputStream cipherInputStream = new CipherInputStream(
                new ByteArrayInputStream(Base64.decode(encryptedText, Base64.DEFAULT)), cipher);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int b;
        while ((b = cipherInputStream.read()) != -1) {
            outputStream.write(b);
        }
        outputStream.close();
        plainText = outputStream.toString("UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return plainText;
}

From source file:com.wso2telco.proxy.util.DecryptAES.java

public static String decrypt(String encryptedText) throws NoSuchPaddingException, NoSuchAlgorithmException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException, ConfigurationException {
    if (encryptionKey != null) {
        byte[] encryptionKeyByteValue = encryptionKey.getBytes();
        SecretKey secretKey = new SecretKeySpec(encryptionKeyByteValue, AuthProxyConstants.ASE_KEY);
        String decryptedText = null;
        if (encryptedText != null) {
            byte[] encryptedTextByte = Base64.decodeBase64(encryptedText);
            Cipher cipher = Cipher.getInstance("AES");

            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
            decryptedText = new String(decryptedByte);
        }//from   w  ww  . j  a va 2s  . c  o  m
        return decryptedText;
    } else {
        throw new ConfigurationException("MSISDN EncryptionKey could not be found in mobile-connect.xml");
    }
}

From source file:com.scorpio4.util.io.IOStreamCrypto.java

public CipherOutputStream encrypt(OutputStream out) throws NoSuchPaddingException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, InvalidKeyException {
    final SecretKey key = new SecretKeySpec(bytePassword, cipherSpec);
    final IvParameterSpec IV = new IvParameterSpec(ivBytes);
    final Cipher cipher = Cipher.getInstance(cipherTransformation);
    cipher.init(Cipher.ENCRYPT_MODE, key, IV);
    return new CipherOutputStream(new Base64OutputStream(out), cipher);
}

From source file:com.searchcode.app.util.AESEncryptor.java

public byte[] encrypt(byte[] plainText) throws Exception {
    SecretKeySpec secretKey = new SecretKeySpec(this.key, this.ALGORITHM);
    Cipher cipher = Cipher.getInstance(this.ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    return cipher.doFinal(plainText);
}

From source file:de.hybris.platform.b2b.punchout.services.impl.SymmetricManager.java

public static String decrypt(final String encrypted, final String key) throws PunchOutCipherException {
    String decrypted = null;//from ww  w .j  a  v a  2s .co  m

    try {
        final Key skeySpec = new SecretKeySpec(new Base64().decode(key), ALGORITHM);
        final Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);

        final byte[] decodedValue = new Base64().decode(encrypted.getBytes());
        final byte[] decryptedValue = cipher.doFinal(decodedValue);
        decrypted = new String(decryptedValue);
    } catch (final NoSuchAlgorithmException | NoSuchPaddingException e) {
        // should never happen
        LOG.error("System was unable instantiate Cipher.", e);
    } catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
        final String msg = "Error occured during decryption." + e.getMessage();
        LOG.info(msg);
        throw new PunchOutCipherException(msg, e);
    }
    return decrypted;
}

From source file:de.marius_oe.cfs.cryption.Crypter.java

/**
 * Returns the {@link Cipher} for the encryption and decryption process.
 * //from w  w  w .  ja  v a  2 s .c o m
 * @param mode
 *            {@link Cipher.DECRYPT_MODE} or {@link Cipher.ENCRYPT_MODE}
 * @param iv
 *            the initial vector which should be used in the cipher. if the
 *            iv is <code>null</code>, a new iv will be generated.
 * @return {@link Cipher} object
 */
private static Cipher getCipher(int mode, byte[] iv) {
    try {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        if (iv == null) {
            cipher.init(mode, KeyManager.instance().getKey());
        } else {
            IvParameterSpec parameterSpec = new IvParameterSpec(iv);
            cipher.init(mode, KeyManager.instance().getKey(), parameterSpec);
        }
        return cipher;
    } catch (InvalidKeyException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}