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.baran.crypto.CryptoDES.java

public byte[] encrypt(File file, String trivia) throws Exception {
    final MessageDigest md = MessageDigest.getInstance("md5");
    // digest the trivia password in UTF-8
    final byte[] digestTrivia = md.digest(trivia.getBytes("utf-8"));

    // truncating digest
    final byte[] keyBytes = Arrays.copyOf(digestTrivia, 24);
    for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];//from  w  w w .j  av  a 2 s .  co m
    }
    // DESede setting
    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");

    // CBC IV setting
    final IvParameterSpec iv = new IvParameterSpec(new byte[8]);

    final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);

    String allInOne = FileUtils.readFileToString(file, "utf-8");

    final byte[] plainTextBytes = allInOne.getBytes("utf-8");
    final byte[] cipherText = cipher.doFinal(plainTextBytes);

    return cipherText;
}

From source file:com.google.resting.rest.util.oauth.SignatureUtil.java

/**
 * Sign request./*from w w w  .jav  a2  s. c  o  m*/
 * 
 * @param keyString Consumer key for request signing.
 * @param targetDomain Domain of the REST endpoint (Ex. login.yahoo.com)
 * @param verb Type of REST operation (GET/POST/PUT/DELETE)
 * @param isSecureInvocation HTTP/HTTPS
 * @param contextPathElement Path element in the base REST uri (Ex. /weather/india)
 * @param inputParams Collection of request params for REST request (Ex. city=calcutta )
 * @return
 * @throws NoSuchAlgorithmException The exception is thrown if the encryption algorithm is not supported.
 * @throws InvalidKeyException The exception is thrown if the consumer key is invalid
 * @throws IllegalStateException 
 * @throws UnsupportedEncodingException The exception is thrown if the URL encoding is incorrect.
 */
public static String getSignature(String keyString, String targetDomain, Verb verb, boolean isSecureInvocation,
        String contextPathElement, List<NameValuePair> inputParams, String messageEncoding)
        throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException,
        UnsupportedEncodingException {

    String baseString = getBaseString(targetDomain, verb.toString(), isSecureInvocation, contextPathElement,
            inputParams, messageEncoding).replace("+", "%20").replace("*", "%2A").replace("%7E", "~");

    System.out.println("Base string is " + baseString);
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(keyString.getBytes(messageEncoding), mac.getAlgorithm());
    mac.init(secret);
    byte[] digest = mac.doFinal(baseString.getBytes(messageEncoding));
    return new String(Base64.encodeBase64(digest)).replace(RequestConstants.CARRIAGE_RETURN,
            RequestConstants.EMPTY_STRING);
}

From source file:edu.utdallas.bigsecret.cipher.AesCtr.java

/**
 * Class constructor. Creates a Javax.Crypto.Cipher instance with AES in CTR<br>
 * mode, without any padding. /*from   ww w .ja v  a2 s . c o m*/
 * @param key Input key for the cipher. Should be 16, 24, or 32 bytes long
 * @throws Exception Throws exception if key length is not 16, 24, or 32 bytes.<br>
 *                 May throw exception based on Javax.Crypto classes.
 */
public AesCtr(byte[] key) throws Exception {
    //use default constructor for cipher.Cipher
    super();

    //check if input key is ok
    if (key.length != 16 && key.length != 24 && key.length != 32) {
        throw new Exception("Key length should be 16, 24, or 32 bytes long");
    }

    //set key length
    KEY_SIZE_BYTES = key.length;

    //create secret key spec instance
    m_keySpec = new SecretKeySpec(key, "AES");

    //create cipher instance
    m_cipher = javax.crypto.Cipher.getInstance("AES/CTR/NoPadding");

    //create secure random number generator instance
    m_secureRandom = new SecureRandom();
}

From source file:com.teasoft.teavote.util.AppProperties.java

public void setSecret(String secret) {
    try {// w ww . j  av a 2s .c  o m
        String first = PBKDF2_ALGORITHM.substring(0, PBKDF2_ALGORITHM.length() - 2);
        String second = "";
        for (int i = 0, j = 12; i < 4; i++) {
            second += first.substring(j - (i * 4), first.length() - i * 4);
        }
        Key aesKey = new SecretKeySpec(second.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        byte[] encrypted = cipher.doFinal(secret.getBytes());
        this.secret = Base64.encodeBase64String(encrypted);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException ex) {
        Logger.getLogger(AppProperties.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.aqnote.shared.encrypt.symmetric.Blowfish.java

/**
 * ?//from w  w w.  j  av  a 2 s  . com
 * 
 * @return Key
 */
private static Key generateKey(String keyStr) {
    byte[] keyBytes = null;
    try {
        if (keyStr == null) {
            keyBytes = DEFAULT_KEY.getBytes(DEFAULT_CHARSET);
        } else {
            keyBytes = keyStr.getBytes(DEFAULT_CHARSET);
        }
    } catch (UnsupportedEncodingException e) {
    }
    return new SecretKeySpec(keyBytes, "Blowfish");
}

From source file:SecurityUtils.java

/**
 * Converts a source string to its HMAC/SHA-1 value.
 * /*from ww w.  j a v a2  s.co m*/
 * @param source
 *            The source string to convert.
 * @param secretKey
 *            The secret key to use for conversion.
 * @return The HMac value of the source string.
 */
public static byte[] toHMac(String source, String secretKey) {
    byte[] result = null;

    try {
        // Create the HMAC/SHA1 key
        final SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");

        // Create the message authentication code (MAC)
        final Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // Compute the HMAC value
        result = mac.doFinal(source.getBytes());
    } catch (NoSuchAlgorithmException nsae) {
        throw new RuntimeException("Could not find the SHA-1 algorithm. HMac conversion failed.", nsae);
    } catch (InvalidKeyException ike) {
        throw new RuntimeException("Invalid key exception detected. HMac conversion failed.", ike);
    }

    return result;
}

From source file:fr.ortolang.diffusion.security.authentication.TOTPHelper.java

private static byte[] hmacSha(byte[] keyBytes, byte[] text) {
    try {/*from  ww w.  j  a  v  a  2  s .co  m*/
        Mac hmac;
        hmac = Mac.getInstance("HmacSHA1");
        SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
        hmac.init(macKey);
        return hmac.doFinal(text);
    } catch (GeneralSecurityException gse) {
        throw new UndeclaredThrowableException(gse);
    }
}

From source file:adminpassword.AESDemo.java

@SuppressWarnings("static-access")
public String decrypt(String encryptedText) throws Exception {

    byte[] saltBytes = salt.getBytes("UTF-8");
    byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText);

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, pswdIterations, keySize);

    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    // Decrypt the message
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));

    byte[] decryptedTextBytes = null;
    try {/*www.  ja  v  a 2 s  .  co m*/
        decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }

    return new String(decryptedTextBytes);
}

From source file:net.sourceforge.vulcan.web.SignedRequestAuthorizationFilter.java

@Override
protected void initFilterBean() throws ServletException {
    if (StringUtils.isBlank(sharedSecret)) {
        secretKey = null;/*from  w  ww. j ava2  s.  co  m*/
        return;
    }

    try {
        secretKey = new SecretKeySpec(sharedSecret.getBytes(), algorithm);

        // Initialize a mac instance to fail fast on NoSuchAlgorithmException or InvalidKeyException.
        // This way any configuration errors will prevent the application from starting instead of causing
        // problems later.
        final Mac mac = Mac.getInstance(algorithm);

        mac.init(secretKey);
    } catch (NoSuchAlgorithmException e) {
        throw new ServletException(e);
    } catch (InvalidKeyException e) {
        throw new ServletException(e);
    }
}

From source file:com.kku.apps.pricesearch.util.SignedHelper.java

private static String sign(String apiSecretKey, String sourceString) throws Exception {
    SecretKeySpec secretKeySpec = new SecretKeySpec(apiSecretKey.getBytes(ENCODING), ALGORITHM);
    Mac mac = Mac.getInstance(ALGORITHM);
    mac.init(secretKeySpec);//from  w  ww.  j a va 2 s .c om
    byte[] data = mac.doFinal(sourceString.getBytes(ENCODING));
    Base64 encoder = new Base64();
    String signature = new String(encoder.encode(data));
    return signature;
}