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.skplanet.syruppay.token.tav.TransactionAuthenticationValue.java

public String getChecksumBy(final String key)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException {
    final Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm()));
    mac.update((cardToken + mctTransAuthId + ocTransAuthId
            + new ObjectMapper().writeValueAsString(paymentAuthenticationDetail)).getBytes("UTF-8"));
    return Base64.encodeBase64URLSafeString(mac.doFinal());
}

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

/**
 * Method to AES encrypt string if fails, will attempt to use {@link #encryptLegacy(String str, byte[] key)}
 * @param str string to encrypt/*  ww  w .j av a 2s  .co  m*/
 * @param key encryption key
 * @return encrypted string or "" if legacy fails
 */
public static String encrypt(String str, byte[] key) {
    try {
        Cipher aes = Cipher.getInstance("AES");
        aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(pad(key), "AES"));
        return Base64.encodeBase64String(aes.doFinal(("FDT:" + str).getBytes("utf8")));
    } catch (Exception e) {
        Logger.logError("Error Encrypting information, reverting to legacy format", e);
        return encryptLegacy(str, key);
    }
}

From source file:fitmon.DietAPI.java

public ArrayList<Food> getFood(String foodID) throws ClientProtocolException, IOException,
        NoSuchAlgorithmException, InvalidKeyException, SAXException, ParserConfigurationException {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api&"
            + "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1408230438&"
            + "oauth_nonce=abc&oauth_version=1.0&method=food.get&food_id=33691");
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    String base = URLEncoder.encode("GET") + "&";
    base += "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&";

    String params;/*from w  ww.  j  a  va2 s.com*/

    params = "food_id=" + foodID + "&";
    params += "method=food.get&";
    params += "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&"; // ur consumer key 
    params += "oauth_nonce=123&";
    params += "oauth_signature_method=HMAC-SHA1&";
    Date date = new java.util.Date();
    Timestamp ts = new Timestamp(date.getTime());
    params += "oauth_timestamp=" + ts.getTime() + "&";
    params += "oauth_version=1.0";
    //params += "search_expression=apple"; 

    String params2 = URLEncoder.encode(params);
    base += params2;
    System.out.println(base);
    String line = "";

    String secret = "76172de2330a4e55b90cbd2eb44f8c63&";
    Mac sha256_HMAC = Mac.getInstance("HMACSHA1");
    SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HMACSHA1");
    sha256_HMAC.init(secret_key);
    String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(base.getBytes()));

    //$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig); 

    String url = "http://platform.fatsecret.com/rest/server.api?" + params + "&oauth_signature="
            + URLEncoder.encode(hash);
    System.out.println(url);
    xmlParser xParser = new xmlParser();
    ArrayList<Food> foodList = xParser.Parser(url);
    return foodList;
    //while ((line = rd.readLine()) != null) {
    //  System.out.println(line);
    //}
}

From source file:edu.stanford.junction.extra.Encryption.java

private void init() {
    try {/*from  w  ww  . j a va2 s  . c  o  m*/
        mCipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        mKeySpec = new SecretKeySpec(mKey, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.thischwa.pmcms.tool.DESCryptor.java

private Key buildKey() throws CryptorException {
    try {//from w w w  .j  av  a 2s . c  o  m
        return new SecretKeySpec(secretKeyPlain.getBytes(encoding), this.algorithm);
    } catch (UnsupportedEncodingException e) {
        throw new CryptorException(e);
    }
}

From source file:cn.vlabs.duckling.aone.client.impl.EmailNameEncoding.java

public String getEncryptEmail(String email) {
    String context = getContext(email);

    SecretKeySpec spec;/*from  w  ww.jav  a  2  s  .co  m*/
    try {
        spec = new SecretKeySpec(getKey(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, spec);
        byte[] result = cipher.doFinal(context.getBytes("utf-8"));
        return encodeByte(result);
    } catch (Exception e) {
        throw new RuntimeException("", e);
    }
}

From source file:com.github.bmadecoder.Authenticator.java

private void init(byte[] internalToken) throws InvalidKeyException {
    SecretKeySpec secretKeySpec = new SecretKeySpec(internalToken, "HmacSHA1");
    try {//  w  w w .  j  a  va  2s . c  om
        mac = Mac.getInstance("HmacSHA1");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    mac.init(secretKeySpec);
}

From source file:controllers.DiscourseAuth.java

@Override
public void configure(Env env, Config conf, Binder binder) throws Throwable {
    if (!conf.hasPath(SECRET_KEY)) {
        return;/*from w ww.ja va  2s .  com*/
    }
    byte[] keyBytes = conf.getString(SECRET_KEY).getBytes(StandardCharsets.UTF_8);
    SecretKeySpec key = new SecretKeySpec(keyBytes, "HmacSHA256");
    env.router().get(Routes.API + "/discourseAuth", req -> {
        // validate request from server
        String payload = urlDecode(req.param("sso").value());
        String sig = req.param("sig").value();
        if (!checksum(key, payload).equals(sig)) {
            throw new IllegalArgumentException("Invalid signature");
        }
        // decode the nonce
        String nonce = decodeBase64(payload);
        String response = appendUserInfoToNonce(req, nonce);
        String response64 = encodeBase64(response);
        if (!response64.endsWith("\n")) {
            response64 += "\n";
        }
        return Results.redirect(
                DISCOURSE_SSO + "?sso=" + urlEncode(response64) + "&sig=" + checksum(key, response64));
    });
}

From source file:mitm.common.security.otp.HMACOTPGenerator.java

private Mac createMAC(byte[] secret) throws OTPException {

    try {/*ww  w .  j  a  v a2s.com*/
        Mac mac = securityFactory.createMAC(algorithm);

        SecretKeySpec keySpec = new SecretKeySpec(secret, "raw");

        mac.init(keySpec);

        return mac;
    } catch (NoSuchAlgorithmException e) {
        throw new OTPException(e);
    } catch (NoSuchProviderException e) {
        throw new OTPException(e);
    } catch (InvalidKeyException e) {
        throw new OTPException(e);
    }
}

From source file:testFileHandler.java

public void decrypt(String encryptedText, String secretKey, javax.swing.JTextArea plainTextField)
        throws Exception {

    byte[] message = Base64.decodeBase64(encryptedText.getBytes("utf-8"));

    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 decipher = Cipher.getInstance("DESede");
    decipher.init(Cipher.DECRYPT_MODE, key);

    byte[] plainText = decipher.doFinal(message);
    plainTextField.setText(new String(plainText, "UTF-8"));
}