DES的java实现小记

package com.des;

import java.security.SecureRandom;

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

public class DES {


public static byte[] encrypto(byte input[], byte key[])
throws Exception{
byte plainData[];
int len = (input.length / 8 + (input.length % 8 != 0 ? 1 : 0)) * 8;
plainData = new byte[len];
System.arraycopy(input, 0, plainData, 0, input.length);
SecureRandom sr;
DESKeySpec dks;
SecretKeyFactory keyFactory;
sr = new SecureRandom();
dks = new DESKeySpec(key);
keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(dks);
Cipher cipher = null;
cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(1, secretKey, sr);

byte encryptedData[];
encryptedData = cipher.doFinal(plainData);

return encryptedData;
}


public static byte[] decrypto(byte input[], byte key[])
throws Exception
{
SecretKeyFactory keyFactory = null;
keyFactory = SecretKeyFactory.getInstance("DES");
javax.crypto.SecretKey secretKey = null;
secretKey = keyFactory.generateSecret(new DESKeySpec(key));
Cipher cipher = null;
cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(2, secretKey);
byte decryptedData[];
decryptedData = cipher.doFinal(input);
return decryptedData;
}

public static void main(String... args) throws Exception{
String key="0808080808080808";
byte[] realkey=fromHex(key);
byte[] afterDes=encrypto("aaaaaaaaaa".getBytes(),realkey);
System.out.println(toHex(afterDes));

byte[] desBack=decrypto(afterDes,realkey);
System.out.println(new String(desBack));
}









public static final byte[] fromHex(String b)
{
char data[] = b.toCharArray();
int l = data.length;
byte out[] = new byte[l >> 1];
int i = 0;
for(int j = 0; j < l;)
{
int f = Character.digit(data[j++], 16) << 4;
f |= Character.digit(data[j++], 16);
out[i] = (byte)(f & 0xff);
i++;
}

return out;
}

public static final String toHex(byte b[])
{
char buf[] = new char[b.length * 2];
int j;
for(int i = j = 0; i < b.length; i++)
{
int k = b[i];
buf[j++] = hex[k >>> 4 & 0xf];
buf[j++] = hex[k & 0xf];
}

return new String(buf);
}

private static final char hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'
};

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值