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.earldouglas.xjdl.io.LicenseCreator.java

public String encryptLicense(License license, String key)
        throws Exception, NoSuchAlgorithmException, NoSuchPaddingException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    objectOutputStream.writeObject(license);
    objectOutputStream.close();//from  w  w  w  .  ja  va  2s . c  om
    byte[] serializedLicense = byteArrayOutputStream.toByteArray();

    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    byte[] encryptedLicense = cipher.doFinal(serializedLicense);
    String encodedLicense = Base64.encodeBase64String(encryptedLicense);
    encodedLicense = encodedLicense.replaceAll("\n", "");
    encodedLicense = encodedLicense.replaceAll("\r", "");
    return encodedLicense;
}

From source file:com.moha.demo.utils.Hashsalt.java

public String encrypt(String password) {
    String algorithm = EnvUtils.getProperty("algorithm");
    String keyString = EnvUtils.getProperty("keyString");
    SecretKey key = new SecretKeySpec(keyString.getBytes(), algorithm);

    try {//from w w w .  j a va2s.com
        Mac m = Mac.getInstance(algorithm);
        m.init(key);
        m.update(password.getBytes());
        byte[] mac = m.doFinal();
        return toHexString(mac);
    } catch (Exception e) {
        System.out.println(e.toString());
    }

    return StringUtils.EMPTY;
}

From source file:com.dasol.util.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  a v  a 2  s .c  om
    System.arraycopy(b, 0, keyBytes, 0, len);
    SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

    this.keySpec = keySpec;
}

From source file:com.cloud.bridge.util.S3SoapAuth.java

/**
 * Create a signature by the following method:
 *     new String( Base64( SHA1( key, byte array )))
 * //from w  w  w  .ja v  a  2 s  .  co  m
 * @param signIt    - the data to generate a keyed HMAC over
 * @param secretKey - the user's unique key for the HMAC operation
 * @return String   - the recalculated string
 */
private static String calculateRFC2104HMAC(String signIt, String secretKey) {
    String result = null;
    try {
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac hmacSha1 = Mac.getInstance("HmacSHA1");
        hmacSha1.init(key);
        byte[] rawHmac = hmacSha1.doFinal(signIt.getBytes());
        result = new String(Base64.encodeBase64(rawHmac));

    } catch (Exception e) {
        logger.error("Failed to generate keyed HMAC on soap request: " + e.getMessage());
        return null;
    }
    return result.trim();
}

From source file:com.rr.familyPlanning.ui.security.decryptObject.java

/**
 * Decrypts the String and serializes the object
 *
 * @param base64Data//from  www . j  a  v  a  2s  . c  o  m
 * @param base64IV
 * @return
 * @throws Exception
 */
public Object decryptObject(String base64Data, String base64IV) throws Exception {
    // Decode the data
    byte[] encryptedData = Base64.decodeBase64(base64Data.getBytes());

    // Decode the Init Vector
    byte[] rawIV = Base64.decodeBase64(base64IV.getBytes());

    // Configure the Cipher
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivSpec = new IvParameterSpec(rawIV);
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.update(keyString.getBytes());
    byte[] key = new byte[16];
    System.arraycopy(digest.digest(), 0, key, 0, key.length);
    SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

    // Decrypt the data..
    byte[] decrypted = cipher.doFinal(encryptedData);

    // Deserialize the object
    ByteArrayInputStream stream = new ByteArrayInputStream(decrypted);

    ObjectInput in = new ObjectInputStream(stream);
    Object obj = null;
    try {
        obj = in.readObject();
    } finally {
        stream.close();
        in.close();
    }
    return obj;
}

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

public String build(String baseString, String consumerSecret, String tokenSecret) throws Exception {
    String key = Oauth.urlEncode(consumerSecret) + "&" + Oauth.urlEncode(tokenSecret);

    Charset charset = Charset.defaultCharset();

    SecretKey sk = new SecretKeySpec(key.getBytes(charset), "HmacSHA1");

    Mac mac = Mac.getInstance("HmacSHA1");

    mac.init(sk);//from ww  w  . j  a  v  a  2 s  .c  o m

    byte[] result = mac.doFinal(baseString.getBytes(charset));

    return Base64.encodeBase64String(result);
}

From source file:aajavafx.Kripto.java

public String decrypt(String cipherText) throws Exception {
    Base64 decoder = new Base64();
    byte[] decodedBytes = org.apache.commons.codec.binary.Base64.decodeBase64(cipherText.getBytes());
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
    return new String(cipher.doFinal(decodedBytes), "UTF-8");
}

From source file:com.twosigma.jupyter.security.HashedMessageAuthenticationCode.java

public HashedMessageAuthenticationCode(String key) {
    checkNotNull(key, "No key specified");
    logger.info("Using signing hmac: {}", key);
    spec = new SecretKeySpec(key.getBytes(), TYPE);
}

From source file:com.app.utils.StringEncrypt.java

/**
 * Funcin de tipo String que recibe una llave (key), un vector de inicializacin (iv)
 * y el texto que se desea descifrar//from w w  w .jav a  2s.  co m
 * @param key la llave en tipo String a utilizar
 * @param iv el vector de inicializacin a utilizar
 * @param encrypted el texto cifrado en modo String
 * @return el texto desencriptado en modo String
 * @throws Exception puede devolver excepciones de los siguientes tipos: NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException
 */
public static String decrypt(String key, String iv, 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.janrain.backplane.common.HmacHashUtils.java

/**
 * @return true if the provided hmacHash matches the password, false otherwise
 *///  w w  w. j  av  a  2 s  .  c o  m
public static boolean checkHmacHash(String password, String hmacHash) {
    if (password == null || hmacHash == null)
        return false;

    String[] keyAndSigned = hmacHash.split("\\.");
    if (keyAndSigned.length != 2)
        return false;

    try {
        byte[] encodedKey = Base64.decodeBase64(keyAndSigned[0].getBytes(UTF8_STRING_ENCODING));
        String newSigned = hmacSign(new SecretKeySpec(encodedKey, HMAC_SHA256_ALGORITHM), password);
        String pwdHash = keyAndSigned[1];

        // equal-time compare
        if (newSigned.length() == 0 || newSigned.length() != pwdHash.length())
            return false;
        int result = 0;
        for (int i = 0; i < newSigned.length(); i++) {
            result |= newSigned.charAt(i) ^ pwdHash.charAt(i);
        }
        return result == 0;
    } catch (Exception e) {
        logger.error("Error checking HMAC hash: " + e.getMessage());
        return false;
    }
}