Search in sources :

Example 16 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 17 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 18 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 19 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)19 GoCipher (com.thoughtworks.go.security.GoCipher)6 Test (org.junit.Test)6 BlockCipher (org.bouncycastle.crypto.BlockCipher)5 UrlArgument (com.thoughtworks.go.util.command.UrlArgument)4 BadPaddingException (javax.crypto.BadPaddingException)4 ParametersWithIV (org.bouncycastle.crypto.params.ParametersWithIV)4 SecretKeySpec (javax.crypto.spec.SecretKeySpec)3 CipherParameters (org.bouncycastle.crypto.CipherParameters)3 GCMBlockCipher (org.bouncycastle.crypto.modes.GCMBlockCipher)3 KeyParameter (org.bouncycastle.crypto.params.KeyParameter)3 InvalidJweException (org.xdi.oxauth.model.exception.InvalidJweException)3 SvnMaterial (com.thoughtworks.go.config.materials.svn.SvnMaterial)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)2 IvParameterSpec (javax.crypto.spec.IvParameterSpec)2 DataLengthException (org.bouncycastle.crypto.DataLengthException)2 AESEngine (org.bouncycastle.crypto.engines.AESEngine)2 RSABlindedEngine (org.bouncycastle.crypto.engines.RSABlindedEngine)2