gpt4 book ai didi

java - 使用 Java 解码 cryptlib 编码文本(不使用 cryptlib)

转载 作者:行者123 更新时间:2023-12-01 15:51:06 27 4
gpt4 key购买 nike

你好。

首先:我是 stackOverflow 和我正在谈论的主题的新手......
我试图避免使用 cryptlib我的 Java 应用程序中用于 TripleDES 加密的库(现在我使用 AES - 为了确保向下兼容性,我还希望能够解码使用 cryptlib 库创建但不使用 JNI 的字符串)。
但到目前为止,我尝试过的所有方法都对我不起作用。

配置:
算法: TripleDES
模式: CBC
格式: CRYPT_FORMAT_CRYPTLIB
key 的大小为 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 native”格式)-我在网上找不到任何有关它的描述...

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

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

我也尝试了不同的填充,但我总是以这两个异常(exception)之一结束:

    javax.crypto.IllegalBlockSizeException:数据 block 大小未对齐javax.crypto.IllegalBlockSizeException:最后一个 block 解密未完成

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

编辑:以下是加密代码 (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:相比之下,它与描述的实现相同in this mailing list .
但我想用 Java 对其进行解码...

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

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

最佳答案

我终于明白了。
经过调试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());<p></p>

<pre><code> 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);
}
}
}
</code></pre>


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

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

关于java - 使用 Java 解码 cryptlib 编码文本(不使用 cryptlib),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6020648/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com