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.com.amazonaws.cognito.devauthsample.Utilities.java

public static String sign(String content, String key) {
    try {//from  ww  w  . j a  v  a 2s.co  m
        byte[] data = content.getBytes(Constants.ENCODING_FORMAT);
        Mac mac = Mac.getInstance(Constants.SIGNATURE_METHOD);
        mac.init(new SecretKeySpec(key.getBytes(Constants.ENCODING_FORMAT), Constants.SIGNATURE_METHOD));
        char[] signature = Hex.encodeHex(mac.doFinal(data));
        return new String(signature);
    } catch (Exception e) {
        log.log(Level.SEVERE, "Exception during sign", e);
    }
    return null;
}

From source file:com.earldouglas.xjdl.io.LicenseLoader.java

protected License decryptLicense(String encodedLicense)
        throws BadPaddingException, UnsupportedEncodingException, Exception {
    byte[] encryptedLicense = Base64.decodeBase64(encodedLicense);

    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] serializedLicense = cipher.doFinal(encryptedLicense);

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(serializedLicense);
    ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
    License license = (License) objectInputStream.readObject();
    objectInputStream.close();//from  w  ww  .  j a  v a  2  s  .  co  m
    return license;
}

From source file:com.os.util.PasswordDecoderEncoder.java

public static String decrypt(String encryptPassword) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    key = convertHexToBytes(keyst);/*from w  w  w. j a  v  a 2s.  com*/
    final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKey);
    String encryptedString = new String(cipher.doFinal(Base64.decodeBase64(encryptPassword.getBytes())),
            "UTF-8");
    System.out.println(encryptedString);
    String passwordDecrypted = encryptedString.trim();

    return passwordDecrypted;

}

From source file:Models.Geographic.Repository.RepositoryGoogle.java

/**
 * Create a string URL with the corresponding signature code and client id.
 * @param path// w  ww  .  ja  va 2 s.c  om
 * @param query
 * @return the specified String URL
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws URISyntaxException
 */
private static String signRequest(String path, String query) throws NoSuchAlgorithmException,
        InvalidKeyException, UnsupportedEncodingException, URISyntaxException, IOException {
    if (RepositoryGoogle.mac == null) {
        // key
        byte[] key = Base64
                .decode(Configuration.getParameter("geocoding_google_key").replace('-', '+').replace('_', '/'));
        // Get an HMAC-SHA1 signing key from the raw key bytes
        SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1");
        // Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1

        RepositoryGoogle.mac = Mac.getInstance("HmacSHA1");
        RepositoryGoogle.mac.init(sha1Key);
    }
    // Retrieve the proper URL components to sign
    String resource = path + '?' + query + "&client=" + Configuration.getParameter("geocoding_google_client");
    // compute the binary signature for the request
    byte[] sigBytes = RepositoryGoogle.mac.doFinal(resource.getBytes());
    // base 64 encode the binary signature
    String signature = Base64.encodeBytes(sigBytes);
    // convert the signature to 'web safe' base 64
    signature = signature.replace('+', '-').replace('/', '_');
    return resource + "&signature=" + signature;
}

From source file:com.elle.analyster.admissions.AESCrypt.java

public static String decrypt(String key, String initVector, String encrypted) {
    try {/*ww w  . j  a  va  2s .co m*/
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

        byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

        return new String(original);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return null;
}

From source file:com.feedzai.commons.sql.abstraction.util.AESHelper.java

/**
 * Decrypts a string encrypted by {@link #encrypt} method.
 *
 * @param c   The encrypted HEX string.//from   ww  w.jav  a 2s .com
 * @param key The  key.
 * @return The decrypted string.
 */
public static String decrypt(String c, String key) {
    try {
        SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decoded = cipher.doFinal(Hex.decodeHex(c.toCharArray()));
        return new String(decoded);
    } catch (Exception e) {
        logger.warn("Could not decrypt string", e);
        return null;
    }
}

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

/**
 * Encrypts and encodes the Object and IV for url inclusion
 *
 * @param input//from  ww w .j a  v  a 2 s.c  o  m
 * @return
 * @throws Exception
 */
public String[] encryptObject(Object obj) throws Exception {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(stream);
    try {
        // Serialize the object
        out.writeObject(obj);
        byte[] serialized = stream.toByteArray();
        // Setup the cipher and Init Vector
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] iv = new byte[cipher.getBlockSize()];
        new SecureRandom().nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        // Hash the key with SHA-256 and trim the output to 128-bit for the key
        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");
        // encrypt
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        // Encrypt & Encode the input
        byte[] encrypted = cipher.doFinal(serialized);
        byte[] base64Encoded = Base64.encodeBase64(encrypted);
        String base64String = new String(base64Encoded);
        String urlEncodedData = URLEncoder.encode(base64String, "UTF-8");
        // Encode the Init Vector
        byte[] base64IV = Base64.encodeBase64(iv);
        String base64IVString = new String(base64IV);
        String urlEncodedIV = URLEncoder.encode(base64IVString, "UTF-8");

        return new String[] { urlEncodedData, urlEncodedIV };
    } finally {
        stream.close();
        out.close();
    }
}

From source file:eml.studio.shared.util.Aes.java

/** 
 * Aes Encryption //from  w w  w.  ja  va2 s . c o m
 * @param content content to be encrypted
 * @param encryptKey encryption key
 * @return 
 * @throws Exception 
 */
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);
    Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

    return cipher.doFinal(content.getBytes("utf-8"));
}

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

/**
 * @see corner.encrypt.services.EncryptService#encrypt(byte[], byte[])
 *///from  ww w  .  j  a v  a 2 s  . com
@Override
public byte[] encrypt(byte[] src, byte[] key) {
    try {
        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:com.haulmont.cuba.web.test.PasswordEncryptionTest.java

protected String decryptPassword(String password) {
    SecretKeySpec key = new SecretKeySpec(PASSWORD_KEY.getBytes(), "DES");
    IvParameterSpec ivSpec = new IvParameterSpec(PASSWORD_KEY.getBytes());
    String result;//from   w w  w .  j  a  va2s  . c o m
    try {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        result = new String(cipher.doFinal(Hex.decodeHex(password.toCharArray())));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}