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:br.com.vectorx.BlowfishCryptox.java

/**
 * Construtor private. Define o tamanho mximo da palavra salt de acordo com
 * o SecurityPolice instalado/*from   w w w  . j a v  a2 s  .  co m*/
 * 
 * @param palavraChave
 *            Palavra chave
 * @param algoritmo
 *            Algoritmo a ser utilizado (no caso o Blowfish)
 * @param cifraCesar
 *            em quantos numeros os caracteres sero trocados
 * @param charset
 * @throws IllegalArgumentException
 */
private BlowfishCryptox(String palavraChave, String algoritmo, int cifraCesar, Charset charset)
        throws IllegalArgumentException {
    try {
        int maxSalt = LIMITEDSALTLENGTH;
        // Checagem para ver se tem JCE Unlimited Strength Policy instalado
        if (Cipher.getMaxAllowedKeyLength(algoritmo) > BlowfishCryptox.CIFRAMAX) {
            maxSalt = BlowfishCryptox.UNLIMITEDJCESALT;
        }
        validateInput(palavraChave, cifraCesar, maxSalt);
        this.charset = charset;
        SecretKey chave = new SecretKeySpec(palavraChave.getBytes(charset), algoritmo);
        this.encrypt = Cipher.getInstance(algoritmo);
        this.decrypt = Cipher.getInstance(algoritmo);
        this.encrypt.init(Cipher.ENCRYPT_MODE, chave);
        this.decrypt.init(Cipher.DECRYPT_MODE, chave);
        this.cifraCesar = cifraCesar;
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.nubits.nubot.utils.Utils.java

/**
 * @param pathToFile/*ww  w  . ja  va  2 s  .co  m*/
 * @param passphrase
 * @return
 */
public static String decode(String pathToFile, String passphrase) {
    String clearString = null;
    MessageDigest digest;
    try {
        //Encapsule the passphrase in a 16bit SecretKeySpec key
        digest = MessageDigest.getInstance("SHA");
        digest.update(passphrase.getBytes());
        SecretKeySpec key = new SecretKeySpec(digest.digest(), 0, 16, "AES");

        Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
        aes.init(Cipher.DECRYPT_MODE, key);

        byte[] ciphertextBytes = FileUtils.readFileToByteArray(new File(pathToFile));
        clearString = new String(aes.doFinal(ciphertextBytes));

    } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | BadPaddingException | IllegalBlockSizeException ex) {
        LOG.error(ex.toString());
        return "-1";
    }
    return clearString;
}

From source file:controlador.ControlEmpleados.java

/**
 * Solicita al server la SecretKey para cifrar/descifrar el resto de la comunicacin. Primero, hace una
 * peticin http de cuya respuesta abre un InputStream y almacena el stream de bytes en un fichero binario.
 * Este fichero es la clave pblica del servidor y se utilizar para descifrar asimtricamente la segunda
 * peticin, la cual contiene un objeto SecretKey que ser el utilizado para cifrar/descifrar de manera simtrica.
 *//*from ww w .  java  2  s  .com*/
public void solicitarClave() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpGet = new HttpGet(Configuration.getInstance().getServerUrl() + "/secretKey?opcion=public");
        CloseableHttpResponse response1 = httpclient.execute(httpGet,
                SessionContext.getInstance().getContext());
        try {
            HttpEntity entity1 = response1.getEntity();
            File f = new File("./server1024.publica");
            if (f.exists()) {
                f.delete();
            }
            IOUtils.copy(entity1.getContent(), new FileOutputStream(f));
        } finally {
            response1.close();
        }

        httpGet = new HttpGet(Configuration.getInstance().getServerUrl() + "/secretKey?opcion=secret");
        response1 = httpclient.execute(httpGet, SessionContext.getInstance().getContext());
        try {
            HttpEntity entity1 = response1.getEntity();
            String respuesta = EntityUtils.toString(entity1);
            byte[] clave = Base64.decodeBase64(respuesta);
            //descifro
            byte[] bufferPub = new byte[5000];
            File f = new File("server1024.publica");
            System.out.println(f.getAbsolutePath());
            FileInputStream in = new FileInputStream(f);
            int chars = in.read(bufferPub, 0, 5000);
            in.close();

            byte[] bufferPub2 = new byte[chars];
            System.arraycopy(bufferPub, 0, bufferPub2, 0, chars);

            Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

            KeyFactory keyFactoryRSA = KeyFactory.getInstance("RSA", "BC"); // Hace uso del provider BC
            // 4.2 Recuperar clave publica desde datos codificados en formato X509
            X509EncodedKeySpec clavePublicaSpec = new X509EncodedKeySpec(bufferPub2);
            PublicKey clavePublica2 = keyFactoryRSA.generatePublic(clavePublicaSpec);

            cifrador.init(Cipher.DECRYPT_MODE, clavePublica2); // Descrifra con la clave privada

            byte[] claveAES = cifrador.doFinal(clave);
            SecretKey originalKey = new SecretKeySpec(claveAES, 0, claveAES.length, "AES");
            SessionContext.getInstance().setSecretKey(originalKey);

        } finally {
            response1.close();
        }

    } catch (IOException ex) {
        Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:jp.primecloud.auto.common.component.PasswordEncryptor.java

/**
 * ?/* w  w  w.  java2s.  c  o m*/
 * @param encryptedString
 * @param keyString
 * @return
 */
public String decrypt(String encryptedString, String keyString) {
    byte[] encryptedBytes = Base64.decodeBase64(encryptedString.getBytes());
    byte[] keyBytes = keyString.getBytes();

    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);

    try {
        chipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    }

    byte decryptedBytes[] = null;
    try {
        decryptedBytes = chipher.doFinal(encryptedBytes);
    } catch (IllegalBlockSizeException e) {
        throw new RuntimeException(e);
    } catch (BadPaddingException e) {
        throw new RuntimeException(e);
    }

    return new String(decryptedBytes);
}

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

/**
 * RSA Decryption//from  w  ww. ja v  a  2s.  c o  m
 *
 * @param pemKey RSA Private Key
 * @param encryptedB64 RSA Encrypted data encoded with Base64
 * @return Original data Base64 Encoded
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
public String decrypt(String pemKey, String encryptedB64)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    String dataB64 = null;
    PrivateKey privateKey = null;
    Key key = null;
    try {
        key = CryptoUtil.getKey(pemKey);
    } catch (IOException e) {
        //try to fix key:
        key = CryptoUtil.getKey(CryptoUtil.fixPemString(pemKey));
    }
    if (key instanceof PrivateKey) {
        privateKey = (PrivateKey) key;
    } else {
        throw new IllegalArgumentException("Invalid key object type: " + key.getClass().getName());
    }

    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    dataB64 = Base64.encodeBase64String(cipher.doFinal(Base64.decodeBase64(encryptedB64)));
    return dataB64;
}

From source file:com.waveerp.desEncryption.java

public String decrypt(String value) {
    try {/*from w w w  .  ja v  a  2 s .c  om*/
        Cipher dcipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");
        dcipher.init(Cipher.DECRYPT_MODE, sKey, ivParSpec);

        if (value == null)
            return null;

        byte[] dec = Base64.decodeBase64(value.getBytes());
        byte[] utf8 = dcipher.doFinal(dec);

        return new String(utf8, "UTF8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.anteam.demo.codec.cipher.symmetric.DESedeCoder.java

/**
 * Decodes a byte array and returns the results as a byte array.
 *
 * @param source A byte array which has been encoded with the appropriate encoder
 * @return ?byte.source, null//www .j a  v  a2 s .com
 * @throws org.apache.commons.codec.DecoderException A decoder exception is thrown if a Decoder encounters a failure condition during the decode process.
 */
@Override
public byte[] decode(byte[] source) throws DecoderException {
    if (source == null) {
        return null;
    }
    try {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM_NAME);
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance(CIPHER_NAME);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, IvParameters);
        return cipher.doFinal(source);
    } catch (Exception e) {
        LOG.error(":" + key + ":" + source, e);
        throw new DecoderException(":" + key + ":" + source, e);
    }
}

From source file:com.invariantproperties.sandbox.springentitylistener.service.EncryptorBean.java

/**
 * Decrypt string/*from  ww  w  . jav  a  2s. c om*/
 */
public String decryptString(String ciphertext, String salt) {
    String plaintext = null;

    if (ciphertext != null) {
        try {
            // Encryptor encryptor = JavaEncryptor.getInstance();
            // CipherText ct =
            // CipherText.fromPortableSerializedBytes(Base64.decode(ciphertext));
            // plaintext = encryptor.decrypt(key, ct).toString();
            IvParameterSpec iv = new IvParameterSpec(Base64.decode(salt));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, iv);

            plaintext = new String(cipher.doFinal(Base64.decode(ciphertext)));
        } catch (NoSuchAlgorithmException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (NoSuchPaddingException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (InvalidKeyException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (BadPaddingException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (IllegalBlockSizeException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (Throwable e) {
            e.printStackTrace(System.out);
        }
    }

    return plaintext;
}

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

/**
 * Encrypts/decrypts a message based on the underlying mode of operation.
 *
 * @param message if in encryption mode, the clear-text message, otherwise
 *        the message to decrypt// www.java 2s. co m
 * @return if in encryption mode, the encrypted message, otherwise the
 *         decrypted message
 * @throws SymmetricEncryptionException on runtime errors
 * @see #setMode(Mode)
 */
public byte[] encrypt(byte[] message) {
    try {
        final Cipher cipher = (((provider == null) || (provider.length() == 0))
                ? Cipher.getInstance(cipherAlgorithm)
                : Cipher.getInstance(cipherAlgorithm, provider));
        switch (mode) {
        case ENCRYPT:
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, initializationVectorSpec);
            break;
        case DECRYPT:
            cipher.init(Cipher.DECRYPT_MODE, keySpec, initializationVectorSpec);
            break;
        default:
            throw new SymmetricEncryptionException(
                    "error encrypting/decrypting message: invalid mode; mode=" + mode);
        }
        return cipher.doFinal(message);
    } catch (Exception e) {
        throw new SymmetricEncryptionException("error encrypting/decrypting message; mode=" + mode, e);
    }
}

From source file:bioLockJ.module.agent.MailAgent.java

private String decrypt(final String property) {
    String decryptedPassword = null;
    try {/*from   w w  w  . ja  v a 2  s  . c om*/
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        final SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        final Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        decryptedPassword = new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    } catch (final Exception ex) {
        Log.out.error(ex.getMessage(), ex);
    }

    return decryptedPassword;

}