Example usage for org.bouncycastle.crypto InvalidCipherTextException InvalidCipherTextException

List of usage examples for org.bouncycastle.crypto InvalidCipherTextException InvalidCipherTextException

Introduction

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

Prototype

public InvalidCipherTextException(String message) 

Source Link

Document

create a InvalidCipherTextException with the given message.

Usage

From source file:freenet.crypt.OCBBlockCipher_v149.java

License:Open Source License

public int doFinal(byte[] output, int outOff) throws IllegalStateException, InvalidCipherTextException {
    /*/* w  w w  . j  a v a 2  s  .  c  o  m*/
     * For decryption, get the tag from the end of the message
     */
    byte[] tag = null;
    if (!forEncryption) {
        if (mainBlockPos < macSize) {
            throw new InvalidCipherTextException("data too short");
        }
        mainBlockPos -= macSize;
        tag = new byte[macSize];
        System.arraycopy(mainBlock, mainBlockPos, tag, 0, macSize);
    }

    /*
     * HASH: Process any final partial block; compute final hash value
     */
    if (hashBlockPos > 0) {
        OCB_extend(hashBlock, hashBlockPos);
        updateHASH(L_Asterisk);
    }

    /*
     * OCB-ENCRYPT/OCB-DECRYPT: Process any final partial block
     */
    if (mainBlockPos > 0) {
        if (forEncryption) {
            OCB_extend(mainBlock, mainBlockPos);
            xor(Checksum, mainBlock);
        }

        xor(OffsetMAIN, L_Asterisk);

        byte[] Pad = new byte[16];
        hashCipher.processBlock(OffsetMAIN, 0, Pad, 0);

        xor(mainBlock, Pad);

        System.arraycopy(mainBlock, 0, output, outOff, mainBlockPos);

        if (!forEncryption) {
            OCB_extend(mainBlock, mainBlockPos);
            xor(Checksum, mainBlock);
        }
    }

    /*
     * OCB-ENCRYPT/OCB-DECRYPT: Compute raw tag
     */
    xor(Checksum, OffsetMAIN);
    xor(Checksum, L_Dollar);
    hashCipher.processBlock(Checksum, 0, Checksum, 0);
    xor(Checksum, Sum);

    this.macBlock = new byte[macSize];
    System.arraycopy(Checksum, 0, macBlock, 0, macSize);

    /*
     * Validate or append tag and reset this cipher for the next run
     */
    int resultLen = mainBlockPos;

    if (forEncryption) {
        // Append tag to the message
        System.arraycopy(macBlock, 0, output, outOff + resultLen, macSize);
        resultLen += macSize;
    } else {
        // Compare the tag from the message with the calculated one
        if (!Arrays.constantTimeAreEqual(macBlock, tag)) {
            throw new InvalidCipherTextException("mac check in OCB failed");
        }
    }

    reset(false);

    return resultLen;
}

From source file:heat.crypto.Crypto.java

License:Open Source License

public static byte[] aesDecrypt(byte[] ivCiphertext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) {
    try {/*from w w  w  .  j  a v  a 2 s .  c  om*/
        if (ivCiphertext.length < 16 || ivCiphertext.length % 16 != 0) {
            throw new InvalidCipherTextException("invalid ciphertext");
        }
        byte[] iv = Arrays.copyOfRange(ivCiphertext, 0, 16);
        byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, 16, ivCiphertext.length);
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        for (int i = 0; i < 32; i++) {
            dhSharedSecret[i] ^= nonce[i];
        }
        byte[] key = sha256().digest(dhSharedSecret);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(false, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(ciphertext.length)];
        int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0);
        plaintextLength += aes.doFinal(output, plaintextLength);
        byte[] result = new byte[plaintextLength];
        System.arraycopy(output, 0, result, 0, result.length);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.ccnx.ccn.impl.security.crypto.jce.RFC3394WrapWithPadEngine.java

License:Open Source License

public byte[] unwrap(byte[] input, int offset, int length) throws InvalidCipherTextException {

    if (_forWrapping) {
        throw new IllegalStateException("Not initialized for unwrapping!");
    }/*from   w w  w.j a  v  a2s .com*/

    int n = length / 8;

    if ((n * 8) != length) {
        throw new InvalidCipherTextException("unwrap data must be a multiple of 8 bytes");
    }

    byte[] block = new byte[length - _iv.length];
    byte[] a = new byte[_iv.length];
    byte[] buf = new byte[8 + _iv.length];

    System.arraycopy(input, 0, a, 0, _iv.length);
    System.arraycopy(input, _iv.length, block, 0, length - _iv.length);

    _engine.init(false, _parameters);

    n = n - 1;

    for (int j = 5; j >= 0; j--) {
        for (int i = n; i >= 1; i--) {
            System.arraycopy(a, 0, buf, 0, _iv.length);
            System.arraycopy(block, 8 * (i - 1), buf, _iv.length, 8);

            int t = n * j + i;
            for (int k = 1; t != 0; k++) {
                byte v = (byte) t;

                buf[_iv.length - k] ^= v;

                t >>>= 8;
            }

            _engine.processBlock(buf, 0, buf, 0);
            System.arraycopy(buf, 0, a, 0, 8);
            System.arraycopy(buf, 8, block, 8 * (i - 1), 8);
        }
    }

    for (int i = 0; i < FIXED_IV; i++) {
        if (a[i] != _iv[i]) {
            throw new InvalidCipherTextException("Checksum failed to verify!");
        }
    }
    int expectedLength = (a[FIXED_IV] << 24) + ((a[FIXED_IV + 1] & 0xFF) << 16)
            + ((a[FIXED_IV + 2] & 0xFF) << 8) + (a[FIXED_IV + 3] & 0xFF);

    int maxBlockLength = 8 * n;
    if ((expectedLength < (maxBlockLength - 8)) || (expectedLength > maxBlockLength)) {
        throw new InvalidCipherTextException("Invalid checksum length: got: " + block.length + " expected: "
                + expectedLength + " max: " + maxBlockLength + " n: " + n);
    }
    int b = (maxBlockLength - expectedLength) % 8;
    if (block.length != (expectedLength + b)) {
        throw new InvalidCipherTextException("Invalid checksum length: got: " + block.length + " expected: "
                + expectedLength + " b: " + b + " max: " + maxBlockLength + " n: " + n);
    }
    for (int i = expectedLength; i < block.length; ++i) {
        if (block[i] != 0) {
            throw new InvalidCipherTextException(
                    "Invalid padding: byte " + i + " is " + Integer.toHexString(0x000000FF & block[i]));
        }
    }

    // Strip padding
    if (b > 0) {
        byte[] trimmedBlock = new byte[expectedLength];
        System.arraycopy(block, 0, trimmedBlock, 0, expectedLength);
        block = trimmedBlock;
    }
    return block;
}

From source file:org.ethereum.crypto.EthereumIESEngine.java

License:Open Source License

private byte[] decryptBlock(byte[] inEnc, int inOff, int inLen, byte[] macData)
        throws InvalidCipherTextException {
    byte[] m = null;
    byte[] k = null;
    byte[] k1 = null;
    byte[] k2 = null;

    int len;//w ww  . j a v  a  2s .  c om

    // Ensure that the length of the input is greater than the MAC in bytes
    if (inLen <= (param.getMacKeySize() / 8)) {
        throw new InvalidCipherTextException("Length of input must be greater than the MAC");
    }

    if (cipher == null) {
        // Streaming mode.
        k1 = new byte[inLen - v.length - mac.getMacSize()];
        k2 = new byte[param.getMacKeySize() / 8];
        k = new byte[k1.length + k2.length];

        kdf.generateBytes(k, 0, k.length);

        //            if (v.length != 0)
        //            {
        //                System.arraycopy(K, 0, K2, 0, K2.length);
        //                System.arraycopy(K, K2.length, K1, 0, K1.length);
        //            }
        //            else
        {
            System.arraycopy(k, 0, k1, 0, k1.length);
            System.arraycopy(k, k1.length, k2, 0, k2.length);
        }

        m = new byte[k1.length];

        for (int i = 0; i != k1.length; i++) {
            m[i] = (byte) (inEnc[inOff + v.length + i] ^ k1[i]);
        }

        len = k1.length;
    } else {
        // Block cipher mode.
        k1 = new byte[((IESWithCipherParameters) param).getCipherKeySize() / 8];
        k2 = new byte[param.getMacKeySize() / 8];
        k = new byte[k1.length + k2.length];

        kdf.generateBytes(k, 0, k.length);
        System.arraycopy(k, 0, k1, 0, k1.length);
        System.arraycopy(k, k1.length, k2, 0, k2.length);

        // If iv provide use it to initialize the cipher
        if (iv != null) {
            cipher.init(false, new ParametersWithIV(new KeyParameter(k1), iv));
        } else {
            cipher.init(false, new KeyParameter(k1));
        }

        m = new byte[cipher.getOutputSize(inLen - v.length - mac.getMacSize())];
        len = cipher.processBytes(inEnc, inOff + v.length, inLen - v.length - mac.getMacSize(), m, 0);
        len += cipher.doFinal(m, len);
    }

    // Convert the length of the encoding vector into a byte array.
    byte[] p2 = param.getEncodingV();

    // Verify the MAC.
    int end = inOff + inLen;
    byte[] t1 = Arrays.copyOfRange(inEnc, end - mac.getMacSize(), end);

    byte[] t2 = new byte[t1.length];
    byte[] k2A;
    if (hashK2) {
        k2A = new byte[hash.getDigestSize()];
        hash.reset();
        hash.update(k2, 0, k2.length);
        hash.doFinal(k2A, 0);
    } else {
        k2A = k2;
    }
    mac.init(new KeyParameter(k2A));
    mac.update(iv, 0, iv.length);
    mac.update(inEnc, inOff + v.length, inLen - v.length - t2.length);

    if (p2 != null) {
        mac.update(p2, 0, p2.length);
    }

    if (v.length != 0 && p2 != null) {
        byte[] l2 = new byte[4];
        Pack.intToBigEndian(p2.length * 8, l2, 0);
        mac.update(l2, 0, l2.length);
    }

    if (macData != null) {
        mac.update(macData, 0, macData.length);
    }

    mac.doFinal(t2, 0);

    if (!Arrays.constantTimeAreEqual(t1, t2)) {
        throw new InvalidCipherTextException("Invalid MAC.");
    }

    // Output the message.
    return Arrays.copyOfRange(m, 0, len);
}

From source file:org.freenetproject.freemail.RTSFetcher.java

License:Open Source License

private byte[] decrypt_rts(File rtsmessage) throws IOException, InvalidCipherTextException {
    // initialise our ciphers
    RSAKeyParameters ourprivkey = AccountManager.getPrivateKey(account.getProps());
    AsymmetricBlockCipher deccipher = new RSAEngine();
    deccipher.init(false, ourprivkey);//from  w ww . ja va2s . c o m

    PaddedBufferedBlockCipher aescipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
            new PKCS7Padding());

    // first n bytes will be an encrypted RSA block containting the
    // AES IV and Key. Read that.
    byte[] encrypted_params = new byte[deccipher.getInputBlockSize()];
    int read = 0;
    FileInputStream fis = new FileInputStream(rtsmessage);
    try {
        while (read < encrypted_params.length) {
            read += fis.read(encrypted_params, read, encrypted_params.length - read);
            if (read < 0)
                break;
        }

        if (read < 0) {
            fis.close();
            throw new InvalidCipherTextException("RTS Message too short");
        }

        byte[] aes_iv_and_key = deccipher.processBlock(encrypted_params, 0, encrypted_params.length);

        KeyParameter kp = new KeyParameter(aes_iv_and_key, aescipher.getBlockSize(),
                aes_iv_and_key.length - aescipher.getBlockSize());
        ParametersWithIV kpiv = new ParametersWithIV(kp, aes_iv_and_key, 0, aescipher.getBlockSize());
        try {
            aescipher.init(false, kpiv);
        } catch (IllegalArgumentException iae) {
            fis.close();
            throw new InvalidCipherTextException(iae.getMessage());
        }

        byte[] plaintext = new byte[aescipher.getOutputSize((int) rtsmessage.length() - read)];

        int ptbytes = 0;
        while (read < rtsmessage.length()) {
            byte[] buf = new byte[(int) rtsmessage.length() - read];

            int thisread = fis.read(buf, 0, (int) rtsmessage.length() - read);
            ptbytes += aescipher.processBytes(buf, 0, thisread, plaintext, ptbytes);
            read += thisread;
        }

        try {
            aescipher.doFinal(plaintext, ptbytes);
        } catch (DataLengthException dle) {
            throw new InvalidCipherTextException(dle.getMessage());
        }

        return plaintext;
    } finally {
        fis.close();
    }
}

From source file:org.xipki.security.p11.AbstractP11DSASigner.java

License:Open Source License

@Override
public byte[] generateSignature() throws CryptoException, DataLengthException {
    byte[] digestValue = new byte[digest.getDigestSize()];
    digest.doFinal(digestValue, 0);/*  w  ww. j  a v  a2 s  . c  om*/

    try {
        return sign(digestValue);
    } catch (SignerException e) {
        throw new InvalidCipherTextException("SignerException: " + e.getMessage());
    }
}

From source file:org.xipki.security.p11.sun.nss.NSSSignatureSpi.java

License:Open Source License

private static byte[] decodePkcs11Block(final byte[] block, final int minLen)
        throws InvalidCipherTextException {
    int offset = 0;
    while (block[offset] == 0) {
        offset++;/* www  .  j a  v a 2  s .  co m*/
    }

    if (block.length - offset < minLen) {
        throw new InvalidCipherTextException("block truncated");
    }

    byte type = block[offset];

    if (type != 1) {
        throw new InvalidCipherTextException("unknown block type");
    }

    // find and extract the message block.
    int start;
    for (start = offset + 1; start != block.length; start++) {
        byte pad = block[start];
        if (pad == 0) {
            break;
        }
        if (pad != (byte) 0xff) {
            throw new InvalidCipherTextException("block padding incorrect");
        }
    }

    start++; // data should start at the next byte

    final int HEADER_LENGTH = 10;

    if (start > block.length || start < HEADER_LENGTH) {
        throw new InvalidCipherTextException("no data in block");
    }

    byte[] result = new byte[block.length - start];
    System.arraycopy(block, start, result, 0, result.length);

    return result;
}

From source file:secret.sharing.Dealer.java

License:Open Source License

/**
 * Decrypts a set of data blocks and joins the data back to the secret
 * @param encryptedDataBlocks the encrypted data blocks
 * @return the decrypted secret//from  w w  w  . j  a  v a 2s.  c  om
 */
private byte[] decryptEncryptedDataBlocks(byte[][] encryptedDataBlocks)
        throws InvalidKeyException, DataLengthException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, UnsupportedEncodingException, IllegalBlockSizeException,
        BadPaddingException, IllegalStateException, InvalidCipherTextException, InvalidKeySpecException {
    if (encryptedDataBlocks.length < Encryptor.EncryptionHeaderBlocks + 1)
        throw new IllegalArgumentException(
                "there have to be at least two encrypted data blocks: 1 * header + n * data, n > 0");
    // allocate buffer: number of encrypted data blocks minus 1 (header) times default container size
    ByteBuffer dataBuffer = ByteBuffer
            .allocate((encryptedDataBlocks.length - Encryptor.EncryptionHeaderBlocks) * ContainerSize);

    byte[][] encHeader = new byte[Encryptor.EncryptionHeaderBlocks][];
    for (int i = 0; i < Encryptor.EncryptionHeaderBlocks; ++i)
        encHeader[i] = encryptedDataBlocks[i];
    Encryptor encryptor = new Encryptor(mPassPhrase, false, encHeader);

    for (int i = Encryptor.EncryptionHeaderBlocks; i < encryptedDataBlocks.length; ++i) {
        byte[] currentBlock = encryptor.ProcessDataBlock(encryptedDataBlocks[i]);
        dataBuffer.put(currentBlock);
    }

    if (!encryptor.IsHMACValid())
        throw new InvalidCipherTextException("Invalid HMAC!");

    return dataBuffer.array();
}