我已经实现了 AES 256 加密方法,并且在 Java 中运行良好,如下所示!
private static final byte[] IV = {
0, 2, 4, 8, 16, 32, 64, 127,
127, 64, 32, 16, 8, 4, 2, 0
};
//actual encryption over here
private static byte[] encrypt(byte[] raw, byte[] clear) throws
Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = null;
if(isIVUsedForCrypto) {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(IV));
}
else
{
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
}
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
从上述方法返回的字节数组最终使用以下方法转换为十六进制字符串toHex
方法。
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
所以使用Java AES 256加密代码的最终结果是一个十六进制字符串。
现在对于 Qt 部分,
QByteArray IV("0, 2, 4, 8, 16, 32, 64, 127,127, 64, 32, 16, 8, 4, 2, 0");
QString encrypt(QByteArray r, const QString &password)
{
const char *sample = r.data();
string plain = password.toStdString();
string ciphertext;
// Generate Cipher, Key, and CBC
byte key[ AES::MAX_KEYLENGTH ], iv[ AES::BLOCKSIZE ];
StringSource( reinterpret_cast<const char *>(sample), true,
new HashFilter(*(new SHA256), new ArraySink(key, AES::MAX_KEYLENGTH)) );
memset( iv, 0x00, AES::BLOCKSIZE );
CBC_Mode<AES>::Encryption Encryptor( key, sizeof(key), iv );
StringSource( plain, true, new StreamTransformationFilter( Encryptor,
new HexEncoder(new StringSink( ciphertext ) ) ) );
return QString::fromStdString(ciphertext);
}
从 main 方法中我调用上面的函数
QString encrypted = encrypt(result, "test");
其中“结果”是QByteArray
我将其传递给加密,就像在 java 中所做的那样。
Java 和 Qt 中的字节数组的获取方式相同。我已经证实了这一点。
我的问题
Qt 的加密逻辑尤其在某个地方失败了,因为HEX
通过 Java 和 Qt 获得的结果不匹配。
谁能告诉我 Qt 部分做错了什么。我没有使用吗IV
or the QByteArray
result
正确吗?