我有一个传统的C模块,它使用openssl库提供加密/解密(DES加密).我正在尝试将该代码转换为
java,我不想依赖DLL,JNI等…
C代码看起来像:
des_string_to_key(reinterpret_cast(key1), &initkey);
des_string_to_key(reinterpret_cast(key2), &key);
key_sched(&key, ks);
// ...
des_ncbc_encrypt(reinterpret_cast(tmp.c_str()),
reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey,
DES_ENCRYPT);
return base64(reinterpret_cast(encrypted_buffer), strlen(encrypted_buffer));
Java代码如下所示:
Cipher ecipher;
try {
ecipher = Cipher.getInstance("DES");
SecretKeySpec keySpec = new SecretKeySpec(key, "DES");
ecipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] utf8 = password.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
catch {
// ...
}
所以我可以很容易地在Java中进行DES加密,但是如何使用完全不同的方法获得与上述代码相同的结果?让我烦恼的是,C版本使用2个密钥,而Java版本只使用1个密钥.
在CBC模式下关于DES的答案非常令人满意,但我还不能让它工作.
以下是有关原始代码的更多详细信息:
unsigned char key1 [10] = {0};
unsigned char key2 [50] = {0};
int i;
for (i=0;i<8;i++)
key1[i] = 31+int((i*sqrt((double)i*5)))%100;
key1[9]=0;
for (i=0;i<48;i++)
key2[i] = 31+int((i*i*sqrt((double)i*2)))%100;
key2[49]=0;
...
// Initialize encrypted buffer
memset(encrypted_buffer, 0, sizeof(encrypted_buffer));
// Add begin Text and End Text to the encrypted message
std::string input;
const char beginText = 2;
const char endText = 3;
input.append(1,beginText);
input.append(bufferToEncrypt);
input.append(1,endText);
// Add padding
tmp.assign(desPad(input));
des_ncbc_encrypt(reinterpret_cast(tmp.c_str()),
reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey,
DES_ENCRYPT);
...
从我所读到的,密钥应该是56(或64,我不清楚)位长,但这里它长48个字节.