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.confighub.core.security.Encryption.java

private static String encryptShared(CipherTransformation ct, String decrypted, String secret)
        throws ConfigException {
    if (null == decrypted)
        return null;

    try {/*from  w w w . j  a  va2s .c om*/
        Cipher cipher = Cipher.getInstance(ct.getName());
        final int blockSize = cipher.getBlockSize();

        SecretKeySpec sharedKey = new SecretKeySpec(getKeyAsBytes(secret, ct.getKeyLen()), ct.getAlgo());

        if ("CBC".equals(ct.getMode()))
            cipher.init(Cipher.ENCRYPT_MODE, sharedKey, new IvParameterSpec(getIV(blockSize)));
        else
            cipher.init(Cipher.ENCRYPT_MODE, sharedKey);

        byte[] encrypted = cipher.doFinal(Utils.isBlank(decrypted) ? new byte[0] : decrypted.getBytes("UTF8"));
        return Base64.encodeBase64String(encrypted);
    } catch (Exception e) {
        throw new ConfigException(Error.Code.ENCRYPTION_ERROR);
    }
}

From source file:chronic.app.ChronicCookie.java

public static String createAuthCode(byte[] secret, String string, long value) throws GeneralSecurityException {
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec signKey = new SecretKeySpec(secret, "HmacSHA1");
    mac.init(signKey);//  ww w.  ja va  2 s. c  om
    mac.update(string.getBytes());
    return new Base32().encodeAsString(mac.doFinal(Bytes.toByteArray(value)));
}

From source file:Main.java

/**
 * Generates SHA256 hash of the password which is used as key
 *
 * @param password used to generated key
 * @return SHA256 of the password//from w w  w. j  a  v  a 2  s. c om
 */
private static SecretKeySpec generateKey(final String password)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    final MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
    byte[] bytes = password.getBytes("UTF-8");
    digest.update(bytes, 0, bytes.length);
    byte[] key = digest.digest();

    log("SHA-256 key ", key);

    return new SecretKeySpec(key, "AES");
}

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

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

From source file:org.edeoliveira.oauth2.dropwizard.oauth2.auth.CookieEncrypter.java

public CookieEncrypter(String secret) throws Exception {
    byte[] tmp = secret.getBytes(UTF8);

    if ((tmp.length * 8) < BIT_LENGTH)
        throw new IllegalArgumentException(
                "Wrong key size (" + (tmp.length * 8) + ") lower than the " + BIT_LENGTH + " bits required");

    byte[] secretKey = new byte[BIT_LENGTH / 8];
    System.arraycopy(tmp, 0, secretKey, 0, secretKey.length);
    keySpec = new SecretKeySpec(secretKey, ALGORITHM);
}

From source file:com.ec2box.manage.util.EncryptionUtil.java

/**
 * return decrypted value of encrypted string
 *
 * @param str encrypted string//from  w w  w . ja va2 s  .com
 * @return decrypted string
 */
public static String decrypt(String str) {
    String retVal = null;
    if (str != null && str.length() > 0) {
        try {
            Cipher c = Cipher.getInstance("AES");
            c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
            byte[] decodedVal = Base64.decodeBase64(str.getBytes());
            retVal = new String(c.doFinal(decodedVal));
        } catch (Exception ex) {
            log.error(ex.toString(), ex);
        }

    }
    return retVal;
}

From source file:com.bconomy.autobit.Encryption.java

public static byte[] decrypt(byte[] cyphertext, byte[] key) {
    if (keySpec == null)
        keySpec = new SecretKeySpec(key, "AES");
    Cipher aes;/* ww w .j ava2 s .  c  o m*/
    try {
        aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
        aes.init(Cipher.DECRYPT_MODE, keySpec);
        return aes.doFinal(cyphertext);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException ex) {
        ex.printStackTrace();
    }
    return new byte[0];
}

From source file:net.sourceforge.js3tream.util.Access.java

/*******************************************************
 * @throws Exception/*w  ww . j  a  v a  2  s. c  om*/
 ******************************************************/
public Access() throws Exception {
    this.calFormat_ = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
    this.calFormat_.setTimeZone(TimeZone.getTimeZone("GMT"));
    this.mac_ = Mac.getInstance(HMAC_SHA1);
    this.mac_.init(new SecretKeySpec(Access.accessSecret_.getBytes(), HMAC_SHA1));

}

From source file:com.xwiki.authentication.AbstractAuthServiceImpl.java

protected String encryptText(String text, XWikiContext context) {
    try {//from ww  w  .j a  v  a 2s  .  co m
        String secretKey = null;
        secretKey = context.getWiki().Param("xwiki.authentication.encryptionKey");
        secretKey = secretKey.substring(0, 24);

        if (secretKey != null) {
            SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "TripleDES");
            Cipher cipher = Cipher.getInstance("TripleDES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encrypted = cipher.doFinal(text.getBytes());
            String encoded = new String(Base64.encodeBase64(encrypted));
            return encoded.replaceAll("=", "_");
        } else {
            LOG.error("Encryption key not defined");
        }
    } catch (Exception e) {
        LOG.error("Failed to encrypt text", e);
    }

    return null;
}

From source file:com.sshtools.j2ssh.transport.hmac.HmacSha.java

/**
 *
 *
 * @param keydata//  w  w  w.  ja v a 2s.com
 *
 * @throws AlgorithmInitializationException
 */
public void init(byte[] keydata) throws AlgorithmInitializationException {
    try {
        mac = Mac.getInstance("HmacSha1");

        byte[] key = new byte[20];
        System.arraycopy(keydata, 0, key, 0, 20);

        SecretKeySpec keyspec = new SecretKeySpec(key, "HmacSha1");

        mac.init(keyspec);
    } catch (NoSuchAlgorithmException nsae) {
        throw new AlgorithmInitializationException("No provider exists for the HmacSha1 algorithm");
    } catch (InvalidKeyException ike) {
        throw new AlgorithmInitializationException("Invalid key");
    }
}