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.glaf.core.security.DefaultEncryptor.java

public byte[] decrypt(byte[] bytes)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    return crypt(Cipher.DECRYPT_MODE, bytes);
}

From source file:cn.util.RSAUtils.java

/**
 * ?   /*w  w w.ja va 2  s  .  c o  m*/
 * 
 * @param data  116#
 * @param privateKey
 * @return
 * @throws Exception
 */
public static String decryptByPrivateKeySplit(String data) throws Exception {

    RSAPrivateKey privateKey = getPrivateKey();
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    String stringarray[] = data.split("#");

    List<byte[]> srcArrays = new ArrayList<byte[]>();

    for (String stemp : stringarray) {
        byte[] byte_temp = Base64Util.decryptBASE64(stemp);
        byte_temp = cipher.doFinal(byte_temp);
        srcArrays.add(byte_temp);

    }

    byte[] byte_sta = sysCopy(srcArrays);

    return new String(byte_sta);

}

From source file:com.launchkey.sdk.crypto.JCECrypto.java

/**
 * @see Crypto#decryptRSA(byte[])//from ww  w.j a v  a2 s  .  c o  m
 */
public byte[] decryptAES(byte[] message, byte[] key, byte[] iv) throws GeneralSecurityException {
    return processAES(Cipher.DECRYPT_MODE, message, key, iv);
}

From source file:info.magnolia.cms.security.SecurityUtil.java

public static String decrypt(String message, String encodedKey) throws SecurityException {
    try {/*from  www. j  ava 2s  . co  m*/
        if (StringUtils.isBlank(encodedKey)) {
            throw new SecurityException(
                    "Activation key was not found. Please make sure your instance is correctly configured.");
        }

        // decode key
        byte[] binaryKey = hexToByteArray(encodedKey);

        // create RSA public key cipher
        Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC");
        try {
            // create private key
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PublicKey pk = kf.generatePublic(publicKeySpec);
            pkCipher.init(Cipher.DECRYPT_MODE, pk);

        } catch (InvalidKeySpecException e) {
            // decrypting with private key?
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PrivateKey pk = kf.generatePrivate(privateKeySpec);
            pkCipher.init(Cipher.DECRYPT_MODE, pk);
        }

        // decrypt
        String[] chunks = StringUtils.split(message, ";");
        if (chunks == null) {
            throw new SecurityException(
                    "The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message.");
        }
        StringBuilder clearText = new StringBuilder();
        for (String chunk : chunks) {
            byte[] byteChunk = hexToByteArray(chunk);
            clearText.append(new String(pkCipher.doFinal(byteChunk), "UTF-8"));
        }
        return clearText.toString();
    } catch (NumberFormatException e) {
        throw new SecurityException(
                "The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message.",
                e);
    } catch (IOException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchPaddingException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (InvalidKeySpecException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (InvalidKeyException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchProviderException e) {
        throw new SecurityException(
                "Failed to find encryption provider. Please use Java version with cryptography support.", e);
    } catch (IllegalBlockSizeException e) {
        throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.",
                e);
    } catch (BadPaddingException e) {
        throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.",
                e);
    }

}

From source file:com.baidu.rigel.biplatform.ac.util.AesUtil.java

/**
 * ??//from w w  w.j  a  va  2s  .c o m
 * 
 * @param encryptedData 
 * @param keyValue 
 * @return ?
 * @throws IllegalArgumentException 
 * @throws Exception 
 */
public String decrypt(String encryptedData, String keyValue) throws Exception {
    if (StringUtils.isBlank(encryptedData)) {
        throw new IllegalArgumentException("decode string can not be blank!");
    }
    Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
    ;
    Key key = generateKey(keyValue);
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decordedValue = Base64.getDecoder().decode(encryptedData);
    byte[] decValue = cipher.doFinal(decordedValue);
    String decryptedValue = new String(decValue);
    return decryptedValue;
}

From source file:com.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <P>//  w  w w.ja  v  a  2 s .  com
 * ?
 * </p>
 * 
 * @param encryptedData ?
 * @param privateKey ?(BASE64?)
 * @return byte
 * @throws Exception Exception
 */
@SuppressWarnings({ "PMD.ShortVariable", "PMD.AvoidDuplicateLiterals" })
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateK);
    int inputLen = encryptedData.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // ?
    while (inputLen - offSet > 0) {
        if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
            cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
        } else {
            cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
        }
        out.write(cache, 0, cache.length);
        i++;
        offSet = i * MAX_DECRYPT_BLOCK;
    }
    byte[] decryptedData = out.toByteArray();
    out.close();
    return decryptedData;
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.Cipherer.java

/**
* Initializes the encoder and decoder. /*ww w  . jav  a2  s  .  co m*/
* Note: The vaues of CIPHER_TRANSFORMATION, KEY_BYTES, KEY_ALGORITHM should be set before calling this method,
*       otherwise it will use the default values.
*/
public void init() {
    try {
        /*
                 byte[] nonce = new byte[16];
                 NONCE_GEN.nextBytes(nonce);
                 AlgorithmParameterSpec paramSpec = new IvParameterSpec(nonce);
        */
        AlgorithmParameterSpec paramSpec = cipherTransformation.toUpperCase().startsWith("AES")
                ? new IvParameterSpec(INIT_VECTOR_16)
                : new IvParameterSpec(INIT_VECTOR_8);

        E_CIPHER = Cipher.getInstance(cipherTransformation);
        D_CIPHER = Cipher.getInstance(cipherTransformation);

        SecretKeySpec spec = new SecretKeySpec(keyBytes, keyAlgorithm);

        // CBC requires an initialization vector
        E_CIPHER.init(Cipher.ENCRYPT_MODE, spec, paramSpec);
        D_CIPHER.init(Cipher.DECRYPT_MODE, spec, paramSpec);
    } catch (Exception e) {
        log.error("Cipher init failed", e);
        throw new RuntimeException(e);
    }
}

From source file:architecture.common.adaptor.connector.jdbc.AbstractJdbcConnector.java

protected List<Map<String, Object>> pull(final String queryString,
        final List<ParameterMapping> parameterMappings, final Object[] args) {

    // log.debug("pulling..." );

    return getJdbcTemplate().query(queryString, args, new RowMapper<Map<String, Object>>() {
        public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            Map<String, Object> mapOfColValues = createColumnMap(columnCount);
            for (int i = 1; i <= columnCount; i++) {
                String key = getColumnKey(lookupColumnName(rsmd, i));
                Object obj = getColumnValue(rs, i);
                mapOfColValues.put(key, obj);
            }//from www .j av a 2 s. c o  m

            return mapOfColValues;
        }

        protected Map<String, Object> createColumnMap(int columnCount) {
            return new LinkedHashMap<String, Object>(columnCount);
        }

        protected String getColumnKey(String columnName) {
            return columnName;
        }

        protected Object getColumnValue(ResultSet rs, int index) throws SQLException {

            for (ParameterMapping mapping : parameterMappings) {
                // LOG.debug( index + " mapping match :" +
                // mapping.getIndex());
                if (index == mapping.getIndex()) {
                    if (String.class == mapping.getJavaType()) {

                        String value = rs.getString(index);
                        if (StringUtils.isEmpty(value))
                            value = "";

                        if (!StringUtils.isEmpty(mapping.getCipher())) {
                            try {
                                Cipher cipher = Cipher.getInstance(mapping.getCipher());
                                SecretKeySpec skeySpec = new SecretKeySpec(
                                        Hex.decodeHex(mapping.getCipherKey().toCharArray()),
                                        mapping.getCipherKeyAlg());
                                cipher.init(Cipher.DECRYPT_MODE, skeySpec);

                                byte raw[];
                                if (!StringUtils.isEmpty(mapping.getEncoding())) {
                                    String enc = mapping.getEncoding();
                                    if (enc.toUpperCase().equals("BASE64")) {
                                        raw = Base64.decodeBase64(value);
                                        // BASE64Decoder decoder = new
                                        // BASE64Decoder();
                                        // raw =
                                        // decoder.decodeBuffer(value);
                                    } else {
                                        raw = value.getBytes();
                                    }
                                } else {
                                    raw = value.getBytes();
                                }
                                byte stringBytes[] = cipher.doFinal(raw);
                                return new String(stringBytes);

                            } catch (Exception e) {
                                LOG.error(e);
                            }
                            return value;
                        }

                        if (!StringUtils.isEmpty(mapping.getEncoding())) {
                            String[] encoding = StringUtils.split(mapping.getEncoding(), ">");
                            try {
                                if (encoding.length == 2)
                                    return new String(value.getBytes(encoding[0]), encoding[1]);
                                else if (encoding.length == 1) {
                                    return new String(value.getBytes(), encoding[0]);
                                }
                            } catch (UnsupportedEncodingException e) {
                                LOG.error(e);
                                return value;
                            }
                        }

                    } else if (Long.class == mapping.getJavaType()) {
                        String value = rs.getString(index);
                        if (StringUtils.isEmpty(value))
                            value = "0";
                        return new Long(value);
                    } else if (Integer.class == mapping.getJavaType()) {
                        String value = rs.getString(index);
                        if (StringUtils.isEmpty(value))
                            value = "0";
                        return new Integer(value);
                    } else if (Double.class == mapping.getJavaType()) {
                        String value = rs.getString(index);
                        if (StringUtils.isEmpty(value))
                            value = "0";
                        return new Double(value);
                    }
                }
            }
            return JdbcUtils.getResultSetValue(rs, index);
        }
    });
}

From source file:net.fender.crypto.CryptoUtil.java

public String decrypt(Key key, String base64Encoded) throws GeneralSecurityException {
    byte[] encryptedBytes = Base64.decodeBase64(base64Encoded.getBytes());
    Cipher cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
    String decrypted = new String(decryptedBytes);
    return decrypted;
}

From source file:de.alpharogroup.crypto.aes.HexDecryptor.java

/**
 * Initializes the {@link SimpleDecryptor} object.
 *
 * @throws UnsupportedEncodingException//w  w w  .  ja v  a2  s.  c om
 *             is thrown by get the byte array of the private key String object fails.
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the cypher object fails.
 * @throws NoSuchPaddingException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeyException
 *             the invalid key exception is thrown if initialization of the cypher object fails.
 */
private void initialize() throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException {
    if (!isInitialized()) {
        byte[] key;
        if (this.getPrivateKey() != null) {
            key = this.getPrivateKey().getBytes("UTF-8");
        } else {
            key = CryptConst.PRIVATE_KEY.getBytes("UTF-8");
        }
        final SecretKeySpec skeySpec = new SecretKeySpec(key, Algorithm.AES.getAlgorithm());
        this.cipher = Cipher.getInstance(Algorithm.AES.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    }
}