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

private static String generateSignature(String base, String type, String nonce, String timestamp, String token,
        String tokenSecret, String verifier, ArrayList<String> parameters)
        throws NoSuchAlgorithmException, InvalidKeyException {
    String encodedBase = Uri.encode(base);

    StringBuilder builder = new StringBuilder();

    //Create an array of all the parameters
    //So that we can sort them
    //OAuth requires that we sort all parameters
    ArrayList<String> sortingArray = new ArrayList<String>();

    sortingArray.add("oauth_consumer_key=" + oauthConsumerKey);
    sortingArray.add("oauth_nonce=" + nonce);
    sortingArray.add("oauth_signature_method=HMAC-SHA1");
    sortingArray.add("oauth_timestamp=" + timestamp);
    sortingArray.add("oauth_version=1.0");

    if (parameters != null) {
        sortingArray.addAll(parameters);
    }//  w  ww  .  ja  va2  s.co m

    if (token != "" && token != null) {
        sortingArray.add("oauth_token=" + token);
    }
    if (verifier != "" && verifier != null) {
        sortingArray.add("oauth_verifier=" + verifier);
    }

    Collections.sort(sortingArray);

    //Append all parameters to the builder in the right order
    for (int i = 0; i < sortingArray.size(); i++) {
        if (i > 0)
            builder.append("&" + sortingArray.get(i));
        else
            builder.append(sortingArray.get(i));

    }

    String params = builder.toString();
    //Percent encoded the whole url
    String encodedParams = Uri.encode(params);

    String completeUrl = type + "&" + encodedBase + "&" + encodedParams;

    String completeSecret = oauthSecretKey;

    if (tokenSecret != null && tokenSecret != "") {
        completeSecret = completeSecret + "&" + tokenSecret;
    } else {
        completeSecret = completeSecret + "&";
    }

    Log.v("Complete URL: ", completeUrl);
    Log.v("Complete Key: ", completeSecret);

    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(completeSecret.getBytes(), mac.getAlgorithm());
    mac.init(secret);
    byte[] sig = mac.doFinal(completeUrl.getBytes());

    String signature = Base64.encodeToString(sig, 0);
    signature = signature.replace("+", "%2b"); //Specifically encode all +s to %2b

    return signature;
}

From source file:in.mtap.iincube.mongoser.codec.crypto.Psyfer.java

public static Psyfer getInstance(String secretKey) throws NoSuchAlgorithmException,
        UnsupportedEncodingException, NoSuchPaddingException, InvalidKeyException {
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    byte[] key = digest.digest(secretKey.getBytes("UTF-8"));
    key = Arrays.copyOf(key, 16);
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
    Cipher eCipher = Cipher.getInstance("AES");
    Cipher deCipher = Cipher.getInstance("AES");
    eCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    deCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    return new Psyfer(eCipher, deCipher);
}

From source file:cn.ucloud.sdk.utils.EncoderUtils.java

/**
 * SHA1//  w  w w .  ja  va 2  s.  c  o  m
 * @param key
 * @param str
 * @return
 */
public static String sha1(String key, String str) {
    String algorithm = "HmacSHA1";
    String result = null;
    try {
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(keySpec);
        result = getFormattedText(mac.doFinal(str.getBytes("UTF-8")));
    } catch (Exception e) {
        LogUtils.exception(logger, e);
    }
    return result;
}

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

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

    // value = StringUtils.rightPad(value, 16,"*");
    // Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    // NEED TO UNDERSTAND WHY PKCS5Padding DOES NOT WORK
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
    IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
    byte[] inpbytes = value.getBytes();
    byte[] encrypted = cipher.doFinal(inpbytes);
    return new String(bytesToHex(encrypted));

}

From source file:com.AES256Util.java

public AES256Util(String key) throws UnsupportedEncodingException {

    this.iv = key.substring(0, 16);

    byte[] keyBytes = new byte[16];

    byte[] b = key.getBytes("UTF-8");

    int len = b.length;

    if (len > keyBytes.length)

        len = keyBytes.length;//from   w w w . j  ava 2s .  c  om

    System.arraycopy(b, 0, keyBytes, 0, len);

    SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

    this.keySpec = keySpec;

}

From source file:com.k42b3.aletheia.oauth.HMACSHA1.java

public String build(String baseString, String consumerSecret, String tokenSecret) {
    try {//from   w w w .j  av a 2s.  com
        String key = Oauth.urlEncode(consumerSecret) + "&" + Oauth.urlEncode(tokenSecret);

        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secret = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(secret);
        byte[] result = mac.doFinal(baseString.getBytes());

        return Base64.encodeBase64String(result);
    } catch (Exception e) {
        Aletheia.handleException(e);

        return null;
    }
}

From source file:com._64bitlabs.util.Encryptors.java

/**
 * Generates key required for encrypt and decrypt operations
 * @return Key//from  ww  w  .  j ava  2  s.c  o  m
 */
private static Key generateKey() {
    Key key = new SecretKeySpec(keyValues, ALGORITHM);
    return key;
}

From source file:corner.services.impl.DESedeEncryptServiceImpl.java

public byte[] encrypt(byte[] src, byte[] key) {
    try {//ww  w  . j  a  va2 s. com
        SecretKey deskey = new SecretKeySpec(key, Algorithm);
        Cipher c1 = Cipher.getInstance(Algorithm);
        c1.init(Cipher.ENCRYPT_MODE, deskey);
        return c1.doFinal(src);
    } catch (java.security.NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (javax.crypto.NoSuchPaddingException e2) {
        e2.printStackTrace();
    } catch (java.lang.Exception e3) {
        e3.printStackTrace();
    }
    return null;
}

From source file:Main.java

private static SecretKeySpec getKey(String password) throws UnsupportedEncodingException {

    // You can change it to 128 if you wish
    int keyLength = 256;
    byte[] keyBytes = new byte[keyLength / 8];
    // explicitly fill with zeros
    Arrays.fill(keyBytes, (byte) 0x0);

    // if password is shorter then key length, it will be zero-padded
    // to key length
    byte[] passwordBytes = password.getBytes("UTF-8");
    int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length;
    System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
    return key;//from   w w w .  ja v  a 2  s.  com
}

From source file:de.extra.client.plugins.outputplugin.crypto.ExtraCryptoUtil.java

/**
 * Generates a new SecretKeySpec using the encoded string. Uses the
 * specified algorithm to generate the key.
 *///from  ww  w  . jav  a  2 s . com
private static SecretKeySpec decodeKey(String encrpKey) throws Exception {
    SecretKeySpec skeySpec = null;
    new Base64().decode(encrpKey);
    byte[] raw = new Base64().decode(encrpKey);
    skeySpec = new SecretKeySpec(raw, ALGORITHM);

    return skeySpec;
}