Example usage for org.bouncycastle.crypto.macs CMac CMac

List of usage examples for org.bouncycastle.crypto.macs CMac CMac

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.macs CMac CMac.

Prototype

public CMac(BlockCipher cipher) 

Source Link

Document

create a standard MAC based on a CBC block cipher (64 or 128 bit block).

Usage

From source file:com.netflix.msl.crypto.SymmetricCryptoContext.java

License:Open Source License

@Override
public byte[] sign(final byte[] data) throws MslCryptoException {
    if (signatureKey == null)
        throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED, "No signature key.");
    try {/*from   w  w  w. j  ava 2 s.  co m*/
        // Compute the xMac.
        final byte[] xmac;
        if (signatureKey.getAlgorithm().equals(JcaAlgorithm.HMAC_SHA256)) {
            final Mac mac = CryptoCache.getMac(HMAC_SHA256_ALGO);
            mac.init(signatureKey);
            xmac = mac.doFinal(data);
        } else if (signatureKey.getAlgorithm().equals(JcaAlgorithm.AES_CMAC)) {
            final CipherParameters params = new KeyParameter(signatureKey.getEncoded());
            final BlockCipher aes = new AESEngine();
            final CMac mac = new CMac(aes);
            mac.init(params);
            mac.update(data, 0, data.length);
            xmac = new byte[mac.getMacSize()];
            mac.doFinal(xmac, 0);
        } else {
            throw new MslCryptoException(MslError.SIGN_NOT_SUPPORTED, "Unsupported algorithm.");
        }

        // Return the signature envelope byte representation.
        return new MslSignatureEnvelope(xmac).getBytes();
    } catch (final NoSuchAlgorithmException e) {
        throw new MslInternalException("Invalid MAC algorithm specified.", e);
    } catch (final InvalidKeyException e) {
        throw new MslCryptoException(MslError.INVALID_HMAC_KEY, e);
    }
}

From source file:com.netflix.msl.crypto.SymmetricCryptoContext.java

License:Open Source License

@Override
public boolean verify(final byte[] data, final byte[] signature) throws MslCryptoException {
    if (signatureKey == null)
        throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED, "No signature key.");
    try {/*from   w w  w. java 2 s . c  o m*/
        // Reconstitute the signature envelope.
        final MslSignatureEnvelope envelope = MslSignatureEnvelope.parse(signature);

        // Compute the xMac.
        final byte[] xmac;
        if (signatureKey.getAlgorithm().equals(JcaAlgorithm.HMAC_SHA256)) {
            final Mac mac = CryptoCache.getMac(HMAC_SHA256_ALGO);
            mac.init(signatureKey);
            xmac = mac.doFinal(data);
        } else if (signatureKey.getAlgorithm().equals(JcaAlgorithm.AES_CMAC)) {
            final CipherParameters params = new KeyParameter(signatureKey.getEncoded());
            final BlockCipher aes = new AESEngine();
            final CMac mac = new CMac(aes);
            mac.init(params);
            mac.update(data, 0, data.length);
            xmac = new byte[mac.getMacSize()];
            mac.doFinal(xmac, 0);
        } else {
            throw new MslCryptoException(MslError.VERIFY_NOT_SUPPORTED, "Unsupported algorithm.");
        }

        // Compare the computed hash to the provided signature.
        return MslUtils.safeEquals(xmac, envelope.getSignature());
    } catch (final MslEncodingException e) {
        throw new MslCryptoException(MslError.SIGNATURE_ENVELOPE_PARSE_ERROR, e);
    } catch (final NoSuchAlgorithmException e) {
        throw new MslInternalException("Invalid MAC algorithm specified.", e);
    } catch (final InvalidKeyException e) {
        throw new MslCryptoException(MslError.INVALID_HMAC_KEY, e);
    }
}

From source file:com.pearson.pdn.learningstudio.helloworld.OAuth1SignatureServlet.java

License:Apache License

private String generateCmac(String key, String msg) throws UnsupportedEncodingException {
    byte[] keyBytes = key.getBytes("UTF-8");
    byte[] data = msg.getBytes("UTF-8");

    CMac macProvider = new CMac(new AESFastEngine());
    macProvider.init(new KeyParameter(keyBytes));
    macProvider.reset();/*w  w w  .j a v  a 2s.  c o m*/

    macProvider.update(data, 0, data.length);
    byte[] output = new byte[macProvider.getMacSize()];
    macProvider.doFinal(output, 0);

    // Convert the CMAC to a Base64 string and remove the new line the
    // Base64 library adds
    String cmac = Base64.encodeBase64String(output).replaceAll("\r\n", "");

    return cmac;
}

From source file:com.pearson.pdn.learningstudio.helloworld.OAuth2AssertionServlet.java

License:Apache License

private String generateCmac(String key, String msg) throws UnsupportedEncodingException {
    byte[] keyBytes = key.getBytes("UTF-8");
    byte[] data = msg.getBytes("UTF-8");

    CMac macProvider = new CMac(new AESFastEngine());
    macProvider.init(new KeyParameter(keyBytes));
    macProvider.reset();/*from   w  w  w . j a va  2s  .co m*/

    macProvider.update(data, 0, data.length);
    byte[] output = new byte[macProvider.getMacSize()];
    macProvider.doFinal(output, 0);

    return Strings.fromUTF8ByteArray(Hex.encode(output));
}

From source file:com.pearson.pdn.learningstudio.oauth.OAuth1SignatureService.java

License:Apache License

/**
 * Generates a Base64-encoded CMAC-AES digest
 * /*from ww w  .j a va2  s .  c o  m*/
 * @param key
 *            The secret key used to sign the data
 * @param msg
 *            The data to be signed
 * 
 * @return A CMAC-AES hash
 * 
 * @throws UnsupportedEncodingException
 */
private String generateCmac(String key, String msg) throws UnsupportedEncodingException {
    byte[] keyBytes = key.getBytes("UTF-8");
    byte[] data = msg.getBytes("UTF-8");

    CMac macProvider = new CMac(new AESFastEngine());
    macProvider.init(new KeyParameter(keyBytes));
    macProvider.reset();

    macProvider.update(data, 0, data.length);
    byte[] output = new byte[macProvider.getMacSize()];
    macProvider.doFinal(output, 0);

    // Convert the CMAC to a Base64 string and remove the new line the
    // Base64 library adds
    String cmac = Base64.encodeBase64String(output).replaceAll("\r\n", "");

    return cmac;
}

From source file:com.pearson.pdn.learningstudio.oauth.OAuth2AssertionService.java

License:Apache License

/**
 * Generates a HEX-encoded CMAC-AES digest
 * //w w  w. j a  va  2 s.  c om
 * @param key
 *            The secret key used to sign the data
 * @param msg
 *            The data to be signed
 * 
 * @return A CMAC-AES digest
 * 
 * @throws UnsupportedEncodingException
 */
private String generateCmac(String key, String msg) throws UnsupportedEncodingException {
    byte[] keyBytes = key.getBytes("UTF-8");
    byte[] data = msg.getBytes("UTF-8");

    CMac macProvider = new CMac(new AESFastEngine());
    macProvider.init(new KeyParameter(keyBytes));
    macProvider.reset();

    macProvider.update(data, 0, data.length);
    byte[] output = new byte[macProvider.getMacSize()];
    macProvider.doFinal(output, 0);

    return Strings.fromUTF8ByteArray(Hex.encode(output));
}

From source file:io.warp10.script.lora.LORAMIC.java

License:Apache License

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {

    Object top = stack.pop();/* ww w . ja  v a2s. co  m*/

    if (!(top instanceof String)) {
        throw new WarpScriptException(getName() + " expects a 128 bits hex encoded key on top of the stack.");
    }

    String keystr = top.toString();

    if (keystr.length() != 32) {
        throw new WarpScriptException(getName() + " expects a 128 bits hex encoded key on top of the stack.");
    }

    top = stack.pop();

    if (!(top instanceof Long)) {
        throw new WarpScriptException(getName() + " expects a sequence counter below the key.");
    }

    int sequenceCounter = ((Number) top).intValue();

    top = stack.pop();

    if (!(top instanceof Long)) {
        throw new WarpScriptException(
                getName() + " expects a direction (0 uplink or 1 downlink) below the sequence counter.");
    }

    int dir = ((Number) top).intValue();

    if (0 != dir && 1 != dir) {
        throw new WarpScriptException(
                getName() + " expects a direction (0 uplink or 1 downlink) below the sequence counter.");
    }

    top = stack.pop();

    if (!(top instanceof Long)) {
        throw new WarpScriptException(getName() + " expects a device address below the direction.");
    }

    int addr = ((Number) top).intValue();

    String datastr = stack.pop().toString();

    if (0 != datastr.length() % 2) {
        throw new WarpScriptException(
                getName() + " expects a hex encoded data frame with an even length of hex digits.");
    }

    byte[] data = Hex.decode(datastr);

    //
    // Compute MIC block B0
    //

    byte[] MicBlockB0 = new byte[16];

    MicBlockB0[0] = 0x49;
    MicBlockB0[5] = (byte) (dir & 0x1);
    MicBlockB0[6] = (byte) (addr & 0xFF);
    MicBlockB0[7] = (byte) ((addr >> 8) & 0xFF);
    MicBlockB0[8] = (byte) ((addr >> 16) & 0xFF);
    MicBlockB0[9] = (byte) ((addr >> 24) & 0xFF);

    MicBlockB0[10] = (byte) ((sequenceCounter) & 0xFF);
    MicBlockB0[11] = (byte) ((sequenceCounter >> 8) & 0xFF);
    MicBlockB0[12] = (byte) ((sequenceCounter >> 16) & 0xFF);
    MicBlockB0[13] = (byte) ((sequenceCounter >> 24) & 0xFF);

    MicBlockB0[15] = (byte) (data.length & 0xFF);

    AESEngine aes = new AESEngine();
    CMac cmac = new CMac(aes);
    KeyParameter key = new KeyParameter(Hex.decode(keystr));
    cmac.init(key);
    cmac.update(MicBlockB0, 0, MicBlockB0.length);
    cmac.update(data, 0, data.length & 0xFF);

    byte[] mac = new byte[cmac.getMacSize()];
    cmac.doFinal(mac, 0);

    //    byte[] mic = new byte[4];
    //    mic[0] = mac[3];
    //    mic[1] = mac[2];
    //    mic[2] = mac[1];
    //    mic[3] = mac[0];

    stack.push(new String(Hex.encode(mac, 0, 4), Charsets.US_ASCII));

    return stack;
}

From source file:org.crypto.sse.CryptoPrimitives.java

License:Open Source License

public static byte[] generateCmac(byte[] key, String msg) throws UnsupportedEncodingException {
    CMac cmac = new CMac(new AESFastEngine());
    byte[] data = msg.getBytes("UTF-8");
    byte[] output = new byte[cmac.getMacSize()];

    cmac.init(new KeyParameter(key));
    cmac.reset();/*from   ww  w. j av  a  2 s. c om*/
    cmac.update(data, 0, data.length);
    cmac.doFinal(output, 0);
    return output;
}

From source file:org.cryptomator.crypto.aes256.AesSivCipherUtil.java

License:Open Source License

static byte[] s2v(byte[] macKey, byte[] plaintext, byte[]... additionalData) {
    final CipherParameters params = new KeyParameter(macKey);
    final BlockCipher aes = new AESFastEngine();
    final CMac mac = new CMac(aes);
    mac.init(params);/*from w  ww .  j a v a2s . c o  m*/

    byte[] d = mac(mac, BYTES_ZERO);

    for (byte[] s : additionalData) {
        d = xor(dbl(d), mac(mac, s));
    }

    final byte[] t;
    if (plaintext.length >= 16) {
        t = xorend(plaintext, d);
    } else {
        t = xor(dbl(d), pad(plaintext));
    }

    return mac(mac, t);
}

From source file:org.cryptomator.siv.SivMode.java

License:Open Source License

byte[] s2v(byte[] macKey, byte[] plaintext, byte[]... associatedData) {
    // Maximum permitted AD length is the block size in bits - 2
    if (associatedData.length > 126) {
        // SIV mode cannot be used safely with this many AD fields
        throw new IllegalArgumentException("too many Associated Data fields");
    }//  w  ww . j  av  a  2s .  co m

    final CipherParameters params = new KeyParameter(macKey);
    final CMac mac = new CMac(threadLocalCipher.get());
    mac.init(params);

    byte[] d = mac(mac, BYTES_ZERO);

    for (byte[] s : associatedData) {
        d = xor(dbl(d), mac(mac, s));
    }

    final byte[] t;
    if (plaintext.length >= 16) {
        t = xorend(plaintext, d);
    } else {
        t = xor(dbl(d), pad(plaintext));
    }

    return mac(mac, t);
}