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.scraper.SignedRequestsHelper.java

public SignedRequestsHelper()
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    byte[] secretyKeyBytes = awsSecretKey.getBytes(UTF8_CHARSET);
    secretKeySpec = new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM);
    mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
    mac.init(secretKeySpec);/*from  w w w .j  a va  2  s .c o  m*/
}

From source file:com.linecorp.platform.channel.sample.BusinessConnect.java

public boolean validateBCRequest(String httpRequestBody, String channelSecret, String channelSignature) {
    if (httpRequestBody == null || channelSecret == null || channelSignature == null) {
        return false;
    }/*from   www  .  j a  v  a  2 s  .c o m*/

    String signature;
    SecretKeySpec key = new SecretKeySpec(channelSecret.getBytes(), "HmacSHA256");
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(key);
        byte[] source = httpRequestBody.getBytes("UTF-8");
        signature = Base64.encodeBase64String(mac.doFinal(source));
    } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
        e.printStackTrace();
        return false;
    }
    return channelSignature.equals(signature);
}

From source file:com.clustercontrol.commons.util.CryptUtil.java

private static String encrypt(String key, String word) {
    if (word == null) {
        return null;
    }//from  w w w  .ja  v a 2  s .  co  m
    // ?
    SecretKeySpec sksSpec = new SecretKeySpec(key.getBytes(), algorithm);
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance(algorithm);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        m_log.warn("encrypt : " + (e.getClass().getName()) + "," + e.getMessage(), e);
        return null;
    }
    try {
        cipher.init(Cipher.ENCRYPT_MODE, sksSpec);
    } catch (InvalidKeyException e) {
        m_log.warn("encrypt : " + (e.getClass().getName()) + "," + e.getMessage(), e);
        return null;
    }

    byte[] encrypted = null;
    try {
        encrypted = cipher.doFinal(word.getBytes());
    } catch (IllegalBlockSizeException | BadPaddingException e) {
        m_log.warn("encrypt : " + (e.getClass().getName()) + "," + e.getMessage(), e);
        return null;
    }

    return Base64.encodeBase64String(encrypted);
}

From source file:testFileHandler.java

public void encrypt(String message, String secretKey, javax.swing.JTextArea ciphertextField) throws Exception {

    MessageDigest md = MessageDigest.getInstance("SHA-1");
    byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
    byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

    SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    // Encode the string into bytes using utf-8
    byte[] plainTextBytes = message.getBytes("utf-8");
    // Encrypt/*from www  .  jav a 2s .  c o m*/
    byte[] buf = cipher.doFinal(plainTextBytes);
    // Encode bytes to base64 to get a string
    byte[] base64Bytes = Base64.encodeBase64(buf);
    String base64EncryptedString = new String(base64Bytes);

    ciphertextField.setText(base64EncryptedString);
}

From source file:com.searchcode.app.util.AESEncryptor.java

public byte[] decrypt(byte[] cipherText) throws Exception {
    SecretKeySpec secretKey = new SecretKeySpec(this.key, this.ALGORITHM);
    Cipher cipher = Cipher.getInstance(this.ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, secretKey);

    return cipher.doFinal(cipherText);
}

From source file:lti.oauth.OAuthMessageSigner.java

/**
 * This method double encodes the parameter keys and values.
 * Thus, it expects the keys and values contained in the 'parameters' SortedMap
 * NOT to be encoded./*from  w w  w. java 2 s  .c  o  m*/
 * 
 * @param secret
 * @param algorithm
 * @param method
 * @param url
 * @param parameters
 * @return oauth signature
 * @throws Exception
 */
public String sign(String secret, String algorithm, String method, String url,
        SortedMap<String, String> parameters) throws Exception {
    SecretKeySpec secretKeySpec = new SecretKeySpec((secret.concat(OAuthUtil.AMPERSAND)).getBytes(), algorithm);
    Mac mac = Mac.getInstance(secretKeySpec.getAlgorithm());
    mac.init(secretKeySpec);

    StringBuilder signatureBase = new StringBuilder(OAuthUtil.percentEncode(method));
    signatureBase.append(OAuthUtil.AMPERSAND);

    signatureBase.append(OAuthUtil.percentEncode(url));
    signatureBase.append(OAuthUtil.AMPERSAND);

    int count = 0;
    for (String key : parameters.keySet()) {
        count++;
        signatureBase.append(OAuthUtil.percentEncode(OAuthUtil.percentEncode(key)));
        signatureBase.append(URLEncoder.encode(OAuthUtil.EQUAL, OAuthUtil.ENCODING));
        signatureBase.append(OAuthUtil.percentEncode(OAuthUtil.percentEncode(parameters.get(key))));

        if (count < parameters.size()) {
            signatureBase.append(URLEncoder.encode(OAuthUtil.AMPERSAND, OAuthUtil.ENCODING));
        }
    }

    if (log.isDebugEnabled()) {
        log.debug(signatureBase.toString());
    }

    byte[] bytes = mac.doFinal(signatureBase.toString().getBytes());
    byte[] encodedMacBytes = Base64.encodeBase64(bytes);

    return new String(encodedMacBytes);
}

From source file:net.ftb.util.CryptoUtils.java

/**
 * Method to AES decrypt string if fails, will attempt to use {@link #decryptLegacy(String str, byte[] key)}
 * @param str string to decrypt//from w w  w.j  a  va  2s. c  o m
 * @param key decryption key key
 * @return decrypted string or "" if legacy fails
 */
public static String decrypt(String str, byte[] key) {
    try {
        Cipher aes = Cipher.getInstance("AES");
        aes.init(Cipher.DECRYPT_MODE, new SecretKeySpec(pad(key), "AES"));
        String s = new String(aes.doFinal(Base64.decodeBase64(str)), "utf8");
        if (s.startsWith("FDT:") && s.length() > 4)
            return s.split(":", 2)[1];//we don't want the decryption test
        else
            return decryptLegacy(str, key);
    } catch (Exception e) {
        Logger.logError("Error Decrypting information, attempting legacy decryption", e);
        return decryptLegacy(str, key);
    }
}

From source file:com.commander4j.util.JCipher.java

private Cipher getCipher(int cipherMode) throws Exception {
    String encryptionAlgorithm = "AES";
    SecretKeySpec keySpecification = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), encryptionAlgorithm);
    Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
    cipher.init(cipherMode, keySpecification);

    return cipher;
}

From source file:com.javaps.springboot.LicenseController.java

@RequestMapping(value = "/public/license", produces = "text/plain", method = RequestMethod.GET)
public String licenseIssue(@RequestParam(value = "ip") String clientIp) throws Exception {
    SecretKeySpec signingKey = new SecretKeySpec(licenseSecretKey.getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signingKey);//from  w ww.j  av a  2 s  .  com

    byte[] rawHmac = mac.doFinal(clientIp.getBytes());
    return Base64.encodeBase64String(rawHmac);
}

From source file:ch.newscron.encryption.Encryption.java

/**
 * Given a JSONObject, and maybe an hash, it is encoded and returned as a String.
 * @param inviteData is a JSONObject having the data with the keys "customerId", "rew1", "rew2" and "val"
 * @param md5Hash is a String that substitute the hash computed using md5 algorithm, in case it is not null and not empty
 * @return encoded string //from w w w . j  a v  a 2 s. c o  m
 */
protected static String encode(JSONObject inviteData, String md5Hash) {

    try {
        //Check in case we want to add a given hash (having at the end a corrupt data)
        if (md5Hash != null && !md5Hash.isEmpty()) {
            //Add md5Hash to JSONObject
            inviteData.put("hash", md5Hash);
        } else {
            return null;
        }

        //Encode inviteData (with hash) JSONObject
        String params = inviteData.toString();
        final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey,
                new IvParameterSpec(initializationVector.getBytes("UTF-8")));
        return Base64.encodeBase64URLSafeString(cipher.doFinal(params.getBytes())); //to ensure valid URL characters
    } catch (Exception e) {
    }

    return null;
}