Example usage for javax.crypto Mac reset

List of usage examples for javax.crypto Mac reset

Introduction

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

Prototype

public final void reset() 

Source Link

Document

Resets this Mac object.

Usage

From source file:example.DecrypterException.java

/**
 * Performs the decryption algorithm.//from www  .ja  va 2 s.c  o  m
 *
 * This method decrypts the ciphertext using the encryption key and verifies
 * the integrity bits with the integrity key. The encrypted format is:
 * {initialization_vector (16 bytes)}{ciphertext}{integrity (4 bytes)}
 * https://developers.google.com/ad-exchange/rtb/response-guide/decrypt-
 * hyperlocal,
 * https://developers.google.com/ad-exchange/rtb/response-guide/decrypt
 * -price and https://support.google.com/adxbuyer/answer/3221407?hl=en have
 * more details about the encrypted format of hyperlocal, winning price,
 * IDFA, hashed IDFA and Android Advertiser ID.
 */
public static byte[] decrypt(byte[] ciphertext, SecretKey encryptionKey, SecretKey integrityKey)
        throws DecrypterException {
    try {
        // Step 1. find the length of initialization vector and clear text.
        final int plaintext_length = ciphertext.length - INITIALIZATION_VECTOR_SIZE - SIGNATURE_SIZE;
        if (plaintext_length < 0) {
            throw new RuntimeException("The plain text length can't be negative.");
        }
        System.out.println(Arrays.toString(ciphertext));
        System.out.println(byte2hex(ciphertext));
        System.out.println(ciphertext.length);
        System.out.println(plaintext_length);

        byte[] iv = Arrays.copyOf(ciphertext, INITIALIZATION_VECTOR_SIZE);

        // Step 2. recover clear text
        final Mac hmacer = Mac.getInstance("HmacSHA1");
        hmacer.init(encryptionKey);

        final int ciphertext_end = INITIALIZATION_VECTOR_SIZE + plaintext_length;
        final byte[] plaintext = new byte[plaintext_length];
        boolean add_iv_counter_byte = true;
        for (int ciphertext_begin = INITIALIZATION_VECTOR_SIZE, plaintext_begin = 0; ciphertext_begin < ciphertext_end;) {
            System.out.println("=====> FOR:");
            hmacer.reset();
            hmacer.init(encryptionKey);
            System.out.println("iv: " + byte2hex(iv));
            final byte[] pad = hmacer.doFinal(iv);
            System.out.println("pad: " + byte2hex(pad) + "  len(pad): " + pad.length);
            Base64 encoder = new Base64();
            String pad_base64 = new String(encoder.encode(pad));
            System.out.println("pad Base64: " + pad_base64);

            int i = 0;
            while (i < BLOCK_SIZE && ciphertext_begin != ciphertext_end) {
                plaintext[plaintext_begin++] = (byte) (ciphertext[ciphertext_begin++] ^ pad[i++]);
            }

            if (!add_iv_counter_byte) {
                final int index = iv.length - 1;
                add_iv_counter_byte = ++iv[index] == 0;
            }

            if (add_iv_counter_byte) {
                add_iv_counter_byte = false;
                iv = Arrays.copyOf(iv, iv.length + 1);
            }
        }
        System.out.println("plaintext: " + byte2hex(plaintext));

        // Step 3. Compute integrity hash. The input to the HMAC is
        // clear_text
        // followed by initialization vector, which is stored in the 1st
        // section
        // or ciphertext.
        hmacer.reset();
        hmacer.init(integrityKey);
        hmacer.update(plaintext);
        hmacer.update(Arrays.copyOf(ciphertext, INITIALIZATION_VECTOR_SIZE));
        final byte[] computedSignature = Arrays.copyOf(hmacer.doFinal(), SIGNATURE_SIZE);
        final byte[] signature = Arrays.copyOfRange(ciphertext, ciphertext_end,
                ciphertext_end + SIGNATURE_SIZE);
        if (!Arrays.equals(signature, computedSignature)) {
            throw new DecrypterException("Signature mismatch.");
        }
        return plaintext;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("HmacSHA1 not supported.", e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Key is invalid for this purpose.", e);
    }
}

From source file:org.ejbca.core.protocol.cmp.CmpMessageHelper.java

public static byte[] protectPKIMessageWithPBE(PKIMessage msg, String keyId, String raSecret, String digestAlgId,
        String macAlgId, int iterationCount)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">protectPKIMessageWithPBE()");
    }//from   w w  w  .  j ava 2  s .  c o m
    // Create the PasswordBased protection of the message
    PKIHeaderBuilder head = getHeaderBuilder(msg.getHeader());
    byte[] keyIdBytes;
    try {
        keyIdBytes = keyId.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        keyIdBytes = keyId.getBytes();
        LOG.info("UTF-8 not available, using platform default encoding for keyIdBytes.");
    }
    head.setSenderKID(new DEROctetString(keyIdBytes));
    // SHA1
    AlgorithmIdentifier owfAlg = new AlgorithmIdentifier(digestAlgId);
    // iterations, usually something like 1024
    ASN1Integer iteration = new ASN1Integer(iterationCount);
    // HMAC/SHA1
    AlgorithmIdentifier macAlg = new AlgorithmIdentifier(macAlgId);
    // We need some random bytes for the nonce
    byte[] saltbytes = createSenderNonce();
    DEROctetString derSalt = new DEROctetString(saltbytes);

    // Create the new protected return message
    //String objectId = "1.2.840.113533.7.66.13" = passwordBasedMac;
    String objectId = CMPObjectIdentifiers.passwordBasedMac.getId();
    PBMParameter pp = new PBMParameter(derSalt, owfAlg, iteration, macAlg);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier(objectId), pp);
    head.setProtectionAlg(pAlg);

    // Calculate the protection bits
    byte[] rasecret = raSecret.getBytes();
    byte[] basekey = new byte[rasecret.length + saltbytes.length];
    System.arraycopy(rasecret, 0, basekey, 0, rasecret.length);
    System.arraycopy(saltbytes, 0, basekey, rasecret.length, saltbytes.length);
    // Construct the base key according to rfc4210, section 5.1.3.1
    MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), "BC");
    for (int i = 0; i < iterationCount; i++) {
        basekey = dig.digest(basekey);
        dig.reset();
    }

    PKIHeader pkiHeader = head.build();
    // Do the mac
    String macOid = macAlg.getAlgorithm().getId();
    byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(pkiHeader, msg.getBody()); //ret.getProtectedBytes();
    Mac mac = Mac.getInstance(macOid, "BC");
    SecretKey key = new SecretKeySpec(basekey, macOid);
    mac.init(key);
    mac.reset();
    mac.update(protectedBytes, 0, protectedBytes.length);
    byte[] out = mac.doFinal();
    DERBitString bs = new DERBitString(out);

    if (LOG.isTraceEnabled()) {
        LOG.trace("<protectPKIMessageWithPBE()");
    }
    // Return response as byte array 
    return CmpMessageHelper
            .pkiMessageToByteArray(new PKIMessage(pkiHeader, msg.getBody(), bs, msg.getExtraCerts()));
}

From source file:org.ejbca.core.protocol.cmp.CmpPbeVerifyer.java

public boolean verify(String raAuthenticationSecret)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    lastUsedRaSecret = raAuthenticationSecret;
    boolean ret = false;
    // Verify the PasswordBased protection of the message
    if (!pAlg.getAlgorithm().equals(CMPObjectIdentifiers.passwordBasedMac)) {
        errMsg = INTRES.getLocalizedMessage("cmp.errorunknownprotalg", pAlg.getAlgorithm().getId());
        LOG.error(errMsg);//from   w  w  w.j a v  a 2  s  .c  om
        return ret;
    } else {
        if (iterationCount > 10000) {
            LOG.info("Received message with too many iterations in PBE protection: " + iterationCount);
            throw new InvalidKeyException("Iteration count can not exceed 10000");
        }
        byte[] raSecret = raAuthenticationSecret.getBytes();
        byte[] basekey = new byte[raSecret.length + salt.length];
        System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
        System.arraycopy(salt, 0, basekey, raSecret.length, salt.length);
        // Construct the base key according to rfc4210, section 5.1.3.1
        MessageDigest dig = MessageDigest.getInstance(owfOid, "BC");
        for (int i = 0; i < iterationCount; i++) {
            basekey = dig.digest(basekey);
            dig.reset();
        }
        // HMAC/SHA1 is normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7 
        Mac mac = Mac.getInstance(macOid, "BC");
        SecretKey key = new SecretKeySpec(basekey, macOid);
        mac.init(key);
        mac.reset();
        mac.update(protectedBytes, 0, protectedBytes.length);
        byte[] out = mac.doFinal();
        // My out should now be the same as the protection bits
        byte[] pb = protection.getBytes();
        ret = Arrays.equals(out, pb);
    }
    return ret;
}

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

protected static PKIMessage protectPKIMessage(PKIMessage msg, boolean badObjectId, String password,
        String keyId, int iterations)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    // Create the PasswordBased protection of the message
    PKIHeaderBuilder head = CmpMessageHelper.getHeaderBuilder(msg.getHeader());
    if (keyId != null) {
        head.setSenderKID(new DEROctetString(keyId.getBytes()));
    }//from   w  w w . j av  a  2 s .c  o m
    // SHA1
    AlgorithmIdentifier owfAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26"));
    // 567 iterations
    int iterationCount = iterations;
    ASN1Integer iteration = new ASN1Integer(iterationCount);
    // HMAC/SHA1
    AlgorithmIdentifier macAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.2.840.113549.2.7"));
    byte[] salt = "foo123".getBytes();
    DEROctetString derSalt = new DEROctetString(salt);

    // Create the new protected return message
    String objectId = "1.2.840.113533.7.66.13";
    if (badObjectId) {
        objectId += ".7";
    }
    PBMParameter pp = new PBMParameter(derSalt, owfAlg, iteration, macAlg);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier(objectId), pp);
    head.setProtectionAlg(pAlg);
    PKIHeader header = head.build();
    // Calculate the protection bits
    byte[] raSecret = password.getBytes();
    byte[] basekey = new byte[raSecret.length + salt.length];
    System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
    for (int i = 0; i < salt.length; i++) {
        basekey[raSecret.length + i] = salt[i];
    }
    // Construct the base key according to rfc4210, section 5.1.3.1
    MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), "BC");
    for (int i = 0; i < iterationCount; i++) {
        basekey = dig.digest(basekey);
        dig.reset();
    }
    // For HMAC/SHA1 there is another oid, that is not known in BC, but the
    // result is the same so...
    String macOid = macAlg.getAlgorithm().getId();
    PKIBody body = msg.getBody();
    byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(header, body);
    Mac mac = Mac.getInstance(macOid, "BC");
    SecretKey key = new SecretKeySpec(basekey, macOid);
    mac.init(key);
    mac.reset();
    mac.update(protectedBytes, 0, protectedBytes.length);
    byte[] out = mac.doFinal();
    DERBitString bs = new DERBitString(out);

    return new PKIMessage(header, body, bs);
}

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

protected static void checkCmpResponseGeneral(byte[] retMsg, String issuerDN, X500Name userDN,
        Certificate cacert, byte[] senderNonce, byte[] transId, boolean signed, String pbeSecret,
        String expectedSignAlg)/* www.  ja  v a2  s .  c  o  m*/
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    assertNotNull("No response from server.", retMsg);
    assertTrue("Response was of 0 length.", retMsg.length > 0);
    boolean pbe = (pbeSecret != null);
    //
    // Parse response message
    //
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg));
    PKIMessage respObject = null;
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    // The signer, i.e. the CA, check it's the right CA
    PKIHeader header = respObject.getHeader();

    // Check that the message is signed with the correct digest alg
    if (StringUtils.isEmpty(expectedSignAlg)) {
        expectedSignAlg = PKCSObjectIdentifiers.sha1WithRSAEncryption.getId();
    }
    // if cacert is ECDSA we should expect an ECDSA signature alg
    //if (AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECDSA")) {
    //    expectedSignAlg = X9ObjectIdentifiers.ecdsa_with_SHA1.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECGOST3410")) {
    //    expectedSignAlg = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("DSTU4145")) {
    //    expectedSignAlg = (new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145())).getId();
    //}
    if (signed) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a signed response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals(expectedSignAlg, algId.getAlgorithm().getId());
    }
    if (pbe) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a pbe protected response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals("Protection algorithm id: " + algId.getAlgorithm().getId(),
                CMPObjectIdentifiers.passwordBasedMac.getId(), algId.getAlgorithm().getId()); // 1.2.840.113549.1.1.5 - SHA-1 with RSA Encryption
    }

    // Check that the signer is the expected CA    
    assertEquals(header.getSender().getTagNo(), 4);

    X500Name expissuer = new X500Name(issuerDN);
    X500Name actissuer = new X500Name(header.getSender().getName().toString());
    assertEquals(expissuer, actissuer);
    if (signed) {
        // Verify the signature
        byte[] protBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString bs = respObject.getProtection();
        Signature sig;
        try {
            sig = Signature.getInstance(expectedSignAlg, "BC");
            sig.initVerify(cacert);
            sig.update(protBytes);
            boolean ret = sig.verify(bs.getBytes());
            assertTrue(ret);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (SignatureException e) {
            e.printStackTrace();
            assertTrue(false);
        }
    }
    if (pbe) {
        ASN1OctetString os = header.getSenderKID();
        assertNotNull(os);
        String keyId = CmpMessageHelper.getStringFromOctets(os);
        log.debug("Found a sender keyId: " + keyId);
        // Verify the PasswordBased protection of the message
        byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString protection = respObject.getProtection();
        AlgorithmIdentifier pAlg = header.getProtectionAlg();
        log.debug("Protection type is: " + pAlg.getAlgorithm().getId());
        PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters());
        int iterationCount = pp.getIterationCount().getPositiveValue().intValue();
        log.debug("Iteration count is: " + iterationCount);
        AlgorithmIdentifier owfAlg = pp.getOwf();
        // Normal OWF alg is 1.3.14.3.2.26 - SHA1
        log.debug("Owf type is: " + owfAlg.getAlgorithm().getId());
        AlgorithmIdentifier macAlg = pp.getMac();
        // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1
        log.debug("Mac type is: " + macAlg.getAlgorithm().getId());
        byte[] salt = pp.getSalt().getOctets();
        // log.info("Salt is: "+new String(salt));
        byte[] raSecret = pbeSecret != null ? pbeSecret.getBytes() : new byte[0];
        byte[] basekey = new byte[raSecret.length + salt.length];
        System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
        for (int i = 0; i < salt.length; i++) {
            basekey[raSecret.length + i] = salt[i];
        }
        // Construct the base key according to rfc4210, section 5.1.3.1
        MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(),
                BouncyCastleProvider.PROVIDER_NAME);
        for (int i = 0; i < iterationCount; i++) {
            basekey = dig.digest(basekey);
            dig.reset();
        }
        // HMAC/SHA1 os normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7
        String macOid = macAlg.getAlgorithm().getId();
        Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME);
        SecretKey key = new SecretKeySpec(basekey, macOid);
        mac.init(key);
        mac.reset();
        mac.update(protectedBytes, 0, protectedBytes.length);
        byte[] out = mac.doFinal();
        // My out should now be the same as the protection bits
        byte[] pb = protection.getBytes();
        boolean ret = Arrays.equals(out, pb);
        assertTrue(ret);
    }

    // --SenderNonce
    // SenderNonce is something the server came up with, but it should be 16
    // chars
    byte[] nonce = header.getSenderNonce().getOctets();
    assertEquals(nonce.length, 16);

    // --Recipient Nonce
    // recipient nonce should be the same as we sent away as sender nonce
    nonce = header.getRecipNonce().getOctets();
    assertEquals(new String(nonce), new String(senderNonce));

    // --Transaction ID
    // transid should be the same as the one we sent
    nonce = header.getTransactionID().getOctets();
    assertEquals(new String(nonce), new String(transId));

}

From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java

private PKIMessage protectPKIMessageWithHMAC(PKIMessage msg, boolean badObjectId, String password,
        int iterations) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    // Create the PasswordBased protection of the message
    PKIHeaderBuilder head = getHeaderBuilder(msg.getHeader());
    // SHA1// w w  w  .  ja  va2s . co  m
    AlgorithmIdentifier owfAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26"));
    // 567 iterations
    int iterationCount = iterations;
    ASN1Integer iteration = new ASN1Integer(iterationCount);
    // HMAC/SHA1
    AlgorithmIdentifier macAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.2.840.113549.2.7"));
    byte[] salt = "foo123".getBytes();
    DEROctetString derSalt = new DEROctetString(salt);

    // Create the new protected return message
    String objectId = "1.2.840.113533.7.66.13";
    if (badObjectId) {
        objectId += ".7";
    }
    PBMParameter pp = new PBMParameter(derSalt, owfAlg, iteration, macAlg);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier(objectId), pp);
    head.setProtectionAlg(pAlg);
    PKIHeader header = head.build();
    // Calculate the protection bits
    byte[] raSecret = password.getBytes();
    byte[] basekey = new byte[raSecret.length + salt.length];
    System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
    for (int i = 0; i < salt.length; i++) {
        basekey[raSecret.length + i] = salt[i];
    }
    // Construct the base key according to rfc4210, section 5.1.3.1
    MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), "BC");
    for (int i = 0; i < iterationCount; i++) {
        basekey = dig.digest(basekey);
        dig.reset();
    }
    // For HMAC/SHA1 there is another oid, that is not known in BC, but the
    // result is the same so...
    String macOid = macAlg.getAlgorithm().getId();
    PKIBody body = msg.getBody();
    byte[] protectedBytes = getProtectedBytes(header, body);
    Mac mac = Mac.getInstance(macOid, "BC");
    SecretKey key = new SecretKeySpec(basekey, macOid);
    mac.init(key);
    mac.reset();
    mac.update(protectedBytes, 0, protectedBytes.length);
    byte[] out = mac.doFinal();
    DERBitString bs = new DERBitString(out);

    return new PKIMessage(header, body, bs);
}

From source file:org.glite.slcs.caclient.impl.CMPRequest.java

private static byte[] makeProtection(String secret, int iterCount, String owfAlgId, String macAlgId,
        DEROctetString salt, PKIMessage message) {
    byte[] saltBytes = salt.getOctets();
    byte[] sharedSecret = secret.getBytes();
    byte[] firstKey = new byte[sharedSecret.length + saltBytes.length];
    for (int i = 0; i < sharedSecret.length; i++) {
        firstKey[i] = sharedSecret[i];// www  .ja  v a  2 s . com
    }
    for (int i = 0; i < saltBytes.length; i++) {
        firstKey[sharedSecret.length + i] = saltBytes[i];
    }
    // Construct the base key according to rfc4210, section 5.1.3.1
    MessageDigest dig = null;
    Mac mac = null;
    try {
        dig = MessageDigest.getInstance(owfAlgId, "BC");
        for (int i = 0; i < iterCount; i++) {
            firstKey = dig.digest(firstKey);
            dig.reset();
        }
        mac = Mac.getInstance(macAlgId, "BC");
        SecretKey key = new SecretKeySpec(firstKey, macAlgId);
        mac.init(key);
    } catch (Exception e) {
        log.error("Error while calculating PKIMessage protection", e);
    }
    mac.reset();
    byte[] protectedBytes = message.getProtectedBytes();
    mac.update(protectedBytes, 0, protectedBytes.length);
    return mac.doFinal();
}