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.qubit.solution.fenixedu.bennu.webservices.services.server.SecurityHeader.java

private String decryptWithSessionKey(String content) throws InvalidKeyException, NoSuchAlgorithmException,
        NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
    SecretKey originalKey = new SecretKeySpec(this.sessionKey, 0, this.sessionKey.length, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, originalKey);
    return new String(cipher.doFinal(Base64.decodeBase64(content)), "UTF-8");
}

From source file:com.hybris.mobile.lib.commerce.helper.SecurityHelper.java

/**
 * Decrypt secure String associated to the key
 *
 * @param value The value to decrypt//ww w. ja v a  2 s  .  c  o  m
 * @return decrypted string
 */
public static String decrypt(String value) {
    String decryptedText = "";
    try {
        if (StringUtils.isNotBlank(value)) {
            Cipher cipher = Cipher.getInstance(CIPHER);
            cipher.init(Cipher.DECRYPT_MODE, mSecretKeySpec, mIvParameterSpec);
            decryptedText = new String(cipher.doFinal(Base64.decode(value, Base64.NO_CLOSE)), ENCODING);
            return decryptedText;
        }
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Algorithm not found.");
    } catch (NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
        Log.e(TAG, "Exception during decrypt");
    } catch (InvalidKeyException e) {
        Log.e(TAG, "No valid key provided.");
    } catch (InvalidAlgorithmParameterException e) {
        Log.e(TAG, "Algorithm parameter specification is invalid");
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "Character to convert is unavailable");
    }

    return decryptedText;
}

From source file:Crypt.java

private String decryptByDES(String str) throws Exception {
    Cipher c;//from  www  . ja  va 2  s. com

    try {
        byte[] tmp = new byte[str.length() / 2];
        int index = 0;
        while (index < str.length()) {
            // convert hexadecimal number into decimal number.
            int num = Integer.parseInt(str.substring(index, index + 2), 16);

            // convert into signed byte.
            if (num < 128) {
                tmp[index / 2] = new Byte(Integer.toString(num)).byteValue();
            } else {
                tmp[index / 2] = new Byte(Integer.toString(((num ^ 255) + 1) * -1)).byteValue();
            }
            index += 2;
        }

        c = Cipher.getInstance("DES/ECB/PKCS5Padding");
        c.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(c.doFinal(tmp));
    } catch (InvalidKeyException e) {
        log.error("The information of the private key may be broken.", e);
        throw e;
    } catch (IllegalBlockSizeException e) {
        log.error("he length of data is unjust.", e);
        throw e;
    }
}

From source file:org.jasig.cas.web.flow.CasFlowExecutionKeyFactory.java

protected String decrypt(final String value) {
    if (value == null) {
        return null;
    }//www .  j  a  va2 s  . c  om

    try {
        final Cipher cipher = Cipher.getInstance(this.cipherAlgorithm);
        cipher.init(Cipher.DECRYPT_MODE, this.key, this.ivs);
        return new String(cipher.doFinal(hexStringToByteArray(value)));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.personium.core.model.file.DataCryptor.java

/**
 * Generate InputStream for decryption from Input and return it.
 * If encryptionType is NONE, it returns input as is.
 * @param input input data/*  w w w.j  a  v a  2s .  c  o  m*/
 * @param encryptionType encryption type
 * @return InputStream for decryption
 */
public InputStream decode(InputStream input, String encryptionType) {
    if (ENCRYPTION_TYPE_AES.equals(encryptionType)) {
        try {
            Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
            cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
            CipherInputStream decodedInputStream = new CipherInputStream(input, cipher);

            return decodedInputStream;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        return input;
    }
}

From source file:duthientan.mmanm.com.CipherRSA.java

@Override
public void decrypt(String filePath) {
    try {/*from  w ww .ja  v  a2s .co m*/
        Cipher decipher = Cipher.getInstance("RSA");
        decipher.init(Cipher.DECRYPT_MODE, privateKey);
        Path path = Paths.get(filePath);
        String decryptFilePath = filePath.replace("RSA" + "_", "");
        byte[] data = Files.readAllBytes(path);
        byte[] textDncrypted = null;
        int chunkSize = 256;
        if (data.length < 256) {
            textDncrypted = decipher.doFinal(data);
        } else {
            for (int i = 0; i < data.length; i += chunkSize) {
                byte[] segment = Arrays.copyOfRange(data, i,
                        i + chunkSize > data.length ? data.length : i + chunkSize);
                byte[] segmentEncrypted = decipher.doFinal(segment);
                textDncrypted = ArrayUtils.addAll(textDncrypted, segmentEncrypted);
            }
        }
        FileOutputStream fos = new FileOutputStream(decryptFilePath);
        fos.write(textDncrypted);
        fos.close();
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.cfs.util.AESCriptografia.java

public String decifrar(String textoCifrado, String chave) {
    try {// www .j a  v  a2s. c o  m
        byte[] cifrado = Base64.decodeBase64(textoCifrado.getBytes());
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, gerarChave(chave));
        byte[] decifrado = cipher.doFinal(cifrado);
        return new String(decifrado);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

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

@Test
public void testCert() throws Exception {
    DataInputStream inStream = new DataInputStream(getClass().getResource("/test.crt").openStream());

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
    inStream.close();/*from   ww w  . jav a 2 s  .  co m*/
    assertNotNull(cert);

    cert.checkValidity();

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, cert);

    byte[] clear = cipher.doFinal(Base64.decodeBase64(SCRAMBLED.getBytes()));
    assertEquals(PLAINTEXT, new String(clear));
}

From source file:com.springcryptoutils.core.cipher.asymmetric.Base64EncodedCiphererWithChooserByKeyIdImpl.java

/**
 * Encrypts/decrypts a message based on the underlying mode of operation.
 *
 * @param keyId the key id/*from   w  w w .  j  av  a  2  s. c o  m*/
 * @param message if in encryption mode, the clear-text message, otherwise
 *        the base64 encoded message to decrypt
 * @return if in encryption mode, the base64 encoded encrypted message,
 *         otherwise the decrypted message
 * @throws AsymmetricEncryptionException on runtime errors
 * @see #setMode(Mode)
 */
public String encrypt(String keyId, String message) {
    final Key key = keyMap.get(keyId);

    if (key == null) {
        throw new AsymmetricEncryptionException("key not found: keyId=" + keyId);
    }

    try {
        final Cipher cipher = (((provider == null) || (provider.length() == 0)) ? Cipher.getInstance(algorithm)
                : Cipher.getInstance(algorithm, provider));
        switch (mode) {
        case ENCRYPT:
            final byte[] messageAsByteArray = message.getBytes(charsetName);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return Base64.encodeBase64String(cipher.doFinal(messageAsByteArray));
        case DECRYPT:
            final byte[] encryptedMessage = Base64.decodeBase64(message);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(encryptedMessage), charsetName);
        default:
            return null;
        }
    } catch (Exception e) {
        throw new AsymmetricEncryptionException("error encrypting/decrypting message; mode=" + mode, e);
    }
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoEncryptionService.java

/**
 * AES Decryption CBC Mode with PKCS5 Padding
 *
 * @param encryptedB64 Encrypted Data Base64 encoded.
 * @param secretB64 Encryption secret Base64 encoded. For AES128 this should be 128 bits (16 bytes) long. For AES256 this should be 256 bits (32 bytes) long.
 * @param ivB64 Initialization Vector Base64 encoded. 16 bytes long
 * @return Original data Base64 encoded.
 * @throws NoSuchAlgorithmException/*from  w  w w.j av a 2 s  . c o m*/
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws IOException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
public String aesDecrypt(String encryptedB64, String secretB64, String ivB64)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    String dataB64 = null;

    final byte[] encryptedBytes = Base64.decodeBase64(encryptedB64);
    final byte[] secretBytes = Base64.decodeBase64(secretB64);
    final byte[] ivBytes = Base64.decodeBase64(ivB64);
    final Cipher cipher = Cipher.getInstance(AES_CIPHER);

    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretBytes, "AES"),
            new IvParameterSpec(ivBytes, 0, cipher.getBlockSize()));

    dataB64 = Base64.encodeBase64String(cipher.doFinal(encryptedBytes));
    return dataB64;
}