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.thoughtworks.go.security.AESEncrypter.java

@Override
public String decrypt(String cipherText) throws CryptoException {
    try {/* w  w  w. j a v a  2  s .  co  m*/
        Assert.isTrue(canDecrypt(cipherText), "bad cipher text");

        String[] splits = cipherText.split(":");

        String encodedIV = splits[1];
        String encodedCipherText = splits[2];

        byte[] initializationVector = DECODER.decode(encodedIV);
        Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        decryptCipher.init(Cipher.DECRYPT_MODE, createSecretKeySpec(),
                new IvParameterSpec(initializationVector));

        byte[] decryptedBytes = decryptCipher.doFinal(DECODER.decode(encodedCipherText));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    } catch (Exception e) {
        throw new CryptoException(e);
    }
}

From source file:hh.learnj.test.license.test.rsacoder.RSACoder.java

/**
 * ?/*w ww.  j  a va2  s.co  m*/
 * 
 * @param data
 *            ?
 * @param key
 *            
 * @return byte[] ?
 */
public static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws Exception {
    // ??
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // ??
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    return cipher.doFinal(data);
}

From source file:io.manasobi.utils.CryptoUtils.java

/**
 *  .//from w  w w .  j a  va2 s.c  o  m
 *
 * @param keyHex generateHexKey ? ? ?? Hex ? ? 
 * @param data    ? ?
 *             
 * @return ? ?? byte 
 */
public static byte[] decryptByDES(String keyHex, byte[] data) {

    SecretKey key = getSecretDESKeyFromHex(keyHex);

    byte[] decryptedData = null;

    try {

        Cipher cipher = Cipher.getInstance(ALGORITHM);

        cipher.init(Cipher.DECRYPT_MODE, key);

        decryptedData = cipher.doFinal(data);

    } catch (Exception e) {

        throw new CryptoUtilsException(e.getMessage());
    }

    return decryptedData;
}

From source file:enc_mods.aes.java

/**
* Decrypts an AES key from a file using an RSA private key
*///from  ww  w .jav a2s .c  o  m
public void loadKey(File in, File privateKeyFile) {
    try {
        // read private key to be used to decrypt the AES key
        byte[] encodedKey = new byte[(int) privateKeyFile.length()];
        new FileInputStream(privateKeyFile).read(encodedKey);

        // create private key
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey pk = kf.generatePrivate(privateKeySpec);

        // read AES key
        cipher.init(Cipher.DECRYPT_MODE, pk);
        key = new byte[AES_Key_Size / 8];
        CipherInputStream is = new CipherInputStream(new FileInputStream(in), cipher);
        is.read(key);
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:dualcontrol.CryptoHandler.java

private void cipher(String mode, String alias, String transformation, String ivString, String dataString)
        throws Exception {
    logger.debug(join("cipher", alias, transformation, mode));
    SecretKey key = dualControl.loadKey(alias);
    logger.debug("keyalg " + key.getAlgorithm());
    Cipher cipher = Cipher.getInstance(transformation);
    logger.debug("mode " + mode);
    if (mode.equals("DECRYPT")) {
        this.ivBytes = Base64.decodeBase64(ivString);
        logger.debug("iv " + Base64.encodeBase64String(ivBytes));
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        this.dataBytes = cipher.doFinal(Base64.decodeBase64(dataString));
        write(ivBytes, dataBytes);/*from w  w  w  .j av a 2  s. com*/
    } else if (mode.equals("ENCRYPT")) {
        this.ivBytes = getIvBytes(ivString);
        logger.debug("iv " + Base64.encodeBase64String(ivBytes));
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        long startTime = System.nanoTime();
        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
        this.dataBytes = cipher.doFinal(dataString.getBytes());
        logger.info("encrypt time nanos " + Nanos.elapsed(startTime));
        write(ivBytes, dataBytes);
    }
}

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

/**
 * Encrypts/decrypts a message based on the underlying mode of operation.
 *
 * @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)/*  w  ww .  j av  a2s .  c  o m*/
 */
public String encrypt(String message) {
    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.marvelution.jira.plugins.hudson.encryption.StringEncrypter.java

/**
 * Decrypt a given {@link String}/*from  www  .  j a v a 2 s .  co m*/
 * 
 * @param stringToDecrypt the {@link String} to Decrypt
 * @return the Decrypted {@link String}
 */
public String decrypt(String stringToDecrypt) {
    if (stringToDecrypt == null || stringToDecrypt.length() == 0) {
        return "";
    }
    try {
        initiliseCipher(Cipher.DECRYPT_MODE);
        return new String(cipher.doFinal(Base64.decodeBase64(stringToDecrypt.getBytes())));
    } catch (Exception e) {
        LOGGER.error("Failed to decrypt provided String. Reason: " + e.getMessage(), e);
        throw new StringEncryptionException("Failed to decrypt provided String. Reason: " + e.getMessage(), e);
    }
}

From source file:com.baran.crypto.CryptoDES.java

public byte[] decrypt(byte[] message, String trivia) throws Exception {
    final MessageDigest md = MessageDigest.getInstance("md5");
    final byte[] digestTrivia = md.digest(trivia.getBytes("utf-8"));

    final byte[] keyBytes = Arrays.copyOf(digestTrivia, 24);

    for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];/*from w w w  .  ja  va2s  .com*/
    }

    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    decipher.init(Cipher.DECRYPT_MODE, key, iv);

    final byte[] plainText = decipher.doFinal(message);

    return plainText;
}

From source file:ie.peternagy.jcrypto.algo.EllipticCurveWrapper.java

/**
 * Initialize the cipher for task//  w ww .  ja va2s.  c  om
 *
 * @param isEncrypt
 */
private void initCipher(boolean isEncrypt) {
    try {
        if (isEncrypt) {
            ecCipher.init(Cipher.ENCRYPT_MODE, publicKey);
        } else {
            ecCipher.init(Cipher.DECRYPT_MODE, privateKey);
        }
    } catch (InvalidKeyException ex) {
        Logger.getLogger(EllipticCurveWrapper.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ru.jts_dev.authserver.packets.in.RequestAuthLogin.java

@Override
public void run() {
    AuthSession session = authSessionService.getSessionBy(getConnectionId());

    byte[] decrypted;
    try {/*from  w w w  .  j  a va  2 s  .c o m*/
        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/nopadding");
        rsaCipher.init(Cipher.DECRYPT_MODE, session.getRsaKeyPair().getPrivate());
        decrypted = rsaCipher.doFinal(data, 0x00, 0x80);
    } catch (Exception e) {
        broadcastService.send(session, null);
        return;
    }

    String login = new String(decrypted, 0x5E, 14, StandardCharsets.UTF_8).trim();
    String password = new String(decrypted, 0x6C, 16, StandardCharsets.UTF_8).trim();

    if (!repository.exists(login)) {
        if (accountsAutocreate) {
            repository.save(new Account(login, passwordEncoder.encode(password)));
        } else {
            log.trace("Account with login '" + login + "' not found in database");

            broadcastService.send(session, new LoginFail(REASON_USER_OR_PASS_WRONG));
            connectionFactory.closeConnection(getConnectionId());
            return;
        }
    }

    Account account = repository.findOne(login);

    if (!passwordEncoder.matches(password, account.getPasswordHash())) {
        log.trace("Password don't match for account '" + login + "'");

        broadcastService.send(session, new LoginFail(REASON_USER_OR_PASS_WRONG));
        connectionFactory.closeConnection(getConnectionId());
        return;
    }

    broadcastService.send(session, new LoginOk(session.getLoginKey1(), session.getLoginKey2()));
}