Example usage for org.bouncycastle.crypto Mac update

List of usage examples for org.bouncycastle.crypto Mac update

Introduction

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

Prototype

public void update(byte[] in, int inOff, int len) throws DataLengthException, IllegalStateException;

Source Link

Usage

From source file:com.github.capone.protocol.crypto.SymmetricKey.java

License:Open Source License

public byte[] encrypt(Nonce nonce, byte[] message) throws EncryptionException {
    try {//from w w  w.ja  v  a2 s  .co m
        byte[] subkey = new byte[SUBKEYBYTES];
        byte[] encrypted = new byte[message.length + MACBYTES];

        StreamCipher cipher = new XSalsa20Engine();
        cipher.init(true, new ParametersWithIV(key, nonce.nonce));
        cipher.processBytes(subkey, 0, subkey.length, subkey, 0);
        cipher.processBytes(message, 0, message.length, encrypted, MACBYTES);

        Mac auth = new Poly1305();
        auth.init(new KeyParameter(subkey));
        auth.update(encrypted, MACBYTES, message.length);
        auth.doFinal(encrypted, 0);

        return encrypted;
    } catch (Exception e) {
        throw new EncryptionException();
    }
}

From source file:com.github.capone.protocol.crypto.SymmetricKey.java

License:Open Source License

public byte[] decrypt(Nonce nonce, byte[] encrypted) throws DecryptionException {
    byte[] subkey = new byte[SUBKEYBYTES];
    byte[] mac = new byte[MACBYTES];
    byte[] plain = new byte[encrypted.length - MACBYTES];

    if (encrypted.length < MACBYTES) {
        throw new DecryptionException();
    }/*from w  ww  .  j  a  va  2 s  .  com*/

    StreamCipher cipher = new XSalsa20Engine();
    cipher.init(true, new ParametersWithIV(key, nonce.nonce));
    cipher.processBytes(subkey, 0, subkey.length, subkey, 0);

    Mac auth = new Poly1305();
    auth.init(new KeyParameter(subkey));
    auth.update(encrypted, MACBYTES, encrypted.length - MACBYTES);
    auth.doFinal(mac, 0);

    boolean validMac = true;
    for (int i = 0; i < MACBYTES; i++) {
        validMac &= mac[i] == encrypted[i];
    }
    if (!validMac) {
        throw new DecryptionException();
    }

    cipher.processBytes(encrypted, MACBYTES, encrypted.length - MACBYTES, plain, 0);

    return plain;
}

From source file:com.github.jinahya.rfc5849.OAuthSignatureHmacSha1Bc.java

License:Apache License

@Override
byte[] get(final byte[] keyBytes, final byte[] baseBytes) throws Exception {
    final Mac mac = new HMac(new SHA1Digest());
    mac.init(new KeyParameter(keyBytes));
    mac.update(baseBytes, 0, baseBytes.length);
    final byte[] output = new byte[mac.getMacSize()];
    mac.doFinal(output, 0);//  w w w .  j  a va2  s.  com
    return output;
}

From source file:com.google.authenticator.blackberry.PasscodeGenerator.java

License:Apache License

/**
 * @param mac A {@link Mac} used to generate passcodes
 * @param passCodeLength The length of the decimal passcode
 * @param interval The interval that a passcode is valid for
 *//*from   ww  w .j  a va  2s. co  m*/
public PasscodeGenerator(final Mac mac, int passCodeLength, int interval) {
    this(new Signer() {
        public byte[] sign(byte[] data) {
            mac.reset();
            mac.update(data, 0, data.length);
            int length = mac.getMacSize();
            byte[] out = new byte[length];
            mac.doFinal(out, 0);
            mac.reset();
            return out;
        }
    }, passCodeLength, interval);
}

From source file:de.tsenger.animamea.crypto.AmAESCrypto.java

License:Open Source License

@Override
public byte[] getMAC(byte[] data) {

    byte[] n = new byte[sscBytes.length + data.length];
    System.arraycopy(sscBytes, 0, n, 0, sscBytes.length);
    System.arraycopy(data, 0, n, sscBytes.length, data.length);
    n = addPadding(n);/*from w  w w  . ja v a2s.  co  m*/

    BlockCipher cipher = new AESFastEngine();
    Mac mac = new CMac(cipher, 64);

    mac.init(keyP);
    mac.update(n, 0, n.length);
    byte[] out = new byte[mac.getMacSize()];

    mac.doFinal(out, 0);

    return out;
}

From source file:de.tsenger.animamea.crypto.AmAESCrypto.java

License:Open Source License

@Override
public byte[] getMAC(byte[] key, byte[] data) {
    BlockCipher cipher = new AESFastEngine();
    Mac mac = new CMac(cipher, 64); // TODO Padding der Daten

    KeyParameter keyP = new KeyParameter(key);
    mac.init(keyP);/*w  w w. ja v a 2  s.com*/

    mac.update(data, 0, data.length);

    byte[] out = new byte[8];

    mac.doFinal(out, 0);

    return out;
}

From source file:de.tsenger.animamea.crypto.AmDESCrypto.java

License:Open Source License

@Override
public byte[] getMAC(byte[] data) {

    byte[] n = new byte[8 + data.length];
    System.arraycopy(sscBytes, 0, n, 0, 8);
    System.arraycopy(data, 0, n, 8, data.length);

    BlockCipher cipher = new DESEngine();
    Mac mac = new ISO9797Alg3Mac(cipher, 64, new ISO7816d4Padding());

    ParametersWithIV parameterIV = new ParametersWithIV(keyP, IV);

    mac.init(parameterIV);/*from   www. j av a 2s.  co m*/
    mac.update(n, 0, n.length);

    byte[] out = new byte[8];

    mac.doFinal(out, 0);

    return out;
}

From source file:de.tsenger.animamea.crypto.AmDESCrypto.java

License:Open Source License

@Override
public byte[] getMAC(byte[] key, byte[] data) {
    BlockCipher cipher = new DESEngine();
    Mac mac = new ISO9797Alg3Mac(cipher, 64, new ISO7816d4Padding());

    KeyParameter keyP = new KeyParameter(key);
    mac.init(keyP);//w ww  . j  a  va2 s  .co  m
    mac.update(data, 0, data.length);

    byte[] out = new byte[8];

    mac.doFinal(out, 0);

    return out;
}

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

License:Open Source License

private static byte[] mac(Mac mac, byte[] in) {
    byte[] result = new byte[mac.getMacSize()];
    mac.update(in, 0, in.length);
    mac.doFinal(result, 0);/*from w  ww. j  ava 2 s  . com*/
    return result;
}

From source file:org.jitsi.impl.neomedia.transform.srtp.CryptoBenchmark.java

License:LGPL

public static void main(String[] args) throws Exception {
    boolean benchmarkJavaxCryptoCipher = false;
    boolean benchmarkNIOBlockCipher = false;

    for (String arg : args) {
        if ("-javax-crypto-cipher".equalsIgnoreCase(arg))
            benchmarkJavaxCryptoCipher = true;
        else if ("-nio-block-cipher".equalsIgnoreCase(arg))
            benchmarkNIOBlockCipher = true;
    }/*w  w  w  . j  a  v  a2 s  .  c  om*/

    Provider sunPKCS11 = new sun.security.pkcs11.SunPKCS11(
            "--name=CryptoBenchmark\\n" + "nssDbMode=noDb\\n" + "attributes=compatibility");
    Provider sunJCE = Security.getProvider("SunJCE");

    //        for (Provider provider : new Provider[] { sunPKCS11, sunJCE })
    //            for (Provider.Service service : provider.getServices())
    //                if ("Cipher".equalsIgnoreCase(service.getType()))
    //                    System.err.println(service);

    // org.bouncycastle.crypto.Digest & java.security.MessageDigest
    Digest[] digests = { new SHA1Digest(), new OpenSSLDigest(OpenSSLDigest.SHA1) };
    MessageDigest[] messageDigests = { MessageDigest.getInstance("SHA-1"),
            MessageDigest.getInstance("SHA-1", sunPKCS11) };
    int maxDigestSize = 0;
    int maxByteLength = 0;

    for (Digest digest : digests) {
        int digestSize = digest.getDigestSize();

        if (maxDigestSize < digestSize)
            maxDigestSize = digestSize;

        int byteLength = (digest instanceof ExtendedDigest) ? ((ExtendedDigest) digest).getByteLength() : 64;

        if (maxByteLength < byteLength)
            maxByteLength = byteLength;

        System.err.println(digest.getClass().getName() + ": digestSize " + digestSize + ", byteLength "
                + byteLength + ".");
    }
    for (MessageDigest messageDigest : messageDigests) {
        int digestLength = messageDigest.getDigestLength();

        if (maxDigestSize < digestLength)
            maxDigestSize = digestLength;

        System.err.println(
                messageDigest.getProvider().getClass().getName() + ": digestLength " + digestLength + ".");
    }

    // org.bouncycastle.crypto.BlockCipher
    BlockCipher[] ciphers = { new AESFastEngine(),
            new BlockCipherAdapter(Cipher.getInstance("AES_128/ECB/NoPadding", sunPKCS11)),
            new BlockCipherAdapter(Cipher.getInstance("AES_128/ECB/NoPadding", sunJCE)),
            new OpenSSLBlockCipher(OpenSSLBlockCipher.AES_128_ECB) };

    for (BlockCipher cipher : ciphers) {
        Class<?> clazz;

        if (cipher instanceof BlockCipherAdapter) {
            clazz = ((BlockCipherAdapter) cipher).getCipher().getProvider().getClass();
        } else {
            clazz = cipher.getClass();
        }
        System.err.println(clazz.getName() + ": blockSize " + cipher.getBlockSize());
    }

    // org.bouncycastle.crypto.Mac
    Mac[] macs = { new HMac(new SHA1Digest()), new HMac(new OpenSSLDigest(OpenSSLDigest.SHA1)),
            new OpenSSLHMAC(OpenSSLDigest.SHA1) };

    Random random = new Random(System.currentTimeMillis());
    byte[] in = new byte[1024 * maxByteLength];
    ByteBuffer inNIO = ByteBuffer.allocateDirect(in.length);
    byte[] out = new byte[maxDigestSize];
    ByteBuffer outNIO = ByteBuffer.allocateDirect(out.length);
    long time0 = 0;
    int dMax = Math.max(digests.length, messageDigests.length);
    final int iEnd = 1000, jEnd = 1000;
    //        Base64.Encoder byteEncoder = Base64.getEncoder().withoutPadding();

    inNIO.order(ByteOrder.nativeOrder());
    outNIO.order(ByteOrder.nativeOrder());

    for (int i = 0; i < iEnd; ++i) {
        System.err.println("========================================");

        random.nextBytes(in);
        inNIO.clear();
        inNIO.put(in);

        // org.bouncycastle.crypto.BlockCipher
        time0 = 0;
        for (BlockCipher blockCipher : ciphers) {
            NIOBlockCipher nioBlockCipher = (blockCipher instanceof NIOBlockCipher)
                    ? (NIOBlockCipher) blockCipher
                    : null;
            Cipher cipher;
            Class<?> clazz;

            if (blockCipher instanceof BlockCipherAdapter) {
                cipher = ((BlockCipherAdapter) blockCipher).getCipher();
                clazz = cipher.getProvider().getClass();
            } else {
                cipher = null;
                clazz = blockCipher.getClass();
            }

            int blockSize = blockCipher.getBlockSize();

            blockCipher.init(true, new KeyParameter(in, 0, blockSize));

            long startTime, endTime;
            int offEnd = in.length - blockSize;

            if (nioBlockCipher != null && benchmarkNIOBlockCipher) {
                inNIO.clear();
                outNIO.clear();

                startTime = System.nanoTime();
                for (int j = 0; j < jEnd; ++j) {
                    for (int off = 0; off < offEnd;) {
                        nioBlockCipher.processBlock(inNIO, off, outNIO, 0);
                        off += blockSize;
                    }
                    //                        nioBlockCipher.reset();
                }
                endTime = System.nanoTime();

                outNIO.get(out);
            } else if (cipher != null && benchmarkJavaxCryptoCipher) {
                startTime = System.nanoTime();
                for (int j = 0; j < jEnd; ++j) {
                    for (int off = 0; off < offEnd;) {
                        int nextOff = off + blockSize;

                        inNIO.limit(nextOff);
                        inNIO.position(off);
                        outNIO.clear();
                        cipher.update(inNIO, outNIO);
                        off = nextOff;
                    }
                    //                        cipher.doFinal();
                }
                endTime = System.nanoTime();

                outNIO.clear();
                outNIO.get(out);
            } else {
                startTime = System.nanoTime();
                for (int j = 0; j < jEnd; ++j) {
                    for (int off = 0; off < offEnd;) {
                        blockCipher.processBlock(in, off, out, 0);
                        off += blockSize;
                    }
                    //                        blockCipher.reset();
                }
                endTime = System.nanoTime();
            }

            long time = endTime - startTime;

            if (time0 == 0)
                time0 = time;
            Arrays.fill(out, blockSize, out.length, (byte) 0);
            System.err.println(clazz.getName() + ": ratio " + String.format("%.2f", time / (double) time0)
                    + ", time " + time + ", out "
                    /*+ byteEncoder.encodeToString(out)*/ + ".");
        }

        // org.bouncycastle.crypto.Digest & java.security.MessageDigest
        System.err.println("----------------------------------------");

        time0 = 0;
        for (int d = 0; d < dMax; ++d) {
            Arrays.fill(out, (byte) 0);

            // org.bouncycastle.crypto.Digest
            Digest digest = (d < digests.length) ? digests[d] : null;
            int byteLength = (digest instanceof ExtendedDigest) ? ((ExtendedDigest) digest).getByteLength()
                    : 64;
            long startTime, endTime;
            int offEnd = in.length - byteLength;

            if (digest != null) {
                startTime = System.nanoTime();
                for (int j = 0; j < jEnd; ++j) {
                    for (int off = 0; off < offEnd;) {
                        digest.update(in, off, byteLength);
                        off += byteLength;
                    }
                    digest.doFinal(out, 0);
                }
                endTime = System.nanoTime();

                long time = endTime - startTime;

                if (time0 == 0)
                    time0 = time;
                System.err.println(digest.getClass().getName() + ": ratio "
                        + String.format("%.2f", time / (double) time0) + ", time " + time + ", digest "
                        /*+ byteEncoder.encodeToString(out)*/ + ".");
            }

            // java.security.MessageDigest
            MessageDigest messageDigest = (d < messageDigests.length) ? messageDigests[d] : null;

            if (messageDigest != null) {
                @SuppressWarnings("unused")
                byte[] t = null;

                startTime = System.nanoTime();
                for (int j = 0; j < jEnd; ++j) {
                    for (int off = 0; off < offEnd;) {
                        messageDigest.update(in, off, byteLength);
                        off += byteLength;
                    }
                    t = messageDigest.digest();
                }
                endTime = System.nanoTime();

                long time = endTime - startTime;

                if (time0 == 0)
                    time0 = time;
                System.err.println(messageDigest.getProvider().getClass().getName() + ": ratio "
                        + String.format("%.2f", time / (double) time0) + ", time " + (endTime - startTime)
                        + ", digest " /*+ byteEncoder.encodeToString(t)*/
                        + ".");
            }
        }

        // org.bouncycastle.crypto.Mac
        System.err.println("----------------------------------------");

        time0 = 0;
        for (Mac mac : macs) {
            mac.init(new KeyParameter(in, 0, maxByteLength));

            long startTime, endTime;
            int offEnd = in.length - maxByteLength;

            startTime = System.nanoTime();
            for (int j = 0; j < jEnd; ++j) {
                for (int off = 0; off < offEnd; off = off + maxByteLength)
                    mac.update(in, off, maxByteLength);
                mac.doFinal(out, 0);
            }
            endTime = System.nanoTime();

            int macSize = mac.getMacSize();
            long time = endTime - startTime;

            if (time0 == 0)
                time0 = time;
            Arrays.fill(out, macSize, out.length, (byte) 0);
            System.err.println(mac.getClass().getName() + ": ratio "
                    + String.format("%.2f", time / (double) time0) + ", time " + time + ", out "
                    /*+ byteEncoder.encodeToString(out)*/ + ".");
        }
    }
}