openssl java des_在Java中使用openssl加密

我有一个传统的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个字节.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值