Example usage for javax.crypto Mac getInstance

List of usage examples for javax.crypto Mac getInstance

Introduction

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

Prototype

public static final Mac getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Mac object that implements the specified MAC algorithm.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    SecureRandom random = new SecureRandom();
    IvParameterSpec ivSpec = createCtrIvForAES();
    Key key = createKeyForAES(256, random);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    String input = "12345678";
    Mac mac = Mac.getInstance("DES", "BC");
    byte[] macKeyBytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
    Key macKey = new SecretKeySpec(macKeyBytes, "DES");

    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

    byte[] cipherText = new byte[cipher.getOutputSize(input.length() + mac.getMacLength())];

    int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0);

    mac.init(macKey);/* w ww .  j  a  va 2  s.  c o  m*/
    mac.update(input.getBytes());

    ctLength += cipher.doFinal(mac.doFinal(), 0, mac.getMacLength(), cipherText, ctLength);

    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);

    byte[] plainText = cipher.doFinal(cipherText, 0, ctLength);
    int messageLength = plainText.length - mac.getMacLength();

    mac.init(macKey);
    mac.update(plainText, 0, messageLength);

    byte[] messageHash = new byte[mac.getMacLength()];
    System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length);

    System.out.println("plain : " + new String(plainText) + " verified: "
            + MessageDigest.isEqual(mac.doFinal(), messageHash));

}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    SecureRandom random = new SecureRandom();
    IvParameterSpec ivSpec = createCtrIvForAES(1, random);
    Key key = createKeyForAES(256, random);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    String input = "www.java2s.com";
    Mac mac = Mac.getInstance("DES", "BC");
    byte[] macKeyBytes = "12345678".getBytes();
    Key macKey = new SecretKeySpec(macKeyBytes, "DES");
    System.out.println("input : " + input);

    // encryption step
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    byte[] cipherText = new byte[cipher.getOutputSize(input.length() + mac.getMacLength())];
    int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0);
    mac.init(macKey);/*  w  w  w .  ja va 2  s  .c  om*/
    mac.update(input.getBytes());
    ctLength += cipher.doFinal(mac.doFinal(), 0, mac.getMacLength(), cipherText, ctLength);
    System.out.println("cipherText : " + new String(cipherText));

    // decryption step
    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    byte[] plainText = cipher.doFinal(cipherText, 0, ctLength);
    int messageLength = plainText.length - mac.getMacLength();

    mac.init(macKey);
    mac.update(plainText, 0, messageLength);

    byte[] messageHash = new byte[mac.getMacLength()];
    System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length);

    System.out.println("plain : " + new String(plainText) + " verified: "
            + MessageDigest.isEqual(mac.doFinal(), messageHash));
}

From source file:Main.java

public static String completeJweFromSIM(String jweSIM) {
    // android.os.Debug.waitForDebugger();

    try {/*from w w w. java  2s. c om*/
        if (jweSIM != null && jweSIM.length() > 0) {
            String parts[] = jweSIM.split("\\.");
            ;
            if (parts != null && parts.length == 5) {
                // retrieve hmac key
                byte hmac_key[] = Base64.decode(parts[4], Base64.URL_SAFE);
                if (hmac_key != null && hmac_key.length == 16) {
                    // init hash instance
                    Mac hmac = Mac.getInstance("HmacSHA256", "SC");
                    hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));

                    byte[] aad = parts[0].getBytes();
                    long al = aad.length * 8;
                    byte[] iv_key = decodeB64(parts[2]);
                    byte[] cryptedBytes = decodeB64(parts[3]);

                    // build data to hash
                    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 hac value
                    byte[] hmacValue = hmac.doFinal(hmacData);
                    // authentication tag
                    byte[] auth_tag = Arrays.copyOf(hmacValue, 16);
                    String auth_tag64 = encodeB64(auth_tag);

                    // A.2.7. Complete Representation
                    String finalString = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3] + "."
                            + auth_tag64;

                    //                  // just for verification
                    //                  byte jwt64 [] = decryptJWE(finalString, RsaKeyTim.privRsaKey);
                    //                  if(jwt64!=null) {
                    //                     String jws = new String(jwt64);
                    //                     Log.d("completeJweFromSIM", "jws verify Key TIM :"+verifyJWS(jws,RsaKeyTim.pubRsaKey));
                    //                  }

                    return finalString;
                }
            }
            // 
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

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

    try {/* ww w .ja  v a2s .co m*/
        // 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:org.cesecore.audit.impl.queued.entity.HmacLogManagementDataTest.java

@Before
public void createHmacConfig() throws Exception {
    log.trace(">setUp()");

    tokenConfigData = new AuditLogCryptoTokenConfigData();
    tokenConfigData.setClassname(SoftCryptoToken.class.getName());
    Properties props = new Properties();
    props.setProperty(CryptoToken.AUTOACTIVATE_PIN_PROPERTY, tokenPin);

    CryptoToken token = CryptoTokenFactory.createCryptoToken(SoftCryptoToken.class.getName(), props, null, 1);
    token.activate(tokenPin.toCharArray());
    token.generateKey("HmacSHA1", 256, keyAlias);

    tokenConfigData.setProperties(props);

    hmac = new HmacLogManagementData();
    hmac.setAlgorithm(algorithm);/*from  ww  w  . ja  v  a2  s .c om*/
    hmac.setKeyLabel(keyAlias);
    hmac.setFrequency(0l);
    hmac.setTokenConfig(tokenConfigData);

    byte[] tokenData = token.getTokenData();
    tokenConfigData.setTokenData(tokenData);

    Key hMacKey = token.getKey(keyAlias);

    Mac hMac = Mac.getInstance(hmac.getAlgorithm(), token.getEncProviderName());
    hMac.init(hMacKey);
    hMac.update(dataToBeSigned.getBytes());
    signed = hMac.doFinal();

    log.trace("<setUp()");
}

From source file:org.cesecore.audit.impl.queued.entity.HmacLogManagementDataTest.java

@Test
public void test01LoadTokenConfigProps() throws Exception {

    AuditLogCryptoTokenConfigData tokenConfig = hmac.getTokenConfig();
    CryptoToken token = CryptoTokenFactory.createCryptoToken(tokenConfig.getClassname(),
            tokenConfig.getProperties(), tokenConfig.getTokenData(), 1);

    token.activate(//ww  w.  j ava  2 s. c om
            ((String) tokenConfig.getProperties().get(CryptoToken.AUTOACTIVATE_PIN_PROPERTY)).toCharArray());
    Key hMacKey = token.getKey(keyAlias);

    Mac hMac = Mac.getInstance(hmac.getAlgorithm(), token.getEncProviderName());
    hMac.init(hMacKey);
    hMac.update(dataToBeSigned.getBytes());
    byte[] signedData = hMac.doFinal();

    assertTrue(ArrayUtils.isEquals(signedData, signed));

}

From source file:com.zxlim.totp.TOTP.java

private final byte[] hmac(final byte[] data) {
    final Mac mac;

    try {/*from w w w  .j a va 2 s .  co  m*/
        mac = Mac.getInstance(HMAC_ALGORITHM, HMAC_PROVIDER);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        return null;
    }

    try {
        mac.init(new SecretKeySpec(secret, HMAC_ALGORITHM));
    } catch (InvalidKeyException e) {
        return null;
    }

    return mac.doFinal(data);
}

From source file:eap.util.EDcodeUtil.java

private static byte[] hmac(byte[] data, byte[] key, String algorithm) {
    try {//from  w  w w.j  a v a 2  s. c  om
        SecretKey secretKey = new SecretKeySpec(key, algorithm);

        Mac mac = Mac.getInstance(secretKey.getAlgorithm(), provider);
        mac.init(secretKey);

        return mac.doFinal(data);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("No such algorithm [" + algorithm + "]");
    } catch (InvalidKeyException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}

From source file:com.the_incognito.darry.incognitochatmessengertest.BouncyCastleImplementation.java

public static String hmacSha256(String key, String value) {
    try {/*from w  w w. j a v a 2  s. c  om*/
        //System.out.println(Base64.getEncoder().encodeToString(keyBytes));
        // Get an hmac_sha256 key from the raw key bytes
        System.out.println("First HMAC on = " + value);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256",
                new BouncyCastleProvider());
        char password[] = key.toCharArray();
        byte salt[] = "salt".getBytes();
        KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "HmacSHA256");

        // Get an hmac_sha256 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleProvider());
        mac.init(secret);

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

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);
        //  Covert array of Hex bytes to a String
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:com.the_incognito.darry.incognitochatmessengertest.BouncyCastleImplementation.java

public static boolean isValid(String plainText, String HMAC, String key) {
    try {// w w w .  jav a  2  s.c om
        System.out.println("HMAC on = " + plainText);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256",
                new BouncyCastleProvider());
        char password[] = key.toCharArray();
        byte salt[] = "salt".getBytes();
        KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "HmacSHA256");
        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleProvider());
        mac.init(secret);
        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(plainText.getBytes());
        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        //  Covert array of Hex bytes to a String
        String check = new String(hexBytes, "UTF-8");
        System.out.println("Checking = " + check);
        return check.equals(HMAC);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}