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:net.mobid.codetraq.utils.PasswordProcessor.java

/**
 * Encrypts a text using the <code>passPhrase</code> above and an algorithm supported
 * by your virtual machine implementation. You can change the default algorithm with
 * another algorithm, but please make sure your virtual machine supports it.
 * @param valueToEncrypt - text to encrypt
 * @return an encrypted, Base64 encoded text
 *//*from  www  . jav  a2  s.c  o  m*/
public static String encryptString(String valueToEncrypt) {
    String output = null;
    try {
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterations);
        SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterations);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        // begin encrypting...
        byte[] byteToEncrypt = valueToEncrypt.getBytes("UTF8");
        byte[] encrypted = cipher.doFinal(byteToEncrypt);
        output = new Base64().encodeToString(encrypted);
    } catch (Exception ex) {
        Logger.getLogger(PasswordProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:net.mobid.codetraq.utils.PasswordProcessor.java

/**
 * Decrypts a text using the <code>passPhrase</code> above and an algorithm supported
 * by your virtual machine implementation. You can change the default algorithm with
 * another algorithm, but please make sure your virtual machine supports it.
 * @param valueToDecrypt - text to decrypt
 * @return a plain text//from   www.  jav a2 s .  c o m
 */
public static String decryptString(String valueToDecrypt) {
    String output = null;
    try {
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterations);
        SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterations);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
        // begin decrypting...
        byte[] encrypted = new Base64().decode(valueToDecrypt);
        byte[] utf8 = cipher.doFinal(encrypted);
        output = new String(utf8, "UTF8");
    } catch (Exception ex) {
        Logger.getLogger(PasswordProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:com.screenslicer.common.Crypto.java

private static String decodeHelper(String cipherText, String encryptionKey) {
    if (cipherText == null || encryptionKey == null) {
        return null;
    }/*from w w w.  jav  a 2  s. c  om*/
    try {
        Cipher aesCipher = Cipher.getInstance("AES");
        aesCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(DigestUtils.sha256(encryptionKey), "AES"),
                aesCipher.getParameters());
        return new String(aesCipher.doFinal(Base64.decodeBase64(cipherText)), "utf-8");
    } catch (Exception e) {
        return null;
    }
}

From source file:com.example.license.DESUtil.java

/**
 * ?// w  w w  . j  a  v a2s.c o  m
 * 
 * @param data
 *            ?
 * @param key
 *            
 * @return ??
 */
public static String encrypt(String data, String key) throws Exception {
    Key deskey = keyGenerator(key);
    // Cipher??
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    SecureRandom random = new SecureRandom();
    // ?Cipher?
    cipher.init(Cipher.ENCRYPT_MODE, deskey, random);
    byte[] results = cipher.doFinal(data.getBytes("UTF-8"));
    // http://tripledes.online-domain-tools.com/??
    for (int i = 0; i < results.length; i++) {
        System.out.print(results[i] + " ");
    }
    System.out.println();
    // ??Base64?
    return Base64.encodeBase64String(results);
}

From source file:com.aurel.track.report.query.ReportQueryBL.java

private static String encrypt(String clearText, char[] password) {
    // Create PBE parameter set
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
    byte[] ciphertext = { 0 };

    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    try {//from ww  w. ja v a  2s . c  om
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

        // Encrypt the cleartext
        ciphertext = pbeCipher.doFinal(clearText.getBytes());
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
    return new String(Base64.encodeBase64(ciphertext));
}

From source file:com.aurel.track.admin.customize.category.filter.execute.ReportQueryBL.java

private static String encrypt(String clearText, char[] password) {
    // Create PBE parameter set
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
    byte[] ciphertext = { 0 };

    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    try {//  w  w  w . j a v  a  2s .  c o  m
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

        // Encrypt the cleartext
        ciphertext = pbeCipher.doFinal(clearText.getBytes());
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e), e);
    }
    return new String(Base64.encodeBase64(ciphertext));
}

From source file:Main.java

public static String encryptData(String password, String plaintextData) throws Exception {
    // Thank you Mr. Nelenkov
    String maybeThisHelps = "http://nelenkov.blogspot.com/2012/04/using-password-based-encryption-on.html";
    Log.v(TAG, maybeThisHelps);/*from w  w  w .java  2s .c  o  m*/
    int iterationCount = 100; //because Polaroid
    int keyLength = 256;
    int saltLength = keyLength;

    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[saltLength];
    random.nextBytes(salt);
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] iv = new byte[cipher.getBlockSize()];
    random.nextBytes(iv);

    IvParameterSpec ivParams = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
    byte[] ciphertext = cipher.doFinal(plaintextData.getBytes("UTF-8"));

    String ivToString = new String(Base64.encode(iv, 0));
    String saltToString = new String(Base64.encode(salt, 0));
    String ciphertextToString = new String(Base64.encode(ciphertext, 0));

    Log.d(TAG, ivToString + "]" + saltToString + "]" + ciphertextToString);
    return (ivToString + "]" + saltToString + "]" + ciphertextToString).replace("\n", "");
}

From source file:com.aurel.track.report.query.ReportQueryBL.java

private static String dcl(String encryptedText, char[] password) {
    byte[] clearText = { ' ' };
    int count = 20;
    PBEKeySpec pbeKeySpec;//from   w  w w  .j  av a 2 s. com
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;
    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);
    pbeKeySpec = new PBEKeySpec(password);
    try {
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

        byte[] ciphertext = Base64.decodeBase64(encryptedText);

        // Decrypt the cleartext
        clearText = pbeCipher.doFinal(ciphertext);
    } catch (Exception e) {
    }
    return new String(clearText);
}

From source file:clases.Seguridad.java

public static String desencriptar(String encrypted) throws Exception {
    Cipher cipher = Cipher.getInstance(CI);
    SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes(), ALG);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
    byte[] enc = decodeBase64(encrypted);
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
    byte[] decrypted = cipher.doFinal(enc);
    return new String(decrypted);
}

From source file:com.myapp.common.AES4MEncrypt.java

/**
 * /*from  ww  w.  j  av  a  2 s  . c o  m*/
 * 
 * @param sSrc 
 * @param sKey KEY
 * @return
 * @throws Exception
 * @author cdduqiang
 * @date 201443
 */
public static String encrypt(String sSrc, String sKey) throws Exception {
    if (sKey == null) {
        log.error("Encrypt Key ??");
        throw new Exception("Encrypt Key ??");
    }

    byte[] raw = hex2byte(sKey);
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
    byte[] anslBytes = sSrc.getBytes(ENCODING);// string2AnslBytes(sSrc);
    byte[] encrypted = cipher.doFinal(anslBytes);
    return byte2hex(encrypted).toUpperCase();
}