第一次使用java的DES加密

用了如下的方法使用des加密和解密,但解密后的结果和原来的结果不一致


package com.cjnetwork.ciphertool.aatest;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class TestDES {

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

byte[] rawData = new byte[]{3, 5, 7, 9, 1, 2, 3, 4};
printByte(rawData);

SecureRandom secureRandom = new SecureRandom();
DESKeySpec deskeySpec = new DESKeySpec(rawData);
SecretKey secretKey = SecretKeyFactory.getInstance("DES").generateSecret(deskeySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, secureRandom);

byte[] encrpytedData = cipher.update(rawData);
printByte(encrpytedData);

SecureRandom secureRandom2 = new SecureRandom();
DESKeySpec deskeySpec2 = new DESKeySpec(encrpytedData);
SecretKey secretKey2 = SecretKeyFactory.getInstance("DES").generateSecret(deskeySpec2);
Cipher cipher2 = Cipher.getInstance("DES");
cipher2.init(Cipher.DECRYPT_MODE, secretKey2, secureRandom2);

byte[] decryptedData = cipher.update(encrpytedData);
printByte(decryptedData);
}


private static void printByte(byte[] data){
for(int i = 0; i < data.length; i++){
System.out.print(data[i]);
if(i + 1 != data.length){
System.out.print(" ");
}
}
System.out.println();
}
}


发现问题如下:
des的使用不是如此使用,des加密解密中使用的密钥是成对出现的,在上述过程中,分别使用了2组密钥对,因此结果是不相关的,需要从相同的来源生成一对密钥,然后在加密解密的时候只是生成的cipher的模式是不同的,而且都是使用doFinal(byte[])方法加密和解密,update方法暂时不知道是做什么用处。

应该如此使用:

byte[] rawKeyData = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};//至少8个
DESKeySpec deskeySpec = new DESKeySpec(rawKey);
SecretKey secretKey = SecretKeyFactory.getInstance("DES").generateSecret(deskeySpec);

Cipher encryptCipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);

Cipher decryptCipher = Cipher.getInstance("DES");
decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);


如此你就有两个密钥了,一个encryptCipher,一个decryptCipher
一个用于加密数据,一个用于解密数据。
使用doFinal(byte[])方法加密和解密,update方法暂时不知道是做什么用处。


关于java的密钥问题,有几个常听到的名词
JCE:加密扩展即Java Cryptography Extension它是Sun的加密服务软件,包含了加密和密匙生成功能
JCA:Java Cryptography Architecture java的密钥体系结构
javax.crypto:jdk中自带的关于密钥的包
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值