java 与c des_Java和C/C++进行DES/AES密文传输

本来觉得DES、AES这种流行加密算法,使用起来应该很简单。但研究后发现有两个变数:

1)分块的方式。加密是逐块进行的。分块方法有:CBC、ECB、CFB……

2)padding的方式。当数据的位数不及块的大小时,需要填充。填充方式有:NoPadding、PKCS5Padding……

如果加解密端采用不同的分块方式或padding方式,即使都是采用DES/AES算法,同样无法解密成功。上次需要C端和Java端进行密文传输,就跪在这一点上(那时候没时间研究)。

参考文章:Java AES算法和openssl配对 ,主要通过其了解openssl里比较高级的EVP系列API(其默认padding和java一样都是PKCS5Padding),节约了搜索时间。

贴代码了,以下代码测试通过了。Java和C++均可以正确解密对方的密文。

约定:分块和padding采用Java默认的 ECB + PKCS5Padding。

加密程序,输入是"src.txt"文件(加密无需纯文本,只是为了可读性),输出保存在"enc.bin"文件。

解码程序,输入是"enc.bin"文件,输出保存在"dec.txt"文件。

------------------------------------------

DES:

Java加密代码:

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.security.GeneralSecurityException;

import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

public class DesEnc {

public static byte[] desEncrypt(byte[] source, byte rawKeyData[])

throws GeneralSecurityException {

// 处理密钥

SecretKeySpec key = new SecretKeySpec(rawKeyData, "DES");

// 加密

Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, key);

return cipher.doFinal(source);

}

public static void main(String[] args) throws Exception {

// DES算法要求密鈅64位(8字节)

byte rawKeyData[] = "hellodes".getBytes("UTF-8");

// 读取文件内容(为了简单忽略错误处理)

File file = new File("src.txt");

byte[] source = new byte[(int) file.length()];

FileInputStream is = new FileInputStream(file);

is.read(source, 0, (int) file.length());

is.close();

// 加密

byte[] enc = desEncrypt(source, rawKeyData);

System.out.println("desEncrypt:" + source.length + "->" + enc.length);

// 输出到文件

FileOutputStream os = new FileOutputStream(new File("enc.bin"));

os.write(enc, 0, enc.length);

os.close();

}

}

Java解密代码:

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.security.GeneralSecurityException;

import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

public class DesDec {

public static byte[] desDecrypt(byte[] data, byte rawKeyData[])

throws GeneralSecurityException {

// 处理密钥

SecretKeySpec key = new SecretKeySpec(rawKeyData, "DES");

// 解密

Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

cipher.init(Cipher.DECRYPT_MODE, key);</

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值