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.vmware.bdd.security.EncryptionGuard.java

/**
 * Decrypt the encrypted text against given secret key.
 * /*  ww  w . j a v  a  2 s  . c  o m*/
 * @param encodedText
 *           the encrypted string
 * @return the clear string, or null if encrypted string is null
 * @throws CommonException
 *            if input arguments is null
 */
public static String decode(String encodedText) throws GeneralSecurityException, UnsupportedEncodingException {
    if (encodedText == null) {
        return null;
    }

    if (encodedText.length() < SALT_SIZE) {
        throw EncryptionException.SHORT_ENCRYPTED_STRING(encodedText);
    }

    Key key = GuardKeyStore.getEncryptionKey();
    String salt = encodedText.substring(0, SALT_SIZE);
    String encryptedText = encodedText.substring(SALT_SIZE);

    Base64 base64 = new Base64(0); // 0 - no chunking
    byte[] encryptedBytes = base64.decode(encryptedText);

    Cipher cipher = getCiperInternal(Cipher.DECRYPT_MODE, key);
    byte[] outputBytes = cipher.doFinal(encryptedBytes);

    String outputText = new String(outputBytes, UTF8_ENCODING);
    AuAssert.check(salt.equals(outputText.substring(0, SALT_SIZE))); // Assert salt

    return outputText.substring(SALT_SIZE);
}

From source file:cn.util.RSAUtils.java

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    //      HashMap<String, Object> map = RSAUtils.getKeys();
    //      //??/*from  w ww .  j a  va2  s . c o  m*/
    //      RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
    //      RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");

    //
    String ming = "wow";
    //??
    RSAPublicKey pubKey = RSAUtils.getPublicKey();
    RSAPrivateKey priKey = RSAUtils.getPrivateKey();
    System.err.println(":" + Base64Util.encryptBASE64(pubKey.getEncoded()));
    System.err.println("?:" + Base64Util.encryptBASE64(priKey.getEncoded()));

    //?
    String mi = RSAUtils.encryptByPublicKey(ming);
    System.err.println("?:" + mi);
    //?
    //mi="aYlJTFE+cQjwsVkhmQrFnlwSPSidfPFbSaez8qw47xEfqwhPHX9na+7KoFwere3F2Incr0OoBhNt\nK8cqKwHtzuvJMW3/rz0X8n9Jld22lrsh9TOcEiq3Xwk3jTfNhGNnOEQIsOYVZs3Qqumdm0tAu7y6\nBHSE8kbfhRIPsqOys+0=";

    String[] mis = mi.split("#");

    String ming1 = "";
    for (String string : mis) {
        ming1 += RSAUtils.decryptByPrivateKey(string);
    }
    System.err.println("?:" + ming);
    System.err.println("?:" + ming1);
    // String a = "cVqjXrpazESBCFmZy5HxIy+C5o0PbYk9iCtBHBCGi8TMRPp2LpsVblrZIGrCw4s/fPEJp5pL7pBfZw4HDx412OfQpMCxezTltNNRWQBbFYCz/FHj6GeX7KAnkZhTC4hTZSHp1EyIa5EMsF6xdFtHuki98KS+75L3Z1Iln1efk2Y=";
    //      System.out.println(RSAUtils.decryptByPrivateKey(a));
    //      System.out.println(RSAUtils.decryptByPrivateKey(null));
    //      

    RSAPrivateKey privateKey = getPrivateKey();
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    //
    //int key_len = privateKey.getModulus().bitLength() / 8;

    String srcstring = "NKUsmMdJpSeAVFSk3hMwBoWsA7t/wOMc8hfzo2dwPIULOo1y0AUwPTDxVLw7AK1888rdyp/3U38y5eQUjuNQH68XN4jm7MHdRm+bnO6XUHuZLiXNFkLpVCAM5hVh6TTcOz3QIE9rhP+Up1WRxnq/PDuM/cXIeNWjBLbW4Iic9/w=#fRdhSf+a3xVktmJ6J0AJTW30wqpwQslN0Bxdyzpyr6u6VEj/Vo/5MpzZsVeIyBU/CzVvvkrvs5LKTagaA3M4thH3mz4gfMTrw746n4NhujZEUEehvNQIFdUBjKWPAI0XUtdcQQTtdUJbIWmuhTYxKParm0G8cNz5DSTRUTIw2fQ=#a9CaDtGkhVQNwgxHl0oJ8I/383pE3kE8yF76OyDtfeQsT50izuk44xQ34ersgzKkKSA8IB0W3SSw2bedsaj8A9dxrSf+S8S8w/Sg3G3/IA8pKaQqJD4idTCUFxjczf32aQbv+eUbs7fenAPKb3rpn+R+Q/c5y6jTEG5h+H27MsY=#N/dn52TTgJ+EoxTSp3weagZ+ggrIPl4rtKfzo0f/j2lMtXMfCQN7xgGiwDpv4Rele/58NV2X0ezDXjB3wtVugIA3nhKSNnsjEs/os1Zl2XO1EKuTnLGSJFSPS6yyr4o0wxHEeA52qA1UXaYS9clpjraXCDWuRrTpyQfONVDXGZ4=#P48NIZj+L8stk0CCNwAQmKZPH0/7GfOhhc9s/MONVPHBPRYo9N47Kb71PJszhrLsoEM2/VZD1Ech4HH8UmWhW6XPnVAWy/lS1nZDD/GEoTZvoN4Rw7oiWUGj2i+2SMyjcET9mnVPBUrgTmP8He5OFV6oIa1mAN95V4UkbXwYApw=#h79I/zTTAc2TA7j4k2wq5hrotElhskZudnuTViRvR2Ot9rAlFzdl1WasY0e+9pi7dCi40F5+2U7eVNuWLA9qvFKwgUSxA+z6FI++p0fAGsboJna9qwcplByYWh6DFPiPVFlRD2CTOZU+U/rfFn8wRT/qgLGyNI23/2el0fC1Bb0=";

    String stringarray[] = srcstring.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);

    System.err.println(new String(byte_sta));
}

From source file:com.cloudant.sync.datastore.encryption.DPKEncryptionUtil.java

/**
 * Decrypt an AES encrypted byte array/* w w  w  .  j  a v  a 2s.c  o  m*/
 *
 * @param key            The encryption key
 * @param iv             The iv
 * @param encryptedBytes The data to decrypt
 * @return The decrypted data
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
public static byte[] decryptAES(SecretKey key, byte[] iv, byte[] encryptedBytes)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParameter = new IvParameterSpec(iv);
    // see http://stackoverflow.com/a/11506343
    Key encryptionKey = new SecretKeySpec(key.getEncoded(), "AES");
    aesCipher.init(Cipher.DECRYPT_MODE, encryptionKey, ivParameter);
    return aesCipher.doFinal(encryptedBytes);
}

From source file:com.shenit.commons.codec.DesUtils.java

/**
 * /*from w  w  w  . j a  v a  2s.c  o  m*/
 * 
 * @param rawKeyData
 * @param encryptedData
 */
public static byte[] decrypt(byte[] encryptedData, byte[] rawKey) {
    return crypt(encryptedData, rawKey, Cipher.DECRYPT_MODE);
}

From source file:com.glaf.core.security.RSAUtils.java

/**
 * ??/* w  ww  .  ja  v  a 2  s .  c o  m*/
 * 
 * @param privateKey
 *            ?
 * @param data
 *            ??
 * @return ?
 */
public static byte[] decrypt(PrivateKey privateKey, byte[] data) throws Exception {
    Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
    ci.init(Cipher.DECRYPT_MODE, privateKey);
    return ci.doFinal(data);
}

From source file:club.jmint.crossing.specs.Security.java

public static String desDecrypt(String data, String key) throws CrossException {
    String ret = null;/*from www  .j  av  a 2 s  .  c om*/
    try {
        DESKeySpec desKey = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);

        Cipher cipher = Cipher.getInstance(CIPHER_DES_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, securekey);

        ret = new String(cipher.doFinal(Base64.decodeBase64(data)));
    } catch (Exception e) {
        CrossLog.printStackTrace(e);
        throw new CrossException(ErrorCode.COMMON_ERR_DECRYPTION.getCode(),
                ErrorCode.COMMON_ERR_DECRYPTION.getInfo());
    }
    return ret;
}

From source file:net.mobid.codetraq.utils.PasswordProcessor.java

/**
 * Decrypts a text using the <code>passPhrase</code> above and an algorithm supported
 * by your virtual machine implementation. You can change the default algorithm with
 * another algorithm, but please make sure your virtual machine supports it.
 * @param valueToDecrypt - text to decrypt
 * @return a plain text/*from  w w w .j  a  va 2s. c  o  m*/
 */
public static String decryptString(String valueToDecrypt) {
    String output = null;
    try {
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterations);
        SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterations);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
        // begin decrypting...
        byte[] encrypted = new Base64().decode(valueToDecrypt);
        byte[] utf8 = cipher.doFinal(encrypted);
        output = new String(utf8, "UTF8");
    } catch (Exception ex) {
        Logger.getLogger(PasswordProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:com.bamboocloud.im.provisioner.json.crypto.simple.SimpleDecryptor.java

@Override
public JsonValue decrypt(JsonValue value) throws JsonCryptoException {
    try {//from   www  .  ja va 2 s .c  o m
        JsonValue key = value.get("key").required();
        String cipher = value.get("cipher").required().asString();
        Key symmetricKey;
        if (key.isString()) {
            symmetricKey = select(key.asString());
        } else {
            Key privateKey = select(key.get("key").required().asString());
            Cipher asymmetric = Cipher.getInstance(key.get("cipher").required().asString());
            asymmetric.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] ciphertext = Base64.decodeBase64(key.get("data").required().asString());
            symmetricKey = new SecretKeySpec(asymmetric.doFinal(ciphertext), cipher.split("/", 2)[0]);
        }
        Cipher symmetric = Cipher.getInstance(cipher);
        String iv = value.get("iv").asString();
        IvParameterSpec ivps = (iv == null ? null : new IvParameterSpec(Base64.decodeBase64(iv)));
        symmetric.init(Cipher.DECRYPT_MODE, symmetricKey, ivps);
        byte[] plaintext = symmetric.doFinal(Base64.decodeBase64(value.get("data").required().asString()));
        return new JsonValue(mapper.readValue(plaintext, Object.class));
    } catch (GeneralSecurityException gse) { // Java Cryptography Extension
        throw new JsonCryptoException(gse);
    } catch (IOException ioe) { // Jackson
        throw new JsonCryptoException(ioe);
    } catch (JsonValueException jne) { // JSON Fluent
        throw new JsonCryptoException(jne);
    }
}

From source file:io.apiman.common.util.AesEncrypter.java

/**
 * Decrypt.// w w  w  . j a  v a2s  .c o m
 * @param encryptedText the encrypted text
 * @param secretKey the secret key
 * @return the string
 */
public static final String decrypt(String secretKey, String encryptedText) {
    if (encryptedText == null) {
        return null;
    }
    if (encryptedText.startsWith("$CRYPT::")) { //$NON-NLS-1$
        byte[] decoded = Base64.decodeBase64(encryptedText.substring(8));
        Cipher cipher;
        try {
            SecretKeySpec skeySpec = keySpecFromSecretKey(secretKey);

            cipher = Cipher.getInstance("AES"); //$NON-NLS-1$
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        try {
            String decryptedString = new String(cipher.doFinal(decoded));
            return decryptedString;
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        }
    } else {
        return encryptedText;
    }
}

From source file:hh.learnj.test.license.test.rsa.RSATest.java

/**
 * /*from  ww w .  ja  v a  2s  . com*/
 * 
 * @param target
 * @throws Exception
 */
static void decryptionByPublicKey(String target) throws Exception {
    PublicKey publicKey = getPublicKey();
    Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicKey);
    cipher.update(decodeBase64(target));
    String source = new String(cipher.doFinal(), "UTF-8");
    System.out.println("??\r\n" + source);
}