Example usage for javax.crypto Mac init

List of usage examples for javax.crypto Mac init

Introduction

In this page you can find the example usage for javax.crypto Mac init.

Prototype

public final void init(Key key) throws InvalidKeyException 

Source Link

Document

Initializes this Mac object with the given key.

Usage

From source file:org.linkdroid.PostJob.java

private static Mac initHmacSha1(String secretString, String nonce)
        throws NoSuchAlgorithmException, IOException, InvalidKeyException {
    SecretKey key = new SecretKeySpec(secretString.getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(key);
    if (nonce != null) {
        mac.update(nonce.getBytes(UTF8));
    }/*from  w ww  . jav a  2  s . com*/
    return mac;
}

From source file:org.identityconnectors.office365.jsontoken.JWTTokenHelper.java

/**
 * Sign the text with the symmetric key.
 * @param signingKey The Signing Key./*from  w w  w .  j a  v  a  2  s .c  o m*/
 * @param rawToken The rawToken that needs to be signed.
 * @return Signed byte array.
 * @throws SampleAppException
 */
private static byte[] signData(String signingKey, String rawToken) throws Exception {
    SecretKeySpec secretKey = null;

    secretKey = new SecretKeySpec(com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(signingKey),
            "HmacSHA256");

    Mac mac;
    byte[] signedData = null;

    mac = Mac.getInstance("HmacSHA256");
    mac.init(secretKey);
    mac.update(rawToken.getBytes("UTF-8"));
    signedData = mac.doFinal();

    return signedData;
}

From source file:org.cloudfoundry.identity.uaa.authentication.RubyUserTokenTests.java

private static byte[] sign(String username, long validUntil, SecretKey key) {
    Mac mac;
    try {/*  w  w w  .j  av a  2s.  c  o  m*/
        mac = Mac.getInstance("HMACSHA1");
        mac.init(key);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("Failed to create and initialize MAC: ", e);
    }

    byte[] bytesToSign = Utf8.encode(username + validUntil);
    //      HexDumpEncoder enc = new HexDumpEncoder();
    //      System.out.println("Signing bytes: \n" + enc.encode(bytesToSign));
    byte[] sig = mac.doFinal(bytesToSign);
    //      System.out.println("Signature is: \n" + enc.encode(sig));
    return sig;
}

From source file:com.flazr.Utils.java

public static byte[] sha256(byte[] message, byte[] key) {
    Mac mac;
    try {/*from   www.j  ava2 s  .c om*/
        mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key, "HmacSHA256"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return mac.doFinal(message);
}

From source file:org.apache.http.contrib.auth.AWSScheme.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data//ww w . ja v a 2 s .c  o m
 *            The data to be signed.
 * @param key
 *            The signing key.
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws RuntimeException
 *             when signature generation fails
 */
private static String calculateRFC2104HMAC(final String data, final String key) throws AuthenticationException {
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes());

        // base64-encode the hmac
        return Base64.encodeBase64String(rawHmac);

    } catch (InvalidKeyException ex) {
        throw new AuthenticationException("Failed to generate HMAC: " + ex.getMessage(), ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new AuthenticationException(HMAC_SHA1_ALGORITHM + " algorithm is not supported", ex);
    }
}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelper.java

public static byte[] calculateHMac(String token, PublicKey publicKey) throws GeneralSecurityException {
    SecretKeySpec keySpec = new SecretKeySpec(token.getBytes(StandardCharsets.UTF_8), "RAW");
    Mac mac = Mac.getInstance("Hmac-SHA256", BouncyCastleProvider.PROVIDER_NAME);
    mac.init(keySpec);
    return mac.doFinal(getKeyIdentifier(publicKey));
}

From source file:com.swdouglass.joid.Crypto.java

private static byte[] hmacShaX(String keySpec, byte[] key, byte[] text)
        throws InvalidKeyException, NoSuchAlgorithmException {
    SecretKey sk = new SecretKeySpec(key, keySpec);
    Mac m = Mac.getInstance(sk.getAlgorithm());
    m.init(sk);
    return m.doFinal(text);
}

From source file:Main.java

static byte[] decryptJWE(String jwe, Key privRsaKey) {
    // Log.d("","decryptJWE");

    try {//from  ww w  . j a  va 2 s  .  c  om
        // split jwe string
        StringTokenizer tokens = new StringTokenizer(jwe, ".");
        int count = tokens.countTokens();
        // Log.d("","parts.length: "+count);

        if (count != 5)
            return null;

        String jweProtectedHeader64 = tokens.nextToken();
        String jweEncrypted64 = tokens.nextToken();
        String jweInitVector64 = tokens.nextToken();
        String cryptedBytes64 = tokens.nextToken();
        String auth_tag64 = tokens.nextToken();

        // decrypt cek using private rsa key
        byte[] cek = decryptRsaB64(jweEncrypted64, privRsaKey);

        // check cek result byte array
        if (cek == null || cek.length == 0 || (cek.length % 2) != 0)
            return null;

        int keySize = cek.length / 2;
        Log.d("", "Decryption AES: " + keySize * 8);

        // build aes_key and hmac_key
        byte aes_key[] = new byte[keySize];
        byte hmac_key[] = new byte[keySize];

        System.arraycopy(cek, 0, hmac_key, 0, keySize);
        System.arraycopy(cek, keySize, aes_key, 0, keySize);

        // decode initialization vector
        byte[] iv_key = decodeB64(jweInitVector64);

        Log.d("", "hmac_key: " + bytesToHex(hmac_key));
        Log.d("", "aes_key:  " + bytesToHex(aes_key));
        Log.d("", "iv_key:   " + bytesToHex(iv_key));

        // decrypt content using aes_key and iv_key
        byte[] cryptedBytes = decodeB64(cryptedBytes64);
        Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SC");
        decrypt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aes_key, "AES"), new IvParameterSpec(iv_key));
        byte[] decryptedBytes = decrypt.doFinal(cryptedBytes);

        Log.d("", "decryptedBytes:");
        Log.d("", bytesToHex(decryptedBytes));

        // validation verification
        byte[] aad = jweProtectedHeader64.getBytes();
        long al = aad.length * 8;

        // concatenate aad, iv_key, cryptedBytes and al 
        byte[] hmacData = new byte[aad.length + iv_key.length + cryptedBytes.length + 8];
        int offset = 0;
        System.arraycopy(aad, offset, hmacData, 0, aad.length);
        offset += aad.length;
        System.arraycopy(iv_key, 0, hmacData, offset, iv_key.length);
        offset += iv_key.length;
        System.arraycopy(cryptedBytes, 0, hmacData, offset, cryptedBytes.length);
        offset += cryptedBytes.length;
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.putLong(al);
        System.arraycopy(buffer.array(), 0, hmacData, offset, 8);

        // compute hmac
        Mac hmac = Mac.getInstance("HmacSHA256", "SC");
        hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));
        byte[] hmacValue = hmac.doFinal(hmacData);

        // pick authentication tag
        byte[] authTag = Arrays.copyOf(hmacValue, 16);

        // validate authentication tag
        byte[] authTagRead = decodeB64(auth_tag64);
        for (int i = 0; i < 16; i++) {
            if (authTag[i] != authTagRead[i]) {
                Log.d("", "validation failed");
                return decryptedBytes;
            }
        }

        Log.d("", "validation success");

        // validation success
        return decryptedBytes;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.annuletconsulting.homecommand.server.HomeCommand.java

private static String getSignature(String timeStamp) {
    if (sharedKey != null)
        try {/*from   w w  w . java2 s .c o m*/
            byte[] data = timeStamp.getBytes(ENCODING_FORMAT);
            Mac mac = Mac.getInstance(SIGNATURE_METHOD);
            mac.init(new SecretKeySpec(sharedKey.getBytes(ENCODING_FORMAT), SIGNATURE_METHOD));
            char[] signature = Hex.encodeHex(mac.doFinal(data));
            return new String(signature);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    return "Error in getSignature()";
}

From source file:ch.rasc.wampspring.cra.DefaultAuthenticationHandler.java

public static String generateHMacSHA256(final String key, final String data)
        throws InvalidKeyException, NoSuchAlgorithmException {
    Assert.notNull(key, "key is required");
    Assert.notNull(data, "data is required");

    final Mac hMacSHA256 = Mac.getInstance("HmacSHA256");
    byte[] hmacKeyBytes = key.getBytes(StandardCharsets.UTF_8);
    final SecretKeySpec secretKey = new SecretKeySpec(hmacKeyBytes, "HmacSHA256");
    hMacSHA256.init(secretKey);
    byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
    byte[] res = hMacSHA256.doFinal(dataBytes);

    return DatatypeConverter.printBase64Binary(res);
}