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 String decrypt(String str)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    byte[] bytes = decodeHex(str);
    byte[] decrypted = Base64.decodeBase64(new String(bytes));
    byte[] decs = crypt(Cipher.DECRYPT_MODE, decrypted);
    String decryptedText = new String(decs);
    return decryptedText;
}

From source file:com.springcryptoutils.core.cipher.symmetric.Base64EncodedCiphererImpl.java

/**
 * Encrypts or decrypts a message. The encryption/decryption mode depends on
 * the configuration of the mode parameter.
 *
 * @param key a base64 encoded version of the symmetric key
 * @param initializationVector a base64 encoded version of the
 *        initialization vector//  www.j  a  v  a 2s .com
 * @param message if in encryption mode, the clear-text message to encrypt,
 *        otherwise a base64 encoded version of the message to decrypt
 * @return if in encryption mode, returns a base64 encoded version of the
 *         encrypted message, otherwise returns the decrypted clear-text
 *         message
 * @throws SymmetricEncryptionException on runtime errors
 * @see #setMode(com.google.code.springcryptoutils.core.cipher.Mode)
 */
public String encrypt(String key, String initializationVector, String message) {
    try {
        IvParameterSpec initializationVectorSpec = new IvParameterSpec(
                Base64.decodeBase64(initializationVector));
        final SecretKeySpec keySpec = new SecretKeySpec(Base64.decodeBase64(key), keyAlgorithm);
        final Cipher cipher = (((provider == null) || (provider.length() == 0))
                ? Cipher.getInstance(cipherAlgorithm)
                : Cipher.getInstance(cipherAlgorithm, provider));
        byte[] messageAsByteArray;

        switch (mode) {
        case ENCRYPT:
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, initializationVectorSpec);
            messageAsByteArray = message.getBytes(charsetName);
            final byte[] encryptedMessage = cipher.doFinal(messageAsByteArray);
            return new String(Base64.encodeBase64(encryptedMessage, chunkOutput));
        case DECRYPT:
            cipher.init(Cipher.DECRYPT_MODE, keySpec, initializationVectorSpec);
            messageAsByteArray = Base64.decodeBase64(message);
            final byte[] decryptedMessage = cipher.doFinal(messageAsByteArray);
            return new String(decryptedMessage, charsetName);
        default:
            return null;
        }
    } catch (Exception e) {
        throw new SymmetricEncryptionException("error encrypting/decrypting message; mode=" + mode, e);
    }
}

From source file:edu.tamu.tcat.crypto.bouncycastle.SecureTokenImpl.java

@Override
public ByteBuffer getContentFromToken(String encoded) throws TokenException {
    try {//  www.jav a 2  s  .  c o m
        byte[] encrypted = Base64.decodeBase64(encoded.getBytes());
        byte[] iv = new byte[ivSize / 8];
        int ivLength = iv.length;
        if (encrypted.length < ivLength)
            throw new TokenException("Invalid Token", true);
        System.arraycopy(encrypted, 0, iv, 0, ivLength);
        Cipher cipher = createCipher(Cipher.DECRYPT_MODE, iv);
        byte[] encryptedBlock = new byte[encrypted.length - ivLength];
        System.arraycopy(encrypted, ivLength, encryptedBlock, 0, encryptedBlock.length);
        byte[] token = cipher.doFinal(encryptedBlock);
        ByteBuffer content = ByteBuffer.wrap(token);
        return content;
    } catch (IllegalBlockSizeException e) {
        throw new TokenException("Incorrect input size", e, true);
    } catch (BadPaddingException e) {
        throw new TokenException("Bad Padding", e, true);
    }
}

From source file:br.com.ufjf.labredes.crypto.Cryptography.java

public static byte[] decrypt(byte[] aesKeyEncrypted, PrivateKey privKey) {
    byte[] aesKey = null;
    try {//from  www  .  j  a  v a2 s. co  m
        Cipher cipher = Cipher.getInstance(ALGORITHM_ASYM);
        cipher.init(Cipher.DECRYPT_MODE, privKey);
        aesKey = cipher.doFinal(aesKeyEncrypted);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return aesKey;
}

From source file:com.frame.Conf.Utilidades.java

public String Desencriptar2(String keypass, String textoEncriptado) throws Exception {

    String secretKey = keypass; //llave para encriptar datos
    String base64EncryptedString = "";

    try {//  w  w  w .  jav  a  2s.c o m
        System.out.println("checkpoint");
        byte[] message = Base64.decodeBase64(textoEncriptado.getBytes("utf-8"));
        MessageDigest md = MessageDigest.getInstance("MD5");
        System.out.println("checkpoint2");
        byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        System.out.println("checkpoint3");
        SecretKey key = new SecretKeySpec(keyBytes, "DESede");

        System.out.println("checkpoint4");
        Cipher decipher = Cipher.getInstance("DESede");
        decipher.init(Cipher.DECRYPT_MODE, key);
        System.out.println("checkpoint5");

        byte[] plainText = decipher.doFinal(message);
        System.out.println("checkpoint6");
        base64EncryptedString = new String(plainText, "UTF-8");

    } catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
        throw new Exception(ex.getMessage());
    }
    return base64EncryptedString;
}

From source file:com.cedarsoft.crypt.X509Support.java

/**
 * <p>decipher</p>//from w  w w. j  a v a  2 s .c  o m
 *
 * @param bytes an array of byte.
 * @return an array of byte.
 *
 * @throws GeneralSecurityException
 *          if any.
 */
@Nonnull
public byte[] decipher(@Nonnull byte[] bytes) throws GeneralSecurityException {
    Cipher cipher = Cipher.getInstance(RSA);
    cipher.init(Cipher.DECRYPT_MODE, certificate);
    return cipher.doFinal(bytes);
}

From source file:com.dc.util.file.FileSupport.java

private static void copyEncryptedStream(InputStream input, OutputStream output, String key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    Cipher dcipher = Cipher.getInstance("AES");
    CipherInputStream cis = null;
    try {//from w ww . jav  a2 s.  co  m
        dcipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
        cis = new CipherInputStream(input, dcipher);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = cis.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
        output.flush();
    } finally {
        if (cis != null) {
            cis.close();
        }
    }
}

From source file:com.github.aelstad.keccakj.keyak.KeyakTestUtils.java

public void runTests(List<KeyakTest> tests) throws Exception {
    LakeKeyak wrapper = new LakeKeyak();
    LakeKeyak unwrapper = new LakeKeyak();
    LakeKeyak unwrapperFailing = new LakeKeyak();

    for (KeyakTest dt : tests) {
        System.out.println("initialize with:");
        System.out.println("key: " + toHex(dt.key));
        System.out.println("nonce: " + toHex(dt.nonce));

        wrapper.init(dt.key, dt.nonce);/*from w  w  w  . j  a  va 2 s .  c  o m*/
        unwrapper.init(dt.key, dt.nonce);
        unwrapperFailing.init(dt.key, dt.nonce);

        LakeKeyakCipher lkEncryptingCipher = new LakeKeyakCipher();
        lkEncryptingCipher.init(Cipher.ENCRYPT_MODE, new LakeKeyakKey(dt.key), new IvParameterSpec(dt.nonce));

        LakeKeyakCipher lkDecryptingCipher = new LakeKeyakCipher();
        lkDecryptingCipher.init(Cipher.DECRYPT_MODE, new LakeKeyakKey(dt.key), new IvParameterSpec(dt.nonce));

        LakeKeyakCipher lkDecryptingFailing = new LakeKeyakCipher();
        lkDecryptingFailing.init(Cipher.DECRYPT_MODE, new LakeKeyakKey(dt.key), new IvParameterSpec(dt.nonce));

        for (TestCommand tc : dt.commands) {
            if (tc instanceof ForgetCommand) {
                System.out.println("forget");
                lkEncryptingCipher.forget();
                lkDecryptingCipher.forget();
            } else if (tc instanceof PairCommand) {
                PairCommand pc = (PairCommand) tc;
                System.out.println("associated data: " + toHex(pc.ad));
                System.out.println("plaintext: " + toHex(pc.plaintext));
                System.out.println("ciphertext: " + toHex(pc.ciphertext));
                System.out.println("tag: " + toHex(pc.tag));

                byte[] wrapOut = new byte[pc.plaintext.length];
                byte[] tagOut = new byte[pc.tag.length];

                lkEncryptingCipher.updateAAD(pc.ad);
                byte[] encrypted = lkEncryptingCipher.doFinal(pc.plaintext);
                Assert.assertTrue(encrypted.length == pc.plaintext.length + 16);

                System.arraycopy(encrypted, 0, wrapOut, 0, pc.plaintext.length);
                System.arraycopy(encrypted, encrypted.length - 16, tagOut, 0, 16);

                System.out.println("got ciphertext: " + toHex(wrapOut));
                System.out.println("got tag: " + toHex(tagOut));

                Assert.assertArrayEquals(wrapOut, pc.ciphertext);
                Assert.assertArrayEquals(tagOut, pc.tag);

                lkDecryptingCipher.updateAAD(pc.ad);
                byte[] decrypted = lkDecryptingCipher.doFinal(encrypted);
                Assert.assertArrayEquals(decrypted, pc.plaintext);

                lkDecryptingFailing.updateAAD(pc.ad);
                AEADBadTagException expected = null;
                try {
                    byte[] decryptedFailing = lkDecryptingFailing.doFinal(new byte[16]);
                } catch (AEADBadTagException ex) {
                    expected = ex;
                }
                Assert.assertNotNull(expected);

                lkDecryptingFailing = new LakeKeyakCipher();
                lkDecryptingFailing.init(Cipher.DECRYPT_MODE, new LakeKeyakKey(dt.key),
                        new IvParameterSpec(dt.nonce));

            }
            System.out.println();
        }

    }
}

From source file:com.thoughtworks.go.security.X509CertificateGeneratorTest.java

@Test
public void shouldGenerateValidRSAKeyPair() throws Exception {
    String text = "this is a secret message";
    X509CertificateGenerator generator = new X509CertificateGenerator();
    Registration registration = generator.createAgentCertificate(keystore, "agentHostName");
    PrivateKey privateKey = registration.getPrivateKey();
    PublicKey publicKey = registration.getPublicKey();

    final Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] encrypted = cipher.doFinal(text.getBytes());

    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] decrypted = cipher.doFinal(encrypted);
    assertThat(decrypted, is(text.getBytes()));
}

From source file:edu.cmu.sei.ams.cloudlet.impl.AESEncrypter.java

public byte[] decrypt(String encrypted) throws EncryptionException {
    try {// w w w  .ja  v  a2 s.  co m
        //log.info("Encrypted string: " + encrypted);
        byte[] cryptedBytes = Base64.decodeBase64(encrypted.getBytes());

        byte[] iv = new byte[16];
        System.arraycopy(cryptedBytes, 0, iv, 0, 16);
        //log.info("IV: " + String.valueOf(Hex.encodeHex(iv)));
        byte[] crypted = new byte[cryptedBytes.length - 16];
        System.arraycopy(cryptedBytes, 16, crypted, 0, crypted.length);
        //log.info("Cipher Text: " + String.valueOf(Hex.encodeHex(crypted)));

        // TODO: change to CBC method with padding.
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, this.skeySpec, new IvParameterSpec(iv));

        byte[] decrypted = cipher.doFinal(crypted);
        log.info("Data decrypted.");
        return decrypted;
    } catch (Exception e) {
        throw new EncryptionException("Error decrypting information", e);
    }
}