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.eucalyptus.auth.euare.EuareServerCertificateUtil.java

public static String getEncryptedKey(final String certArn, final String certPem) throws AuthException {
    final ServerCertificate targetCert = lookupServerCertificate(certArn);
    // generate symmetric key
    final MessageDigest digest = Digest.SHA256.get();
    final byte[] salt = new byte[32];
    Crypto.getSecureRandomSupplier().get().nextBytes(salt);
    digest.update(salt);//from  w w w .  ja v  a  2s.c  o  m
    final SecretKey symmKey = new SecretKeySpec(digest.digest(), "AES");

    try {
        // encrypt the server pk using symm key
        Cipher cipher = Ciphers.AES_CBC.get();
        final byte[] iv = new byte[16];
        Crypto.getSecureRandomSupplier().get().nextBytes(iv);
        cipher.init(Cipher.ENCRYPT_MODE, symmKey, new IvParameterSpec(iv),
                Crypto.getSecureRandomSupplier().get());
        final byte[] cipherText = cipher.doFinal(Base64.encode(targetCert.getPrivateKey().getBytes()));
        final String encPrivKey = new String(Base64.encode(Arrays.concatenate(iv, cipherText)));

        // encrypt the symmetric key using the certPem
        X509Certificate x509Cert = PEMFiles.getCert(B64.standard.dec(certPem));
        cipher = Ciphers.RSA_PKCS1.get();
        cipher.init(Cipher.ENCRYPT_MODE, x509Cert.getPublicKey(), Crypto.getSecureRandomSupplier().get());
        byte[] symmkey = cipher.doFinal(symmKey.getEncoded());
        final String b64SymKey = new String(Base64.encode(symmkey));

        return String.format("%s\n%s", b64SymKey, encPrivKey);
    } catch (final Exception ex) {
        throw Exceptions.toUndeclared(ex);
    }
}

From source file:com.livily.pusher.Pusher.java

/**
 * Returns a HMAC/SHA256 representation of the given string
 * //from   w  ww .  j  ava  2 s  .c o  m
 * @param data
 * @return
 */
private static String hmacsha256Representation(String data) {
    try {
        // Create the HMAC/SHA256 key from application secret
        final SecretKeySpec signingKey = new SecretKeySpec(pusherApplicationSecret.getBytes(), "HmacSHA256");

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

        // Process and return data
        byte[] digest = mac.doFinal(data.getBytes("UTF-8"));
        digest = mac.doFinal(data.getBytes());
        // Convert to string
        BigInteger bigInteger = new BigInteger(1, digest);
        return String.format("%0" + (digest.length << 1) + "x", bigInteger);
    } catch (NoSuchAlgorithmException nsae) {
        // We should never come here, because GAE has HMac SHA256
        throw new RuntimeException("No HMac SHA256 algorithm");
    } catch (UnsupportedEncodingException e) {
        // We should never come here, because UTF-8 should be available
        throw new RuntimeException("No UTF-8");
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Invalid key exception while converting to HMac SHA256");
    }
}

From source file:br.com.manish.ahy.kernel.util.HashUtil.java

private static Cipher getCipher(boolean enc)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);/*from   w w  w.  j a v a 2 s  .c  o m*/
    SecretKeySpec skeySpec = new SecretKeySpec(getBytes(HEXES2), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    if (enc) {
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    } else {
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    }
    return cipher;
}

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

/**
 * Given a String, it is decoded and the result is returned as a String as well.
 * @param encodedUrl is a String that have the full data encrypted
 * @return decoded String//from   w  w w .  j  av a 2s.c  om
 */
public static String decode(String encodedUrl) {

    try {

        //Decode URL
        final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey,
                new IvParameterSpec(initializationVector.getBytes("UTF-8")));

        String result = new String(cipher.doFinal(Base64.decodeBase64(encodedUrl)));

        //Extract and remove hash from JSONObject
        JSONParser parser = new JSONParser();
        JSONObject receivedData = (JSONObject) parser.parse(result);
        String receivedHash = (String) receivedData.get("hash");
        receivedData.remove("hash");

        //Compare received hash with newly computed hash
        if (checkDataValidity(receivedData)) {
            byte[] hashOfData = createMD5Hash(receivedData);

            if (receivedHash.equals(new String(hashOfData, "UTF-8"))) { //Valid data
                return receivedData.toString();
            }
        }
    } catch (Exception e) {
    } //Invalid data (including encryption algorithm exceptions

    return null;
}

From source file:co.edu.uniandes.csw.Arquidalgos.usuario.service._UsuarioService.java

@POST
@Path("/crearUsuario")
public UsuarioDTO crearUsuario(UsuarioDTO usuario) throws Exception {

    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    String key = "123";
    SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
    sha256_HMAC.init(secret_key);/*w ww.  jav  a 2s.  co  m*/

    System.out.println("TO String: " + usuario.toString());

    String hash = Hex.encodeHexString(sha256_HMAC.doFinal(usuario.toString().getBytes()));
    System.out.println("CODIGO HASH: " + hash);
    System.out.println("CODIGO HASH JSON " + usuario.getHash());

    boolean alterado = !(hash.equalsIgnoreCase(usuario.getHash()));
    System.out.println("Alterado: " + alterado);

    if (alterado) {
        throw new Exception("Se han alterado los datos");
    }
    return createUsuario(usuario);
}

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

public Blowfish(String keySpec, byte[] paramSpec) {
    this.keySpec = new SecretKeySpec(keySpec.getBytes(), ALGORITHM);
    this.paramSpec = new IvParameterSpec(paramSpec);
    initBlowfish();// ww  w  .j  av a2 s  .c o  m
}

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

/**
 * @see corner.encrypt.services.EncryptService#decrypt(byte[], byte[])
 *///  w  ww . ja v  a 2 s .co m
@Override
public byte[] decrypt(byte[] src, byte[] keybyte) {
    try {
        SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
        Cipher c1 = Cipher.getInstance(Algorithm);
        c1.init(Cipher.DECRYPT_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:me.lazerka.gae.jersey.oauth2.facebook.TokenVerifierFacebookSignedRequest.java

public TokenVerifierFacebookSignedRequest(URLFetchService urlFetchService, ObjectMapper jackson, String appId,
        String appSecret, String redirectUri) {
    this.jackson = jackson;
    this.redirectUri = redirectUri;
    this.fetcher = new FacebookFetcher(appId, appSecret, jackson, urlFetchService);

    try {/*w ww.j a va2  s .  co  m*/
        SecretKeySpec signingKey = new SecretKeySpec(appSecret.getBytes(UTF_8), "HmacSHA1");
        hmac = Mac.getInstance("HmacSHA256");
        hmac.init(signingKey);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw Throwables.propagate(e);
    }
}

From source file:fitmon.WorkoutApi.java

public StringBuilder apiGetInfo()
        throws ClientProtocolException, IOException, NoSuchAlgorithmException, InvalidKeyException {
    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=4384");
    //HttpResponse response = client.execute(request);
    //BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
    //StringBuilder sb = new StringBuilder();
    String base = URLEncoder.encode("GET") + "&";
    base += "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&";

    String params;//from   w w w .  j  a va  2 s  .  c o m

    params = "format=json&";
    params += "method=exercises.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); 
    HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api?" + params
            + "&oauth_signature=" + URLEncoder.encode(hash));
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuilder sb = new StringBuilder();

    //$url = "http://platform.fatsecret.com/rest/server.api?"+params+"&oauth_signature="+URLEncoder.encode(hash);
    //return url;

    while ((line = rd.readLine()) != null) {
        sb.append(line);
        //System.out.println(line);
    }
    //System.out.println(sb.toString());
    return sb;
}

From source file:net.datacrow.onlinesearch.amazon.SignedRequestsHelper.java

public SignedRequestsHelper(String awsAccessKeyId, String awsSecretKey)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    this.awsAccessKeyId = awsAccessKeyId;
    this.awsSecretKey = awsSecretKey;

    byte[] secretyKeyBytes = this.awsSecretKey.getBytes(UTF8_CHARSET);
    this.secretKeySpec = new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM);
    this.mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
    this.mac.init(secretKeySpec);
}