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:com.eugene.fithealthmaingit.FatSecretSearchAndGet.FatSecretGetMethod.java

private static String sign(String method, String uri, String[] params) {
    String[] p = { method, Uri.encode(uri), Uri.encode(paramify(params)) };
    String s = join(p, "&");
    SecretKey sk = new SecretKeySpec(Globals.APP_SECRET.getBytes(), Globals.HMAC_SHA1_ALGORITHM);
    try {//from   w  w w.ja  v a 2 s  .  c  om
        Mac m = Mac.getInstance(Globals.HMAC_SHA1_ALGORITHM);
        m.init(sk);
        return Uri.encode(new String(Base64.encode(m.doFinal(s.getBytes()), Base64.DEFAULT)).trim());
    } catch (java.security.NoSuchAlgorithmException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    } catch (java.security.InvalidKeyException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    }
}

From source file:com.twilio.sdk.TwilioUtils.java

public boolean validateRequest(String expectedSignature, String url, Map<String, String> params) {

    SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1");

    try {/*from www . j  ava2 s.  c o m*/
        //initialize the hash algortihm
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        //sort the params alphabetically, and append the key and value of each to the url
        StringBuffer data = new StringBuffer(url);
        if (params != null) {
            List<String> sortedKeys = new ArrayList<String>(params.keySet());
            Collections.sort(sortedKeys);

            for (String s : sortedKeys) {
                data.append(s);
                String v = "";
                if (params.get(s) != null) {
                    v = params.get(s);
                }
                data.append(v);
            }
        }

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

        //base64-encode the hmac
        String signature = new String(Base64.encodeBase64(rawHmac));

        return signature.equals(expectedSignature);
    } catch (NoSuchAlgorithmException e) {

        return false;
    } catch (InvalidKeyException e) {

        return false;
    } catch (UnsupportedEncodingException e) {
        return false;
    }
}

From source file:com.cloudant.sync.datastore.encryption.DPKEncryptionUtil.java

/**
 * AES Encrypt a byte array/*from   w ww  . j a va 2s . c  o  m*/
 *
 * @param key              The encryption key
 * @param iv               The iv
 * @param unencryptedBytes The data to encrypt
 * @return The encrypted data
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
public static byte[] encryptAES(SecretKey key, byte[] iv, byte[] unencryptedBytes)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParameter = new IvParameterSpec(iv);
    // see http://stackoverflow.com/a/11506343
    Key encryptionKey = new SecretKeySpec(key.getEncoded(), "AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, encryptionKey, ivParameter);
    return aesCipher.doFinal(unencryptedBytes);
}

From source file:com.credomatic.gprod.db2query2csv.Security.java

/**
 * Cifra una cadena de carateres utilizando el algoritmo AES y una llave (128, 256, o 512 bits). 
 * @param KeySize tamao de la llave autogenerada para relizar el cifrado
 * @param value cadena de caracteres que sera cifrada
 * @return instancia de tipo ${@link SecurityParams} con el resultado del proceso de cifrado
 *//*from w ww.j a  v  a 2  s .c  o  m*/
public static SecurityParams encrypt(int KeySize, String value) {

    SecurityParams result = null;
    try {
        // Get the KeyGenerator
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(KeySize);

        // Generate the secret key specs.
        final SecretKey skey = kgen.generateKey();
        final byte[] raw = skey.getEncoded();
        final SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        final Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        final String key = new Base64().encodeAsString(raw);
        final String encrypt = (new Base64()).encodeAsString(cipher.doFinal(value.getBytes()));

        result = new SecurityParams(encrypt, key, KeySize);

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

From source file:com.khipu.lib.java.KhipuService.java

public static String HmacSHA256(String secret, String data) {
    try {//from   w  w w  .  j  av  a2  s . c  om
        SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKeySpec);
        byte[] digest = mac.doFinal(data.getBytes("UTF-8"));
        return byteArrayToString(digest);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Invalid key exception while converting to HMac SHA256");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Algorithm not supported");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Encoding not supported");
    }
}

From source file:com.scorpio4.util.io.IOStreamCrypto.java

public CipherInputStream decrypt(InputStream in) throws NoSuchPaddingException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, InvalidKeyException {
    final SecretKey key = new SecretKeySpec(bytePassword, cipherSpec);
    final IvParameterSpec IV = new IvParameterSpec(ivBytes);
    final Cipher cipher = Cipher.getInstance(cipherTransformation);
    cipher.init(Cipher.DECRYPT_MODE, key, IV);
    return new CipherInputStream(new Base64InputStream(in), cipher);
}

From source file:net.bryansaunders.jee6divelog.util.HashUtils.java

/**
 * Generates a HMAC-SHA1 Hash of the given String using the specified key.
 * //from   w ww  .j ava 2 s  .  com
 * @param stringToHash
 *            String to Hash
 * @param key
 *            Key to Sign the String with
 * @return Hashed String
 */
public static String toHmacSha1(final String stringToHash, final String key) {
    String result = "";
    try {
        // Get an hmac_sha1 key from the raw key bytes
        final byte[] keyBytes = key.getBytes();
        final SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        final Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

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

        // Convert raw bytes to Hex
        final byte[] base64 = Base64.encodeBase64(rawHmac);

        // Covert array of Hex bytes to a String
        result = new String(base64);
    } catch (GeneralSecurityException e) {
        HashUtils.LOGGER.error("An Error Occured Generating an HMAC-SHA1 Hash!", e);
    }

    return result;
}

From source file:Models.UserModel.java

public static String HMAC_SHA256(String email, String password) {
    try {//from  w ww.  ja  v  a2  s. com

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(password.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        String auth = Base64.encodeBase64String(sha256_HMAC.doFinal(email.getBytes()));
        return auth;
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException e) {
        System.out.println("Error HS-256");
        return "";
    }
}

From source file:org.sentilo.common.rest.hmac.HMACBuilder.java

private static String calculateHMAC(final String secret, final String data) throws GeneralSecurityException {
    final SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), MAC_ALGORITHM);

    final Mac mac = Mac.getInstance(MAC_ALGORITHM);
    mac.init(signingKey);//from w ww  . j ava 2  s .  co m

    final byte[] rawHmac = mac.doFinal(data.getBytes());
    return new String(Base64.encodeBase64(rawHmac));
}

From source file:com.frame.Conf.Utilidades.java

/**
 * /*from www  .  ja v a2s  . c om*/
 * @param keypass Es la llave plublica para enctriptar el texto
 * @param texto Texto a encriptar
 * @return retorna el hash del texto encriptado
 * @throws Exception 
 */
public String Encriptar(String keypass, String texto) throws Exception {

    String secretKey = keypass; //llave para encriptar datos
    String base64EncryptedString = "";

    try {

        MessageDigest md = MessageDigest.getInstance("MD5");
        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);
        base64EncryptedString = new String(base64Bytes);

    } catch (NoSuchAlgorithmException | UnsupportedEncodingException | NoSuchPaddingException
            | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
        throw new Exception(ex.getMessage());
    }
    return base64EncryptedString;
}