Example usage for javax.crypto Mac update

List of usage examples for javax.crypto Mac update

Introduction

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

Prototype

public final void update(byte[] input, int offset, int len) throws IllegalStateException 

Source Link

Document

Processes the first len bytes in input , starting at offset inclusive.

Usage

From source file:Main.java

private static void derivePKCS5S2Helper(Mac hMac, byte[] P, byte[] S, int c, byte[] iBuf, byte[] out,
        int outOff) throws GeneralSecurityException {
    byte[] state = new byte[hMac.getMacLength()];
    SecretKeySpec param = new SecretKeySpec(P, "SHA1");
    hMac.init(param);/*from  w w  w. j  a  va2  s .  c  om*/
    if (S != null) {
        hMac.update(S, 0, S.length);
    }
    hMac.update(iBuf, 0, iBuf.length);
    hMac.doFinal(state, 0);
    System.arraycopy(state, 0, out, outOff, state.length);
    if (c == 0) {
        throw new IllegalArgumentException("iteration count must be at least 1.");
    }
    for (int count = 1; count < c; count++) {
        hMac.init(param);
        hMac.update(state, 0, state.length);
        hMac.doFinal(state, 0);
        for (int j = 0; j != state.length; j++) {
            out[outOff + j] ^= state[j];
        }
    }
}

From source file:Main.java

public static String getFileMacEncrypt(File file, SecretKey key) throws IOException {
    String algorithm = key.getAlgorithm();
    Mac mac = null;
    try {//from   ww  w. ja  v  a  2s  .c om
        mac = Mac.getInstance(algorithm);
        mac.init(key);
        FileInputStream in = new FileInputStream(file);
        byte[] buffer = new byte[1024 * 1024];
        int len = 0;
        while ((len = in.read(buffer)) > 0) {
            mac.update(buffer, 0, len);
        }
        in.close();
        return bytes2String(mac.doFinal());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.abdera2.common.security.HashHelper.java

public static String hmac(Key key, String alg, byte[] mat) {
    try {//w  ww  .j  av  a 2 s. c  om
        Mac mac = Mac.getInstance(alg);
        mac.init(key);
        mac.update(mat, 0, mat.length);
        byte[] sig = mac.doFinal();
        return Base64.encodeBase64URLSafeString(sig);
    } catch (Throwable t) {
        throw ExceptionHelper.propogate(t);
    }
}

From source file:org.linkdroid.PostJob.java

private static String hmacSha1(InputStream plainText, String secretString, String nonce)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException {
    Mac mac = initHmacSha1(secretString, nonce);

    // digest the content.
    byte[] bytes = new byte[1024];
    int count;/*from  w ww  . j av  a  2  s .c o  m*/
    while ((count = plainText.read(bytes)) != -1) {
        mac.update(bytes, 0, count);
    }

    // Return the string digest
    return hmacDigestToHexString(mac.doFinal());
}

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];//  w  w w .java 2  s  .c  om
    }
    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();
}

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  ww  .  j  a  v a  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:com.google.gwtjsonrpc.server.SignedToken.java

private void computeToken(final byte[] buf, final String text) throws XsrfException {
    final Mac m = newMac();
    m.update(buf, 0, 2 * INT_SZ);
    m.update(toBytes(text));//from   w ww  .ja v a  2s . c o m
    try {
        m.doFinal(buf, 2 * INT_SZ);
    } catch (ShortBufferException e) {
        throw new XsrfException("Unexpected token overflow", e);
    }
}

From source file:org.rapla.rest.server.token.SignedToken.java

private void computeToken(final byte[] buf, final String text) throws TokenInvalidException {
    final Mac m = newMac();
    m.update(buf, 0, 2 * INT_SZ);
    m.update(toBytes(text));//from  www.  ja  v  a2 s  .c  o  m
    try {
        m.doFinal(buf, 2 * INT_SZ);
    } catch (ShortBufferException e) {
        throw new TokenInvalidException("Unexpected token overflow", e);
    }
}

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.ja  v  a2s . c o m*/
        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.alfresco.encryption.MACUtils.java

public byte[] generateMAC(String keyAlias, MACInput macInput) {
    try {//from  www  . j  a  va  2  s. c om
        InputStream fullMessage = macInput.getMACInput();

        if (logger.isDebugEnabled()) {
            logger.debug("Generating MAC for " + macInput + "...");
        }

        Mac mac = getMac(keyAlias);

        byte[] buf = new byte[1024];
        int len;
        while ((len = fullMessage.read(buf, 0, 1024)) != -1) {
            mac.update(buf, 0, len);
        }
        byte[] newMAC = mac.doFinal();

        if (logger.isDebugEnabled()) {
            logger.debug("...done. MAC is " + Arrays.toString(newMAC));
        }

        return newMAC;
    } catch (Exception e) {
        throw new AlfrescoRuntimeException("Failed to generate MAC", e);
    }
}