Search in sources :

Example 21 with InvalidCipherTextException

use of org.bouncycastle.crypto.InvalidCipherTextException in project sentinel-android by Samourai-Wallet.

the class AESUtil method decrypt.

// AES 256 PBKDF2 CBC iso10126 decryption
// 16 byte IV must be prepended to ciphertext - Compatible with crypto-js
public static String decrypt(String ciphertext, CharSequenceX password, int iterations) {
    final int AESBlockSize = 4;
    byte[] cipherdata = Base64.decodeBase64(ciphertext.getBytes());
    // Seperate the IV and cipher data
    byte[] iv = copyOfRange(cipherdata, 0, AESBlockSize * 4);
    byte[] input = copyOfRange(cipherdata, AESBlockSize * 4, cipherdata.length);
    PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password.toString().toCharArray()), iv, iterations);
    KeyParameter keyParam = (KeyParameter) generator.generateDerivedParameters(256);
    CipherParameters params = new ParametersWithIV(keyParam, iv);
    // setup AES cipher in CBC mode with PKCS7 padding
    BlockCipherPadding padding = new ISO10126d2Padding();
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
    cipher.reset();
    cipher.init(false, params);
    // create a temporary buffer to decode into (includes padding)
    byte[] buf = new byte[cipher.getOutputSize(input.length)];
    int len = cipher.processBytes(input, 0, input.length, buf, 0);
    try {
        len += cipher.doFinal(buf, len);
    } catch (InvalidCipherTextException icte) {
        icte.printStackTrace();
        return null;
    }
    // remove padding
    byte[] out = new byte[len];
    System.arraycopy(buf, 0, out, 0, len);
    // return string representation of decoded bytes
    String ret = null;
    try {
        ret = new String(out, "UTF-8");
    } catch (UnsupportedEncodingException uee) {
        uee.printStackTrace();
        return null;
    }
    return ret;
}
Also used : PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) AESEngine(org.bouncycastle.crypto.engines.AESEngine) InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) PKCS5S2ParametersGenerator(org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator) KeyParameter(org.bouncycastle.crypto.params.KeyParameter) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ISO10126d2Padding(org.bouncycastle.crypto.paddings.ISO10126d2Padding) CipherParameters(org.bouncycastle.crypto.CipherParameters) ParametersWithIV(org.bouncycastle.crypto.params.ParametersWithIV) BlockCipherPadding(org.bouncycastle.crypto.paddings.BlockCipherPadding) BufferedBlockCipher(org.bouncycastle.crypto.BufferedBlockCipher) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) CBCBlockCipher(org.bouncycastle.crypto.modes.CBCBlockCipher) PBEParametersGenerator(org.bouncycastle.crypto.PBEParametersGenerator)

Example 22 with InvalidCipherTextException

use of org.bouncycastle.crypto.InvalidCipherTextException in project robovm by robovm.

the class DESedeWrapEngine method unwrap.

/**
    * Method unwrap
    *
    * @param in
    * @param inOff
    * @param inLen
    * @return the unwrapped bytes.
    * @throws InvalidCipherTextException
    */
public byte[] unwrap(byte[] in, int inOff, int inLen) throws InvalidCipherTextException {
    if (forWrapping) {
        throw new IllegalStateException("Not set for unwrapping");
    }
    if (in == null) {
        throw new InvalidCipherTextException("Null pointer as ciphertext");
    }
    final int blockSize = engine.getBlockSize();
    if (inLen % blockSize != 0) {
        throw new InvalidCipherTextException("Ciphertext not multiple of " + blockSize);
    }
    /*
      // Check if the length of the cipher text is reasonable given the key
      // type. It must be 40 bytes for a 168 bit key and either 32, 40, or
      // 48 bytes for a 128, 192, or 256 bit key. If the length is not supported
      // or inconsistent with the algorithm for which the key is intended,
      // return error.
      //
      // we do not accept 168 bit keys. it has to be 192 bit.
      int lengthA = (estimatedKeyLengthInBit / 8) + 16;
      int lengthB = estimatedKeyLengthInBit % 8;

      if ((lengthA != keyToBeUnwrapped.length) || (lengthB != 0)) {
         throw new XMLSecurityException("empty");
      }
      */
    // Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK
    // and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3.
    ParametersWithIV param2 = new ParametersWithIV(this.param, IV2);
    this.engine.init(false, param2);
    byte[] TEMP3 = new byte[inLen];
    for (int currentBytePos = 0; currentBytePos != inLen; currentBytePos += blockSize) {
        engine.processBlock(in, inOff + currentBytePos, TEMP3, currentBytePos);
    }
    // Reverse the order of the octets in TEMP3 and call the result TEMP2.
    byte[] TEMP2 = reverse(TEMP3);
    // Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets.
    this.iv = new byte[8];
    byte[] TEMP1 = new byte[TEMP2.length - 8];
    System.arraycopy(TEMP2, 0, this.iv, 0, 8);
    System.arraycopy(TEMP2, 8, TEMP1, 0, TEMP2.length - 8);
    // Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV
    // found in the previous step. Call the result WKCKS.
    this.paramPlusIV = new ParametersWithIV(this.param, this.iv);
    this.engine.init(false, this.paramPlusIV);
    byte[] WKCKS = new byte[TEMP1.length];
    for (int currentBytePos = 0; currentBytePos != WKCKS.length; currentBytePos += blockSize) {
        engine.processBlock(TEMP1, currentBytePos, WKCKS, currentBytePos);
    }
    // Decompose WKCKS. CKS is the last 8 octets and WK, the wrapped key, are
    // those octets before the CKS.
    byte[] result = new byte[WKCKS.length - 8];
    byte[] CKStoBeVerified = new byte[8];
    System.arraycopy(WKCKS, 0, result, 0, WKCKS.length - 8);
    System.arraycopy(WKCKS, WKCKS.length - 8, CKStoBeVerified, 0, 8);
    // with the CKS extracted in the above step. If they are not equal, return error.
    if (!checkCMSKeyChecksum(result, CKStoBeVerified)) {
        throw new InvalidCipherTextException("Checksum inside ciphertext is corrupted");
    }
    // WK is the wrapped key, now extracted for use in data decryption.
    return result;
}
Also used : ParametersWithIV(org.bouncycastle.crypto.params.ParametersWithIV) InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException)

Example 23 with InvalidCipherTextException

use of org.bouncycastle.crypto.InvalidCipherTextException in project XobotOS by xamarin.

the class DESedeWrapEngine method unwrap.

/**
    * Method unwrap
    *
    * @param in
    * @param inOff
    * @param inLen
    * @return the unwrapped bytes.
    * @throws InvalidCipherTextException
    */
public byte[] unwrap(byte[] in, int inOff, int inLen) throws InvalidCipherTextException {
    if (forWrapping) {
        throw new IllegalStateException("Not set for unwrapping");
    }
    if (in == null) {
        throw new InvalidCipherTextException("Null pointer as ciphertext");
    }
    final int blockSize = engine.getBlockSize();
    if (inLen % blockSize != 0) {
        throw new InvalidCipherTextException("Ciphertext not multiple of " + blockSize);
    }
    /*
      // Check if the length of the cipher text is reasonable given the key
      // type. It must be 40 bytes for a 168 bit key and either 32, 40, or
      // 48 bytes for a 128, 192, or 256 bit key. If the length is not supported
      // or inconsistent with the algorithm for which the key is intended,
      // return error.
      //
      // we do not accept 168 bit keys. it has to be 192 bit.
      int lengthA = (estimatedKeyLengthInBit / 8) + 16;
      int lengthB = estimatedKeyLengthInBit % 8;

      if ((lengthA != keyToBeUnwrapped.length) || (lengthB != 0)) {
         throw new XMLSecurityException("empty");
      }
      */
    // Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK
    // and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3.
    ParametersWithIV param2 = new ParametersWithIV(this.param, IV2);
    this.engine.init(false, param2);
    byte[] TEMP3 = new byte[inLen];
    for (int currentBytePos = 0; currentBytePos != inLen; currentBytePos += blockSize) {
        engine.processBlock(in, inOff + currentBytePos, TEMP3, currentBytePos);
    }
    // Reverse the order of the octets in TEMP3 and call the result TEMP2.
    byte[] TEMP2 = reverse(TEMP3);
    // Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets.
    this.iv = new byte[8];
    byte[] TEMP1 = new byte[TEMP2.length - 8];
    System.arraycopy(TEMP2, 0, this.iv, 0, 8);
    System.arraycopy(TEMP2, 8, TEMP1, 0, TEMP2.length - 8);
    // Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV
    // found in the previous step. Call the result WKCKS.
    this.paramPlusIV = new ParametersWithIV(this.param, this.iv);
    this.engine.init(false, this.paramPlusIV);
    byte[] WKCKS = new byte[TEMP1.length];
    for (int currentBytePos = 0; currentBytePos != WKCKS.length; currentBytePos += blockSize) {
        engine.processBlock(TEMP1, currentBytePos, WKCKS, currentBytePos);
    }
    // Decompose WKCKS. CKS is the last 8 octets and WK, the wrapped key, are
    // those octets before the CKS.
    byte[] result = new byte[WKCKS.length - 8];
    byte[] CKStoBeVerified = new byte[8];
    System.arraycopy(WKCKS, 0, result, 0, WKCKS.length - 8);
    System.arraycopy(WKCKS, WKCKS.length - 8, CKStoBeVerified, 0, 8);
    // with the CKS extracted in the above step. If they are not equal, return error.
    if (!checkCMSKeyChecksum(result, CKStoBeVerified)) {
        throw new InvalidCipherTextException("Checksum inside ciphertext is corrupted");
    }
    // WK is the wrapped key, now extracted for use in data decryption.
    return result;
}
Also used : ParametersWithIV(org.bouncycastle.crypto.params.ParametersWithIV) InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException)

Example 24 with InvalidCipherTextException

use of org.bouncycastle.crypto.InvalidCipherTextException in project robovm by robovm.

the class BaseBlockCipher method engineDoFinal.

protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException {
    int len = 0;
    byte[] tmp = new byte[engineGetOutputSize(inputLen)];
    if (inputLen != 0) {
        len = cipher.processBytes(input, inputOffset, inputLen, tmp, 0);
    }
    try {
        len += cipher.doFinal(tmp, len);
    } catch (DataLengthException e) {
        throw new IllegalBlockSizeException(e.getMessage());
    } catch (InvalidCipherTextException e) {
        throw new BadPaddingException(e.getMessage());
    }
    if (len == tmp.length) {
        return tmp;
    }
    byte[] out = new byte[len];
    System.arraycopy(tmp, 0, out, 0, len);
    return out;
}
Also used : InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) DataLengthException(org.bouncycastle.crypto.DataLengthException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) BadPaddingException(javax.crypto.BadPaddingException)

Example 25 with InvalidCipherTextException

use of org.bouncycastle.crypto.InvalidCipherTextException in project oxAuth by GluuFederation.

the class JweEncrypterImpl method generateCipherTextAndIntegrityValue.

@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");
    }
    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);
    }
}
Also used : InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) KeyParameter(org.bouncycastle.crypto.params.KeyParameter) InvalidParameterException(org.xdi.oxauth.model.exception.InvalidParameterException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) Pair(org.xdi.oxauth.model.util.Pair) AESEngine(org.bouncycastle.crypto.engines.AESEngine) BlockCipher(org.bouncycastle.crypto.BlockCipher) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CipherParameters(org.bouncycastle.crypto.CipherParameters) AEADParameters(org.bouncycastle.crypto.params.AEADParameters) IvParameterSpec(javax.crypto.spec.IvParameterSpec) BlockCipher(org.bouncycastle.crypto.BlockCipher) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher)

Aggregations

InvalidCipherTextException (org.bouncycastle.crypto.InvalidCipherTextException)46 KeyParameter (org.bouncycastle.crypto.params.KeyParameter)13 ParametersWithIV (org.bouncycastle.crypto.params.ParametersWithIV)13 AESEngine (org.bouncycastle.crypto.engines.AESEngine)12 CipherParameters (org.bouncycastle.crypto.CipherParameters)11 PaddedBufferedBlockCipher (org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher)9 IOException (java.io.IOException)7 DataLengthException (org.bouncycastle.crypto.DataLengthException)7 CBCBlockCipher (org.bouncycastle.crypto.modes.CBCBlockCipher)7 GCMBlockCipher (org.bouncycastle.crypto.modes.GCMBlockCipher)7 GoCipher (com.thoughtworks.go.security.GoCipher)6 Test (org.junit.Test)6 BadPaddingException (javax.crypto.BadPaddingException)5 BlockCipher (org.bouncycastle.crypto.BlockCipher)5 BufferedBlockCipher (org.bouncycastle.crypto.BufferedBlockCipher)5 UrlArgument (com.thoughtworks.go.util.command.UrlArgument)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 ExtendedInvalidCipherTextException (org.openremote.agent.protocol.bluetooth.mesh.utils.ExtendedInvalidCipherTextException)4 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)3 SecretKeySpec (javax.crypto.spec.SecretKeySpec)3