【加密方法】:
采用DES对称加密算法,使用字符串“hnzt”生成加密的密钥
则组合的字符串为:851-2110599902&ZIQI&SONG&HKG&CN&1503560275539&24
加密后为:
af5a8b0e4680161606b7a72de89295733e05f8e4aec1866056f2850df1e2578bc6bd35f2003534e15a271a5bb03876d047cc1c5c0c2e1913
加密的JAVA代码如下,为什么会报错
package com.test;
import java.math.BigInteger;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.junit.Test;
/**
- 对称加密DES算法
- @author Administrator
-
/
public class DESTest {
/* 算法名称 /
static final String ALGORITHM = "DES";
/ 算法名称/加密模式/填充方式 **/
static final String CIPHER_ALGORITHM = "DES/ECB/pkcs5Padding";/** 密钥,getBytes的长度必须大于等于8 **/
// static final String SECRET_KEY = "!@#$%^&*";
static final String SECRET_KEY = "hnzt";@Test
public void test() throws Exception {
String data = "851-2110599902&ZIQI&SONG&HKG&CN&1503560275539&24";
//加密
String hex = encryption(data);
System.out.println(hex);System.out.println("-----------------------------------------"); // 解密 String origin = decryption(hex); System.out.println(origin);
}
/**
- 加密,返回16进制的字符串
- @param data
- @return
- @throws Exception
*/
private static String encryption(String data) throws Exception{
// 创建密钥
DESKeySpec desKeySpec = new DESKeySpec(SECRET_KEY.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
// 加密
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] bs = cipher.doFinal(data.getBytes("UTF-8"));
// 编码成16进制字符串
BigInteger bi = new BigInteger(1, bs);
return bi.toString(16); }
/**
- 解密
- @param hex
- @return
- @throws Exception
*/
private static String decryption(String hex) throws Exception {
// 解码16进制字符串
BigInteger bi = new BigInteger(hex, 16);
byte[] bs = bi.toByteArray();// 该数组包含此 BigInteger 的二进制补码表示形式。
byte[] originBs = new byte[bs.length - 1];
byte[] target = bs;
if (bs[0] == 0) {
System.out.println("去补码...");
System.arraycopy(bs, 1, originBs, 0, originBs.length); // 去掉补码
target = originBs;
}
// 创建密钥
DESKeySpec desKeySpec = new DESKeySpec(SECRET_KEY.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
// 解密
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptionBs = cipher.doFinal(target);
return new String(decryptionBs, "UTF-8");
}
}
而网上却可以,我代码写错了吗?