Example usage for javax.crypto.spec SecretKeySpec SecretKeySpec

List of usage examples for javax.crypto.spec SecretKeySpec SecretKeySpec

Introduction

In this page you can find the example usage for javax.crypto.spec SecretKeySpec SecretKeySpec.

Prototype

public SecretKeySpec(byte[] key, String algorithm) 

Source Link

Document

Constructs a secret key from the given byte array.

Usage

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   ww w .  ja  v  a2s  .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:Main.java

private static Mac getMacForPassphrase(String passphrase, byte[] salt, int iterations)
        throws GeneralSecurityException {
    SecretKey key = getKeyFromPassphrase(passphrase, salt, iterations);
    byte[] pbkdf2 = key.getEncoded();
    SecretKeySpec hmacKey = new SecretKeySpec(pbkdf2, "HmacSHA1");
    Mac hmac = Mac.getInstance("HmacSHA1");
    hmac.init(hmacKey);//w  w  w .  j  a  va 2  s .  c  om

    return hmac;
}

From source file:Main.java

public static byte[] cipher(int mode, byte[] data, byte[] secret) throws NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    SecretKeySpec secretKeySpec = new SecretKeySpec(sha256(secret), "AES");
    Cipher c = Cipher.getInstance("AES");
    c.init(mode, secretKeySpec);/* w  w  w  . jav  a2 s.c om*/
    return c.doFinal(data);
}

From source file:com.juicioenlinea.application.secutiry.Security.java

public static String encriptar(String texto) {

    final String secretKey = "hunter"; //llave para encriptar datos
    String encryptedString = null;

    try {/*from ww  w . j  a  v  a2s.  c  o m*/

        MessageDigest md = MessageDigest.getInstance("SHA");
        byte[] digestOfPassword = md.digest(secretKey.getBytes("UTF-8"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

        SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        Cipher cipher = Cipher.getInstance("DESede");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] plainTextBytes = texto.getBytes("UTF-8");
        byte[] buf = cipher.doFinal(plainTextBytes);
        byte[] base64Bytes = Base64.encodeBase64(buf);
        encryptedString = new String(base64Bytes);

    } catch (NoSuchAlgorithmException | UnsupportedEncodingException | NoSuchPaddingException
            | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
        Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
    }
    return encryptedString;
}

From source file:com.salesmanager.core.util.EncryptionUtil.java

public static String decryptFromExternal(String key, String value) throws Exception {

    if (value == null || value.equals(""))
        return "";

    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
    IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    byte[] outText;
    outText = cipher.doFinal(hexToBytes(value));
    return new String(outText);

}

From source file:com.music.util.SecurityUtils.java

/**
 * Calculates a HmacSHA1 value//  w  w w.ja  v a  2 s . c om
 *
 * @param data
 * @param key
 * @return HmacSHA1
 */
public static String hmac(String data, String key) {
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes());

        String result = new String(Hex.encodeHex(rawHmac));
        return result.toUpperCase();
    } catch (Exception ex) {
        throw new RuntimeException("Problem with calculating hmac", ex);
    }
}

From source file:ec.edu.uce.medicina.seguimiento.util.EncryptionUtility.java

/**
 *Mtodo que permite la encriptacin de la contrasea.
 * @param cleartext//w w  w  . ja v  a 2 s.c o  m
 * @return
 * @throws java.lang.Exception
 */
public static String encrypt(String cleartext) throws Exception {
    String key = "02AE31B79CCCB2A3"; //llave
    String iv = "0123456789ABCDEF";
    Cipher cipher = Cipher.getInstance(cI);
    SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), alg);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
    byte[] encrypted = cipher.doFinal(cleartext.getBytes());
    return new String(encodeBase64(encrypted));
}

From source file:com.qubole.quark.catalog.db.encryption.AESEncrypt.java

public static SecretKeySpec generateMySQLAESKey(String key, String encoding) {
    try {/*from   ww  w  . jav  a2 s .  c  om*/

        byte[] finalKey = new byte[16];
        int i = 0;
        for (byte b : key.getBytes(encoding)) {
            finalKey[i++ % 16] ^= b;
        }
        return new SecretKeySpec(finalKey, "AES");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:Logic.security.java

public static String symmetricDecrypt(String text, String secretKey) {
    Cipher cipher;/*from  w  w w  .j a v  a  2s.  c  om*/
    String encryptedString;
    byte[] encryptText = null;
    byte[] raw;
    SecretKeySpec skeySpec;
    try {
        raw = Base64.decodeBase64(secretKey);
        skeySpec = new SecretKeySpec(raw, "AES");
        encryptText = Base64.decodeBase64(text);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        encryptedString = new String(cipher.doFinal(encryptText));
    } catch (Exception e) {
        e.printStackTrace();
        return "Error";
    }
    return encryptedString;
}

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);
}