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.boylesoftware.web.impl.auth.CipherToolbox.java

/**
 * Decrypt specified Base64 value. The decrypted values can be retrieved
 * immediately after calling this method using {@link #getUserId},
 * {@link #getSalt} and {@link #getTimestamp}.
 *
 * @param base64Val The value to decrypt in Base64 encoding.
 *
 * @return {@code true} if decrypted successfully, {@code false} if
 * could not decrypt.//from w  w w  . j a  v a2s  .  c  o  m
 */
boolean decrypt(final String base64Val) {

    final boolean debug = this.log.isDebugEnabled();
    if (debug)
        this.log.debug("decrypting [" + base64Val + "], pooled cipher " + this);

    try {
        final int len = base64Val.length();
        base64Val.getChars(0, len, this.base64Chars, 0);
        this.base64Buf.limit(len);
        this.base64Buf.rewind();
    } catch (final IndexOutOfBoundsException e) {
        if (debug)
            this.log.debug("decryption error", e);
        return false;
    }

    this.cipherBuf.clear();
    Base64.decode(this.base64Buf, this.cipherBuf);
    this.cipherBuf.flip();

    this.clearBuf.clear();
    try {
        this.cipher.init(Cipher.DECRYPT_MODE, this.secretKey);
        this.cipher.doFinal(this.cipherBuf, this.clearBuf);
    } catch (final GeneralSecurityException e) {
        if (debug)
            this.log.debug("decryption error", e);
        return false;
    }
    this.clearBuf.flip();

    this.salt = this.clearBuf.getInt();
    this.clearBuf.getLong();
    this.userId = this.clearBuf.getInt();
    this.clearBuf.getLong();
    this.timestamp = this.clearBuf.getLong();

    if (debug)
        this.log.debug("decrypted: userId=" + this.userId + ", salt=" + this.salt + ", ts=" + this.timestamp
                + " (" + (new java.util.Date(this.timestamp)) + ")");

    return true;
}

From source file:de.alpharogroup.crypto.key.PrivateKeyHexDecryptor.java

/**
 * Initializes the {@link SimpleDecryptor} object.
 *
 * @throws NoSuchAlgorithmException//from   w w  w  . ja v a2 s .  c o  m
 *             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.
 * @throws InvalidKeySpecException
 * @throws IOException
 * @throws InvalidAlgorithmParameterException
 */
private void initialize() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidKeySpecException, IOException, InvalidAlgorithmParameterException {
    if (!isInitialized()) {
        cipher = Cipher.getInstance(
                KeyPairWithModeAndPaddingAlgorithm.RSA_ECB_OAEPWithSHA1AndMGF1Padding.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
    }
}

From source file:es.juntadeandalucia.framework.ticket.impl.DefaultTicket.java

private byte[] decrypt(byte[] input) throws Exception {

    Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.DECRYPT_MODE, key);
    return cipher.doFinal(input);

}

From source file:eap.util.EDcodeUtil.java

public static byte[] desDecodeForHex(String dataHex, byte[] key) {
    return des(hexDecode(dataHex), key, Cipher.DECRYPT_MODE);
}

From source file:com.alliander.osgp.oslp.OslpUtils.java

private static boolean validateEncryptedHash(final byte[] message, final byte[] securityKey,
        final PublicKey publicKey) throws GeneralSecurityException {

    // Calculate hash of message
    final byte[] verifyHash = createHash(message);

    try {/*  w ww.j  ava2s  .  c o m*/
        // Decrypt security key hash
        final Cipher cipher = Cipher.getInstance(FALLBACK_CIPHER);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        final byte[] messageHash = cipher.doFinal(securityKey);

        // Verify calculated and received hash
        return Arrays.equals(messageHash, verifyHash);
    } catch (final BadPaddingException e) {
        LOGGER.error("unexpected exception", e);
        return false;
    }
}

From source file:de.alpharogroup.crypto.simple.SimpleDecryptor.java

/**
 * Initializes the {@link SimpleDecryptor} object.
 *
 * @throws InvalidAlgorithmParameterException
 *             is thrown if initialization of the cypher object fails.
 * @throws NoSuchPaddingException/*w  ww . j  a  v  a 2 s  .  com*/
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the SecretKeyFactory object fails.
 * @throws InvalidKeyException
 *             is thrown if initialization of the cypher object fails.
 */
private void initialize() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidKeyException, InvalidAlgorithmParameterException {
    if (!isInitialized()) {
        KeySpec keySpec = null;
        if (this.getPrivateKey() != null) {
            keySpec = new PBEKeySpec(this.getPrivateKey().toCharArray());
        }
        if (this.getPrivateKey() == null) {
            keySpec = new PBEKeySpec(CryptConst.PRIVATE_KEY.toCharArray());
        }
        final SecretKeyFactory factory = SecretKeyFactory.getInstance(CryptConst.PBEWITH_MD5AND_DES);
        final SecretKey key = factory.generateSecret(keySpec);
        this.cipher = Cipher.getInstance(key.getAlgorithm());
        final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(CryptConst.SALT,
                CryptConst.ITERATIONCOUNT);
        this.cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        initialized = true;
    }
}

From source file:MegaHandler.java

private int login_process(JSONObject json, long[] password_aes) throws IOException {

    String master_key_b64 = null;
    try {//from  ww w  .  ja va2 s  .  co  m
        master_key_b64 = json.getString("k");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (master_key_b64 == null || master_key_b64.isEmpty())
        return -1;

    long[] encrypted_master_key = MegaCrypt.base64_to_a32(master_key_b64);
    master_key = MegaCrypt.decrypt_key(encrypted_master_key, password_aes);

    if (json.has("csid")) {
        String encrypted_rsa_private_key_b64 = null;
        try {
            encrypted_rsa_private_key_b64 = json.getString("privk");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        long[] encrypted_rsa_private_key = MegaCrypt.base64_to_a32(encrypted_rsa_private_key_b64);
        long[] rsa_private_key = MegaCrypt.decrypt_key(encrypted_rsa_private_key, master_key);
        String private_key = MegaCrypt.a32_to_str(rsa_private_key);

        this.rsa_private_key = new BigInteger[4];
        for (int i = 0; i < 4; i++) {
            int l = ((((int) private_key.charAt(0)) * 256 + ((int) private_key.charAt(1)) + 7) / 8) + 2;
            this.rsa_private_key[i] = MegaCrypt.mpi_to_int(private_key.substring(0, l));
            private_key = private_key.substring(l);
        }

        BigInteger encrypted_sid = null;
        try {
            encrypted_sid = MegaCrypt.mpi_to_int(MegaCrypt.base64_url_decode(json.getString("csid")));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        BigInteger modulus = this.rsa_private_key[0].multiply(this.rsa_private_key[1]);
        BigInteger privateExponent = this.rsa_private_key[2];

        BigInteger sid = null;
        try {
            PrivateKey privateKey = KeyFactory.getInstance("RSA")
                    .generatePrivate(new RSAPrivateKeySpec(modulus, privateExponent));
            Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // PyCrypt can handle >256 bit length... what the fuck... sometimes i get 257
            if (encrypted_sid.toByteArray().length > 256) {
                Random rg = new Random();
                sequence_number = rg.nextInt(Integer.MAX_VALUE);
                return -2; // lets get a new seession
            }
            sid = new BigInteger(cipher.doFinal(encrypted_sid.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

        String sidS = sid.toString(16);
        if (sidS.length() % 2 != 0)
            sidS = "0" + sidS;
        try {
            byte[] sidsnohex = MegaCrypt.decodeHexString(sidS);
            this.sid = MegaCrypt.base64_url_encode(new String(sidsnohex, "ISO-8859-1").substring(0, 43));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
    return 0;
}

From source file:com.titilink.common.app.EncryptDecryptUtil.java

public void testRSA() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, SignatureException {
    ///* w ww .  j a va  2s. com*/
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    //?
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    //??
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, privateKey, new SecureRandom());
    byte[] cipherData = cipher
            .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8")));

    //
    Cipher cipher1 = Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, publicKey, new SecureRandom());
    byte[] plainData = cipher1.doFinal(cipherData);
    System.out.println(new String(plainData, Charset.forName("UTF-8")));

    //???????
    Signature signature = Signature.getInstance("MD5withRSA");
    signature.initSign(privateKey);
    signature.update(cipherData);
    byte[] signData = signature.sign();

    //?????
    Signature signature1 = Signature.getInstance("MD5withRSA");
    signature1.initVerify(publicKey);
    signature1.update(cipherData);
    System.out.println(signature1.verify(signData));

}

From source file:com.fegor.alfresco.security.crypto.Crypto.java

/**
 * Decryption configuration//from   w  w  w .j  ava2 s .  co  m
 * 
 * @param initvec
 * @param salt
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 */
public void configDecrypt(String initvec, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    salt_pos = Hex.decodeHex(salt.toCharArray());

    if (logger.isDebugEnabled())
        logger.debug(this.getClass().getName() + ": [salt: " + (new String(Hex.encodeHex(salt_pos))) + "]");

    vector_init = Hex.decodeHex(initvec.toCharArray());
    if (logger.isDebugEnabled())
        logger.debug(
                this.getClass().getName() + ": [vector ini: " + (new String(Hex.encodeHex(vector_init))) + "]");

    /*
     * http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files
     * .shtml
     */
    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt_pos, ITERATIONS, KEYLEN_BITS);

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

    deCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    deCipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vector_init));
}

From source file:com.ethercamp.harmony.keystore.KeystoreFormat.java

private byte[] decryptAes(byte[] iv, byte[] keyBytes, byte[] cipherText)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    return processAes(iv, keyBytes, cipherText, Cipher.DECRYPT_MODE);
}