0

你好。

首先:我是stackOverflow和我正在谈论的主题的新手......
我试图避免在我的Java应用程序中使用cryptlib库进行TripleDES加密(现在我正在使用AES - 以确保向下兼容性我还希望能够解码使用 cryptlib 库创建但不使用 JNI 的字符串)。
但是我现在尝试的所有方法都不适合我。

配置:
算法: TripleDES
模式: CBC
格式: CRYPT_FORMAT_CRYPTLIB
密钥的大小为 16 字节(不方便,但 BouncyCastle 会支持)。
并且加密数据的大小不是8 的倍数(例如 81 字节)。

在我的库包装器中(也在 C 中),上下文是这样创建的:

cryptCreateContext( &cryptContext, CRYPT_UNUSED, CRYPT_ALGO_3DES);
cryptSetAttribute( cryptContext, CRYPT_CTXINFO_MODE, CRYPT_MODE_CBC );
cryptSetAttributeString( cryptContext, CRYPT_CTXINFO_KEY, key, keyLen); 

信封是这样创建的:

cryptCreateEnvelope( envelope, CRYPT_FORMAT_CRYPTLIB );

我认为问题在于格式(因为它是“cryptlib 本机”格式) - 我在网上找不到任何关于它的描述......

目前我最好的尝试是这个:

Security.addProvider(new BouncyCastleProvider());
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), "DESede");
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
Cipher e_cipher = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");
e_cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);

byte[] hexdecoded = Hex.decode(ENCRYPTED.getBytes());
byte [] cipherText = e_cipher.doFinal(hexdecoded);

return new String(cipherText);

我也尝试了不同的填充,但我总是以这两个例外之一结束:

  • javax.crypto.IllegalBlockSizeException:数据未对齐块大小
  • javax.crypto.IllegalBlockSizeException:最后一个块在解密中不完整

我有点绝望,所以如果有人能帮助我,我会很高兴...

编辑: 这是加密代码(CryptData.cpp):

bool CCryptData::encryptData(BYTE *key,int keyLen, BYTE *data, int dataLen, int resultMemSize, BYTE *result, int &resultLen)
{
    CRYPT_ENVELOPE cryptEnvelope;
    CRYPT_CONTEXT cryptContext;
    CRYPT_ALGO cryptAlgo = selectCipher( CRYPT_ALGO_3DES );
    int count;

    /* Create the session key context.  We don't check for errors here since
       this code will already have been tested earlier */
    cryptCreateContext( &cryptContext, CRYPT_UNUSED, cryptAlgo );
    cryptSetAttribute( cryptContext, CRYPT_CTXINFO_MODE, CRYPT_MODE_CBC );
    cryptSetAttributeString( cryptContext, CRYPT_CTXINFO_KEY, key, keyLen );

    /* Create the envelope, push in a password and the data, pop the
       enveloped result, and destroy the envelope */
    if( !createEnvelope( &cryptEnvelope ) || \
        !addEnvInfoNumeric( cryptEnvelope, CRYPT_ENVINFO_SESSIONKEY,
                            cryptContext ) )
        return( FALSE );

    cryptSetAttribute( cryptEnvelope, CRYPT_ENVINFO_DATASIZE, dataLen );

    count = pushData( cryptEnvelope, data, dataLen, NULL, 0 );

    if( cryptStatusError( count ) )
        return( FALSE );

    resultLen = popData( cryptEnvelope, result, resultMemSize);

    if( cryptStatusError( count ) )
        return( FALSE );
    if( !destroyEnvelope( cryptEnvelope ) )
        return( FALSE );

    return true;
}

bool CCryptData::checkErrorStatus(int status, CString function)
{
    if( cryptStatusError( status ) )
    {
        m_lastError  = "Error occured in function " + function;
        m_lastError += " with StatusCode: " + status;
        m_bError = true;
        return true;
    }

    return false;
}

int CCryptData::createEnvelope( CRYPT_ENVELOPE *envelope )
{
    int status;

    /* Create the envelope */
    status = cryptCreateEnvelope( envelope, CRYPT_UNUSED, CRYPT_FORMAT_CRYPTLIB );
    if( checkErrorStatus(status, "createEnvelope"))
        return false;

    return( TRUE );
}

int CCryptData::destroyEnvelope( CRYPT_ENVELOPE envelope )
{
    int status;

    /* Destroy the envelope */
    status = cryptDestroyEnvelope( envelope );
    if( checkErrorStatus( status, "destroyEnvelope"))
        return false;

    return( TRUE );

}

int CCryptData::pushData( const CRYPT_ENVELOPE envelope, const BYTE *buffer,
                         const int length, const void *stringEnvInfo,
                         const int numericEnvInfo )
{
    int status, bytesIn;

    /* Push in the data */
    status = cryptPushData( envelope, buffer, length, &bytesIn );
    if( cryptStatusError( status ) )
    {
        printf( "cryptPushData() failed with error code %d, line %d.\n",
                status, __LINE__ );
        return( status );
    }
    if( bytesIn != length )
    {
        printf( "cryptPushData() only copied %d of %d bytes, line %d.\n",
                bytesIn, length, __LINE__ );
        return( SENTINEL );
    }

    /* Flush the data */
    status = cryptPushData( envelope, NULL, 0, NULL );
    if( cryptStatusError( status ) && status != CRYPT_ERROR_COMPLETE )
        {
        printf( "cryptPushData() (flush) failed with error code %d, line "
                "%d.\n", status, __LINE__ );
        return( status );
        }

    return( bytesIn );

}

int CCryptData::popData( CRYPT_ENVELOPE envelope, BYTE *buffer, int bufferSize )
{
    int status, bytesOut;

    status = cryptPopData( envelope, buffer, bufferSize, &bytesOut );
    if( cryptStatusError( status ) )
        {
        printf( "cryptPopData() failed with error code %d, line %d.\n",
                status, __LINE__ );
        return( status );
        }

    return( bytesOut );

}

int CCryptData::addEnvInfoNumeric( const CRYPT_ENVELOPE envelope,
                              const CRYPT_ATTRIBUTE_TYPE type,
                              const int envInfo )
{
    int status;

    status = cryptSetAttribute( envelope, type, envInfo );
    if( checkErrorStatus( status, "addEnvInfoNumeric"))
        return false;

    return( TRUE );

}

CRYPT_ALGO CCryptData::selectCipher( const CRYPT_ALGO algorithm )
{
    if( cryptStatusOK( cryptQueryCapability( algorithm, NULL ) ) )
        return( algorithm );
    return( CRYPT_ALGO_BLOWFISH );
}

编辑 2: 相比之下,它与此邮件列表中描述的实现相同。
但我想用Java解码它......

编辑 3: 我认为问题在于,加密数据被封装在 cryptlib 中(如代码所示)。

编辑 4: 我知道问题在于包围。cryptlib 使用创建的 crypt 上下文的会话密钥以 CRYPT_FORMAT_CRYPTLIB 格式封装解密数据。现在的问题是如何在执行真正的解密之前解码信封。
有什么建议我可以如何执行解码?

4

2 回答 2

1

我终于明白了。
调试了cryptlib的源码后发现,密文是HEX编码的CMS封装的内容。
我使用这个在线解码器来分析 ASN.1 序列(CMS 使用 ASN.1 表示法):
http ://www.aggressivesoftware.com/tools/asn1decoder.php

之后,我可以使用 BouncyCastle 作为提供者在 Java 中重现解码和解密:


    public byte[] decrypt(final byte[] data) throws CryptoException {
        try {
            Security.addProvider(new BouncyCastleProvider());

        EncryptedContentInfo encryptionInfo = parseContentInfo(data);
        AlgorithmIdentifier algoID = encryptionInfo.getContentEncryptionAlgorithm();

        // get the real encrypted data
        byte[] encryptedData = encryptionInfo.getEncryptedContent().getOctets();

        // extract the initialization vector from the algorithm identifier object
        byte[] ivBytes = ((ASN1OctetString) algoID.getParameters()).getOctets();
        // create the key depending on the algorithm
        SecretKeySpec keySpec = new SecretKeySpec(rawKey, algoID.getObjectId().getId());
        // request cipher
        Cipher c = Cipher.getInstance(algoID.getObjectId().getId(), CRYPT_PROVIDER);

        c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ivBytes));
        byte[] decrypted = c.doFinal(encryptedData);

        return decrypted;

        } catch (NoSuchAlgorithmException e) {
            throw new CryptoException(e);
        } catch (NoSuchProviderException e) {
            throw new CryptoException(e);
        } catch (NoSuchPaddingException e) {
            throw new CryptoException(e);
        } catch (InvalidKeyException e) {
            throw new CryptoException(e);
        } catch (InvalidAlgorithmParameterException e) {
            throw new CryptoException(e);
        } catch (IllegalBlockSizeException e) {
            throw new CryptoException(e);
        } catch (BadPaddingException e) {
            throw new CryptoException(e);
        }
    }
}

private EncryptedContentInfo parseContentInfo(final byte[] encrypted) throws CryptoException { try { // create a new byte array stream ByteArrayInputStream bin = new ByteArrayInputStream(encrypted); // create an ASN.1 input stream ASN1InputStream ain = new ASN1InputStream(bin); // read the whole sequence ASN1Sequence mainSequence = (ASN1Sequence) ain.readObject(); // check if it is an encrypted data DERObjectIdentifier mainIdentifier = (DERObjectIdentifier) mainSequence .getObjectAt(ASN1IDENTIFIER_ID); if (!mainIdentifier.equals(OID_ENCRYPTED_DATA)) { throw new CryptoException("Given data is not encrypted CMS."); } // parse the encrypted object DERTaggedObject encryptedObject = (DERTaggedObject) mainSequence.getObjectAt(ASN1CONTENT_ID); // parse the sequence containing the useful informations ASN1Sequence encryptedSequence = (ASN1Sequence) encryptedObject.getObject(); // create the content info object EncryptedContentInfo info = EncryptedContentInfo.getInstance(encryptedSequence .getObjectAt(ASN1CONTENT_ID)); return info; } catch (IOException e) { // if the main sequence can not be read from the stream an IOException would be thrown throw new CryptoException(e); } catch (ClassCastException e) { // if the parsing fails, a ClassCastException would be thrown throw new CryptoException(e); } catch (IllegalStateException e) { // if the parsing fails, also a IllegalStateException can be thrown throw new CryptoException(e); } }

这样我就能够解码给定的文本,识别真正的解密算法并提取使用的初始化向量和真正的解密数据来执行解密。

于 2011-05-30T08:54:37.280 回答
0

异常似乎直接来自您输入的密文长度。根据定义,CBC 输出整数个块,因此它应该给我们 8 的倍数......我现在要问的问题是, cryptlib到底在做什么?你能告诉我们你用来创建加密字符串的 cryptlib 代码吗?

于 2011-05-16T22:12:32.633 回答