Example usage for javax.crypto Cipher DECRYPT_MODE

List of usage examples for javax.crypto Cipher DECRYPT_MODE

Introduction

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

Prototype

int DECRYPT_MODE

To view the source code for javax.crypto Cipher DECRYPT_MODE.

Click Source Link

Document

Constant used to initialize cipher to decryption mode.

Usage

From source file:com.feedzai.commons.sql.abstraction.util.AESHelper.java

/**
 * Decrypts a string encrypted by {@link #encrypt} method.
 *
 * @param c   The encrypted HEX string./*from  ww  w.java 2  s .  c o m*/
 * @param key The  key.
 * @return The decrypted string.
 */
public static String decrypt(String c, String key) {
    try {
        SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decoded = cipher.doFinal(Hex.decodeHex(c.toCharArray()));
        return new String(decoded);
    } catch (Exception e) {
        logger.warn("Could not decrypt string", e);
        return null;
    }
}

From source file:jp.co.golorp.emarf.util.CryptUtil.java

/**
 * Base64??AES????//from www . ja va 2  s. com
 *
 * @param encryped
 *            ?
 * @return ?
 */
public static String decrypt(final String encryped) {

    if (encryped == null) {
        return null;
    }

    byte[] input = Base64.decodeBase64(encryped);

    byte[] decrypted = cipher(Cipher.DECRYPT_MODE, input);

    String ret = new String(decrypted);

    LOG.debug("Decrypt [" + encryped + "] to [" + ret + "].");

    return ret;
}

From source file:com.elle.analyster.admissions.AESCrypt.java

public static String decrypt(String key, String initVector, String encrypted) {
    try {//  w  w w.  j av a  2 s  . c o  m
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

        byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

        return new String(original);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return null;
}

From source file:com.centurylink.mdw.util.CryptUtil.java

public static String decrypt(String input) throws GeneralSecurityException {
    byte[] decoded = decodeBase64(input);
    cipher.init(Cipher.DECRYPT_MODE, key64);
    byte[] decrypted = cipher.doFinal(decoded);
    return new String(decrypted).trim();
}

From source file:Main.java

static byte[] decryptJWE(String jwe, Key privRsaKey) {
    // Log.d("","decryptJWE");

    try {/*  w  w w  . j  av  a  2  s  .c  o  m*/
        // split jwe string
        StringTokenizer tokens = new StringTokenizer(jwe, ".");
        int count = tokens.countTokens();
        // Log.d("","parts.length: "+count);

        if (count != 5)
            return null;

        String jweProtectedHeader64 = tokens.nextToken();
        String jweEncrypted64 = tokens.nextToken();
        String jweInitVector64 = tokens.nextToken();
        String cryptedBytes64 = tokens.nextToken();
        String auth_tag64 = tokens.nextToken();

        // decrypt cek using private rsa key
        byte[] cek = decryptRsaB64(jweEncrypted64, privRsaKey);

        // check cek result byte array
        if (cek == null || cek.length == 0 || (cek.length % 2) != 0)
            return null;

        int keySize = cek.length / 2;
        Log.d("", "Decryption AES: " + keySize * 8);

        // build aes_key and hmac_key
        byte aes_key[] = new byte[keySize];
        byte hmac_key[] = new byte[keySize];

        System.arraycopy(cek, 0, hmac_key, 0, keySize);
        System.arraycopy(cek, keySize, aes_key, 0, keySize);

        // decode initialization vector
        byte[] iv_key = decodeB64(jweInitVector64);

        Log.d("", "hmac_key: " + bytesToHex(hmac_key));
        Log.d("", "aes_key:  " + bytesToHex(aes_key));
        Log.d("", "iv_key:   " + bytesToHex(iv_key));

        // decrypt content using aes_key and iv_key
        byte[] cryptedBytes = decodeB64(cryptedBytes64);
        Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SC");
        decrypt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aes_key, "AES"), new IvParameterSpec(iv_key));
        byte[] decryptedBytes = decrypt.doFinal(cryptedBytes);

        Log.d("", "decryptedBytes:");
        Log.d("", bytesToHex(decryptedBytes));

        // validation verification
        byte[] aad = jweProtectedHeader64.getBytes();
        long al = aad.length * 8;

        // concatenate aad, iv_key, cryptedBytes and al 
        byte[] hmacData = new byte[aad.length + iv_key.length + cryptedBytes.length + 8];
        int offset = 0;
        System.arraycopy(aad, offset, hmacData, 0, aad.length);
        offset += aad.length;
        System.arraycopy(iv_key, 0, hmacData, offset, iv_key.length);
        offset += iv_key.length;
        System.arraycopy(cryptedBytes, 0, hmacData, offset, cryptedBytes.length);
        offset += cryptedBytes.length;
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.putLong(al);
        System.arraycopy(buffer.array(), 0, hmacData, offset, 8);

        // compute hmac
        Mac hmac = Mac.getInstance("HmacSHA256", "SC");
        hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));
        byte[] hmacValue = hmac.doFinal(hmacData);

        // pick authentication tag
        byte[] authTag = Arrays.copyOf(hmacValue, 16);

        // validate authentication tag
        byte[] authTagRead = decodeB64(auth_tag64);
        for (int i = 0; i < 16; i++) {
            if (authTag[i] != authTagRead[i]) {
                Log.d("", "validation failed");
                return decryptedBytes;
            }
        }

        Log.d("", "validation success");

        // validation success
        return decryptedBytes;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.boulmier.machinelearning.jobexecutor.encrypted.AES.java

public String decrypt(String strToDecrypt) {
    try {//w  w w. ja va  2s.c o m
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");

        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return (new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt))));

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException e) {

        System.out.println("Error while decrypting: " + e.toString());

    }
    return null;
}

From source file:DesEncrypter.java

private DesEncrypter(String passPhrase) {
    try {//  w w w.  ja  va 2s.com
        // Create the key
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
        SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        ecipher = Cipher.getInstance(key.getAlgorithm());
        dcipher = Cipher.getInstance(key.getAlgorithm());

        // Prepare the parameter to the ciphers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

        // Create the ciphers
        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    } catch (java.security.InvalidAlgorithmParameterException e) {
    } catch (java.security.spec.InvalidKeySpecException e) {
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    }
}

From source file:Authentication.HashPassword.java

public String decrypt(String encryptedString) {
    String decryptedText = null;//  w w w. j ava 2 s.c  om
    try {
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] encryptedText = Base64.decodeBase64(encryptedString);
        byte[] plainText = cipher.doFinal(encryptedText);
        decryptedText = new String(plainText);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return decryptedText;
}

From source file:com.ikon.util.SecureStore.java

/**
 * DES decoder/*from  w  w w  . j a  va  2s . c  o  m*/
 */
public static byte[] desDecode(String key, byte[] src)
        throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    DESKeySpec keySpec = new DESKeySpec(key.getBytes("UTF8"));
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey sKey = keyFactory.generateSecret(keySpec);

    Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
    cipher.init(Cipher.DECRYPT_MODE, sKey);
    byte[] dst = cipher.doFinal(src);

    return dst;
}

From source file:org.apigw.commons.crypto.Decrypter.java

/**
 *
 * @param encrypted An AES encrypted and Base64 encoded string
 * @return/*from  www . j ava  2 s .  c  om*/
 * @throws java.lang.RuntimeException
 */
public String decrypt(String encrypted) throws RuntimeException {
    log.debug("About to decrypt the string: {}", encrypted);
    if (encrypted == null) {
        log.trace("incoming message is null, returning null");
        return null;
    }
    if (useEncryption) {
        try {
            byte[] encryptedBytes = Base64.decodeBase64(encrypted.getBytes("utf8"));
            SecretKeySpec skeySpec = getSecretKeySpec();
            IvParameterSpec ivParameterSpec = getIvParameterSpec();
            Cipher decryptCipher = getCipher();
            decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
            byte[] decrypted = decryptCipher.doFinal(encryptedBytes);
            log.debug("Message decrypted.");
            return new String(decrypted, "utf8");
        } catch (Exception e) {
            log.error("Caught an error while decrypting", e);
            throw new RuntimeException(e);
        }
    } else {
        log.debug("Encryption is disabled, will not decrypt message");
        return encrypted;
    }
}