0

こんにちは。

まず第一に、私はstackOverflowと私が話している主題に不慣れです... JavaアプリケーションでTripleDES暗号化にcryptlib
ライブラリを 使用しないようにしようとしています(現在、AESを使用しています-確実にするために下位互換性 JNI を使用せずに cryptlib ライブラリで作成された文字列をデコードできるようにしたい)。 しかし、私が今試したことはどれもうまくいきませんでした。

構成:
アルゴリズム: 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);

さまざまなパディングも試しましたが、常に次の 2 つの例外のいずれかで終了します。

  • 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 );
}

EDIT 2:比較すると、このメーリングリストで 説明されているのと同じ実装です。
しかし、Javaでデコードしたい...

編集 3: 問題は、暗号化されたデータが cryptlib に含まれていることだと思います (コードに見られるように)。

編集 4: 問題がエンベロープであることはわかっています。cryptlib は、作成された暗号化コンテキストのセッション キーを使用して、復号化されたデータを 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 に答える