Example usage for org.bouncycastle.crypto.params AEADParameters getMacSize

List of usage examples for org.bouncycastle.crypto.params AEADParameters getMacSize

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.params AEADParameters getMacSize.

Prototype

public int getMacSize() 

Source Link

Usage

From source file:freenet.crypt.OCBBlockCipher_v149.java

License:Open Source License

public void init(boolean forEncryption, CipherParameters parameters) throws IllegalArgumentException {
    this.forEncryption = forEncryption;
    this.macBlock = null;

    KeyParameter keyParameter;/*  www. ja  v  a  2 s  .c o m*/

    byte[] N;
    if (parameters instanceof AEADParameters) {
        AEADParameters aeadParameters = (AEADParameters) parameters;

        N = aeadParameters.getNonce();
        initialAssociatedText = aeadParameters.getAssociatedText();

        int macSizeBits = aeadParameters.getMacSize();
        if (macSizeBits < 64 || macSizeBits > 128 || macSizeBits % 8 != 0) {
            throw new IllegalArgumentException("Invalid value for MAC size: " + macSizeBits);
        }

        macSize = macSizeBits / 8;
        keyParameter = aeadParameters.getKey();
    } else if (parameters instanceof ParametersWithIV) {
        ParametersWithIV parametersWithIV = (ParametersWithIV) parameters;

        N = parametersWithIV.getIV();
        initialAssociatedText = null;
        macSize = 16;
        keyParameter = (KeyParameter) parametersWithIV.getParameters();
    } else {
        throw new IllegalArgumentException("invalid parameters passed to OCB");
    }

    this.hashBlock = new byte[16];
    this.mainBlock = new byte[forEncryption ? BLOCK_SIZE : (BLOCK_SIZE + macSize)];

    if (N == null) {
        N = new byte[0];
    }

    /*
     * TODO There's currently a thread on CFRG
     * (http://www.ietf.org/mail-archive/web/cfrg/current/msg03433.html) debating including
     * (macSize % 128) in the nonce, in which case this test becomes simpler:
     */
    //        if (N.length > 15)
    //        {
    //            throw new IllegalArgumentException("IV must be no more than 120 bits");
    //        }
    if (N.length > 16 || (N.length == 16 && (N[0] & 0x80) != 0)) {
        /*
         * NOTE: We don't just ignore bit 128 because it would hide from the caller the fact
         * that two nonces differing only in bit 128 are not different.
         */
        throw new IllegalArgumentException("IV must be no more than 127 bits");
    }

    /*
     * KEY-DEPENDENT INITIALISATION
     */

    if (keyParameter == null) {
        // TODO If 'keyParameter' is null we're re-using the last key.
    }

    // hashCipher always used in forward mode
    hashCipher.init(true, keyParameter);
    mainCipher.init(forEncryption, keyParameter);

    this.L_Asterisk = new byte[16];
    hashCipher.processBlock(L_Asterisk, 0, L_Asterisk, 0);

    this.L_Dollar = OCB_double(L_Asterisk);

    this.L = new Vector();
    this.L.addElement(OCB_double(L_Dollar));

    /*
     * NONCE-DEPENDENT AND PER-ENCRYPTION/DECRYPTION INITIALISATION
     */

    byte[] nonce = new byte[16];
    System.arraycopy(N, 0, nonce, nonce.length - N.length, N.length);

    /*
     * TODO There's currently a thread on CFRG
     * (http://www.ietf.org/mail-archive/web/cfrg/current/msg03433.html) debating including
     * (macSize % 128) in the nonce, in which case this code becomes simpler:
     */
    //        nonce[0] = (byte)(macSize << 4);
    //        nonce[15 - N.length] |= 1;
    if (N.length == 16) {
        nonce[0] &= 0x80;
    } else {
        nonce[15 - N.length] = 1;
    }

    int bottom = nonce[15] & 0x3F;
    // System.out.println("bottom: " + bottom);

    byte[] Ktop = new byte[16];
    nonce[15] &= 0xC0;
    hashCipher.processBlock(nonce, 0, Ktop, 0);

    byte[] Stretch = new byte[24];
    System.arraycopy(Ktop, 0, Stretch, 0, 16);
    for (int i = 0; i < 8; ++i) {
        Stretch[16 + i] = (byte) (Ktop[i] ^ Ktop[i + 1]);
    }

    this.OffsetMAIN_0 = new byte[16];
    int bits = bottom % 8, bytes = bottom / 8;
    if (bits == 0) {
        System.arraycopy(Stretch, bytes, OffsetMAIN_0, 0, 16);
    } else {
        for (int i = 0; i < 16; ++i) {
            int b1 = Stretch[bytes] & 0xff;
            int b2 = Stretch[++bytes] & 0xff;
            this.OffsetMAIN_0[i] = (byte) ((b1 << bits) | (b2 >>> (8 - bits)));
        }
    }

    this.hashBlockPos = 0;
    this.mainBlockPos = 0;

    this.hashBlockCount = 0;
    this.mainBlockCount = 0;

    this.OffsetHASH = new byte[16];
    this.Sum = new byte[16];
    this.OffsetMAIN = Arrays.clone(this.OffsetMAIN_0);
    this.Checksum = new byte[16];

    if (initialAssociatedText != null) {
        processAADBytes(initialAssociatedText, 0, initialAssociatedText.length);
    }
}

From source file:org.xdi.oxauth.model.jwe.JweEncrypterImpl.java

License:MIT License

@Override
public Pair<String, String> generateCipherTextAndIntegrityValue(byte[] contentMasterKey,
        byte[] initializationVector, byte[] additionalAuthenticatedData, byte[] plainText)
        throws InvalidJweException {
    if (getBlockEncryptionAlgorithm() == null) {
        throw new InvalidJweException("The block encryption algorithm is null");
    }/*from   w ww  . ja v  a2 s  .co m*/
    if (contentMasterKey == null) {
        throw new InvalidJweException("The content master key (CMK) is null");
    }
    if (initializationVector == null) {
        throw new InvalidJweException("The initialization vector is null");
    }
    if (additionalAuthenticatedData == null) {
        throw new InvalidJweException("The additional authentication data is null");
    }
    if (plainText == null) {
        throw new InvalidJweException("The plain text to encrypt is null");
    }

    try {
        if (getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A128GCM
                || getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A256GCM) {
            SecretKey secretKey = new SecretKeySpec(contentMasterKey, "AES");
            KeyParameter key = new KeyParameter(contentMasterKey);
            final int MAC_SIZE_BITS = 128;
            AEADParameters aeadParameters = new AEADParameters(key, MAC_SIZE_BITS, initializationVector,
                    additionalAuthenticatedData);

            final int macSize = aeadParameters.getMacSize() / 8;
            BlockCipher blockCipher = new AESEngine();
            CipherParameters params = new KeyParameter(secretKey.getEncoded());
            blockCipher.init(true, params);
            GCMBlockCipher aGCMBlockCipher = new GCMBlockCipher(blockCipher);
            aGCMBlockCipher.init(true, aeadParameters);
            int len = aGCMBlockCipher.getOutputSize(plainText.length);
            byte[] out = new byte[len];
            int outOff = aGCMBlockCipher.processBytes(plainText, 0, plainText.length, out, 0);
            outOff += aGCMBlockCipher.doFinal(out, outOff);
            byte[] cipherText = new byte[outOff - macSize];
            System.arraycopy(out, 0, cipherText, 0, cipherText.length);
            byte[] authenticationTag = new byte[macSize];
            System.arraycopy(out, outOff - macSize, authenticationTag, 0, authenticationTag.length);

            String encodedCipherText = Base64Util.base64urlencode(cipherText);
            String encodedAuthenticationTag = Base64Util.base64urlencode(authenticationTag);

            return new Pair<String, String>(encodedCipherText, encodedAuthenticationTag);
        } else if (getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A128CBC_PLUS_HS256
                || getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A256CBC_PLUS_HS512) {
            byte[] cek = KeyDerivationFunction.generateCek(contentMasterKey, getBlockEncryptionAlgorithm());
            IvParameterSpec parameters = new IvParameterSpec(initializationVector);
            Cipher cipher = Cipher.getInstance(getBlockEncryptionAlgorithm().getAlgorithm(), "BC");
            //Cipher cipher = Cipher.getInstance(getBlockEncryptionAlgorithm().getAlgorithm());
            SecretKeySpec secretKeySpec = new SecretKeySpec(cek, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, parameters);
            byte[] cipherText = cipher.doFinal(plainText);

            String encodedCipherText = Base64Util.base64urlencode(cipherText);

            String securedInputValue = new String(additionalAuthenticatedData,
                    Charset.forName(Util.UTF8_STRING_ENCODING)) + "." + encodedCipherText;

            byte[] cik = KeyDerivationFunction.generateCik(contentMasterKey, getBlockEncryptionAlgorithm());
            SecretKey secretKey = new SecretKeySpec(cik,
                    getBlockEncryptionAlgorithm().getIntegrityValueAlgorithm());
            Mac mac = Mac.getInstance(getBlockEncryptionAlgorithm().getIntegrityValueAlgorithm());
            mac.init(secretKey);
            byte[] integrityValue = mac.doFinal(securedInputValue.getBytes(Util.UTF8_STRING_ENCODING));

            String encodedIntegrityValue = Base64Util.base64urlencode(integrityValue);

            return new Pair<String, String>(encodedCipherText, encodedIntegrityValue);
        } else {
            throw new InvalidJweException("The block encryption algorithm is not supported");
        }
    } catch (InvalidCipherTextException e) {
        throw new InvalidJweException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidJweException(e);
    } catch (UnsupportedEncodingException e) {
        throw new InvalidJweException(e);
    } catch (NoSuchProviderException e) {
        throw new InvalidJweException(e);
    } catch (IllegalBlockSizeException e) {
        throw new InvalidJweException(e);
    } catch (InvalidKeyException e) {
        throw new InvalidJweException(e);
    } catch (BadPaddingException e) {
        throw new InvalidJweException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new InvalidJweException(e);
    } catch (NoSuchPaddingException e) {
        throw new InvalidJweException(e);
    } catch (InvalidParameterException e) {
        throw new InvalidJweException(e);
    }
}