Example usage for javax.crypto Cipher init

List of usage examples for javax.crypto Cipher init

Introduction

In this page you can find the example usage for javax.crypto Cipher init.

Prototype

public final void init(int opmode, Certificate certificate, SecureRandom random) throws InvalidKeyException 

Source Link

Document

Initializes this cipher with the public key from the given certificate and a source of randomness.

Usage

From source file:com.almende.util.EncryptionUtil.java

/**
 * Encrypt a string./*from  ww w .  j av  a2 s  .c o  m*/
 * 
 * @param text
 *            the text
 * @return encryptedText
 * @throws InvalidKeyException
 *             the invalid key exception
 * @throws InvalidAlgorithmParameterException
 *             the invalid algorithm parameter exception
 * @throws NoSuchAlgorithmException
 *             the no such algorithm exception
 * @throws InvalidKeySpecException
 *             the invalid key spec exception
 * @throws NoSuchPaddingException
 *             the no such padding exception
 * @throws IllegalBlockSizeException
 *             the illegal block size exception
 * @throws BadPaddingException
 *             the bad padding exception
 * @throws UnsupportedEncodingException
 *             the unsupported encoding exception
 */
public static String encrypt(final String text) throws InvalidKeyException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException,
        BadPaddingException, UnsupportedEncodingException {
    final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(S, C);
    final PBEKeySpec pbeKeySpec = new PBEKeySpec(P);
    final SecretKeyFactory keyFac = SecretKeyFactory.getInstance(ENC);
    final SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

    final Cipher pbeCipher = Cipher.getInstance(ENC);
    pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

    final byte[] encryptedText = pbeCipher.doFinal(text.getBytes("UTF-8"));
    return Base64.encodeBase64String(encryptedText);
}

From source file:com.almende.util.EncryptionUtil.java

/**
 * Decrypt an encrypted string./*from  ww w.j av  a 2  s . c  o m*/
 * 
 * @param encryptedText
 *            the encrypted text
 * @return text
 * @throws InvalidKeyException
 *             the invalid key exception
 * @throws InvalidAlgorithmParameterException
 *             the invalid algorithm parameter exception
 * @throws NoSuchAlgorithmException
 *             the no such algorithm exception
 * @throws InvalidKeySpecException
 *             the invalid key spec exception
 * @throws NoSuchPaddingException
 *             the no such padding exception
 * @throws IllegalBlockSizeException
 *             the illegal block size exception
 * @throws BadPaddingException
 *             the bad padding exception
 * @throws UnsupportedEncodingException
 *             the unsupported encoding exception
 */
public static String decrypt(final String encryptedText) throws InvalidKeyException,
        InvalidAlgorithmParameterException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(S, C);
    final PBEKeySpec pbeKeySpec = new PBEKeySpec(P);
    final SecretKeyFactory keyFac = SecretKeyFactory.getInstance(ENC);
    final SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

    final Cipher pbeCipher = Cipher.getInstance(ENC);
    pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

    final byte[] text = pbeCipher.doFinal(Base64.decodeBase64(encryptedText));
    return new String(text, "UTF-8").intern();
}

From source file:Main.java

/**
 * Initializes the Cipher for use./*from  w  ww .  ja v a  2  s .  co  m*/
 */
public static void initCipher(Cipher cipher, int mode, Key secretKey, AlgorithmParameterSpec parameterSpec) {
    try {
        if (parameterSpec != null) {
            cipher.init(mode, secretKey, parameterSpec);
        } else {
            cipher.init(mode, secretKey);
        }
    } catch (InvalidKeyException e) {
        throw new IllegalArgumentException("Unable to initialize due to invalid secret key", e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new IllegalStateException("Unable to initialize due to invalid decryption parameter spec", e);
    }
}

From source file:authentication.AES.java

public static String decrypt(String textoencriptado) throws Exception {
    Cipher decripta = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(chaveencriptacao.getBytes("UTF-8"), "AES");
    decripta.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
    return new String(decripta.doFinal(Base64.decodeBase64(textoencriptado)), "UTF-8");
}

From source file:authentication.AES.java

public static String encrypt(String textopuro) throws Exception {
    Cipher encripta = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(chaveencriptacao.getBytes("UTF-8"), "AES");
    encripta.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
    byte[] a = encripta.doFinal(textopuro.getBytes("UTF-8"));
    return StringUtils.newStringUtf8(Base64.encodeBase64(a, false));
}

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

/**
 * Encrypt String associated with a key//from   w  w w .  j av  a2 s .  c o  m
 *
 * @param value The value to encrypt
 * @return encrypted string
 */
public static String encrypt(String value) {
    if (StringUtils.isBlank(value)) {
        throw new IllegalArgumentException();
    }

    String encryptedText = "";

    try {
        Cipher cipher = Cipher.getInstance(CIPHER);
        cipher.init(Cipher.ENCRYPT_MODE, mSecretKeySpec, mIvParameterSpec);
        encryptedText = Base64.encodeToString(cipher.doFinal(value.getBytes()), Base64.NO_CLOSE);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Algorithm not found.");
    } catch (NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) {
        Log.e(TAG, "Exception during encrypt");
    } catch (InvalidKeyException e) {
        Log.e(TAG, "No valid key provided.");
    } catch (InvalidAlgorithmParameterException e) {
        Log.e(TAG, "Algorithm parameter specification is invalid");
    }

    return encryptedText;
}

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 . j a va 2  s  .c om
 * @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:com.adeptj.modules.security.jwt.internal.JwtKeys.java

static PrivateKey createSigningKey(JwtConfig jwtConfig, SignatureAlgorithm signatureAlgo) {
    LOGGER.info("Creating RSA signing key!!");
    String keyData = jwtConfig.privateKey();
    Assert.isTrue(StringUtils.startsWithAny(keyData, PRIVATE_ENCRYPTED_KEY_HEADER, PRIVATE_KEY_HEADER),
            INVALID_PRIVATE_KEY_MSG);//from  w ww . j ava2 s.  c  om
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(signatureAlgo.getFamilyName());
        if (StringUtils.startsWith(keyData, PRIVATE_ENCRYPTED_KEY_HEADER)) {
            LOGGER.info("Creating PKCS8EncodedKeySpec from private [encrypted] key !!");
            Assert.hasText(jwtConfig.privateKeyPassword(), KEYPASS_NULL_MSG);
            byte[] privateKeyData = decodePrivateKeyData(keyData, true);
            EncryptedPrivateKeyInfo privateKeyInfo = new EncryptedPrivateKeyInfo(privateKeyData);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(privateKeyInfo.getAlgName());
            PBEKeySpec keySpec = new PBEKeySpec(jwtConfig.privateKeyPassword().toCharArray());
            SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance(privateKeyInfo.getAlgName());
            cipher.init(DECRYPT_MODE, secretKey, privateKeyInfo.getAlgParameters());
            return keyFactory.generatePrivate(privateKeyInfo.getKeySpec(cipher));
        }
        LOGGER.info("Creating PKCS8EncodedKeySpec from private key !!");
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decodePrivateKeyData(keyData, false)));
    } catch (GeneralSecurityException | IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new KeyInitializationException(ex.getMessage(), ex);
    }
}

From source file:com.cl.roadshow.crypto.AESCtr.java

/**
 * Private decryption method.//  w  ww .  j  a  va 2s . co  m
 * 
 * @param keystring
 * @param message
 * @param bits
 * @return bytearray containing decrypted message
 * @throws Exception
 */
private static byte[] decrypt(String keystring, byte[] message, int bits) throws Exception {
    byte[] decValue = null;
    byte[] nonceBytes = Arrays.copyOf(Arrays.copyOf(message, 8), 16);
    IvParameterSpec nonce = new IvParameterSpec(nonceBytes);

    Key key = generateKey(keystring, bits);
    Cipher c = Cipher.getInstance(ALGORITHM);
    c.init(Cipher.DECRYPT_MODE, key, nonce);
    decValue = c.doFinal(message, 8, message.length - 8);

    return decValue;
}

From source file:com.miyue.util.Cryptos.java

/**
 * AES?, ?./*from  w w  w . j  av a2s.  c o m*/
 * 
 * @param input 
 * @param key ?AES?
 * @param iv ???
 * @param mode Cipher.ENCRYPT_MODE  Cipher.DECRYPT_MODE
 */
private static byte[] aes(byte[] input, byte[] key, byte[] iv, int mode) {
    try {
        SecretKey secretKey = new SecretKeySpec(key, AES);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance(AES_CBC);
        cipher.init(mode, secretKey, ivSpec);
        return cipher.doFinal(input);
    } catch (GeneralSecurityException e) {
        throw Exceptions.unchecked(e);
    }
}