import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Hex;
public class ImoocDes {
public static void main (String [] args) {
ImoocDes imoocDes = new ImoocDes();
imoocDes.jdkDes("imooc security des");
}
public void jdkDes(String password) {
try {
//生成key
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
SecretKey secretKey = keyGenerator.generateKey();
byte [] bytKey = secretKey.getEncoded();
//key转换
DESKeySpec dESKeySpec = new DESKeySpec(bytKey);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");//参数指定加密方式
Key secretKey1 = secretKeyFactory.generateSecret(dESKeySpec);
//加密
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey1);
byte[] result = cipher.doFinal(password.getBytes());
System.out.println("jdk:" + Hex.encodeHexString(result));
//解密
cipher.init(Cipher.ENCRYPT_MODE, secretKey1);
result = cipher.doFinal(result);
System.out.println("jdk:" + new String(result));
} catch (Exception e) {
e.printStackTrace();
}
}
}
上面的代码都是按照老师的代码写的遇到了两个问题请大家帮忙解答一下1
问题1多次运行时加密的结果不一样这样正常吗
问题2解密的时候为什么解密结果一直是乱码
两次运行结果如下
第一次运行
jdk:b2f7b3a368cc58fb16e9c3fc3980c9da08cd09670b05e47d
jdk:>|V'bC(mA4ѝp öd
第二次运行
jdk:ac91a46c660ce3170281f64dc17489756ad8e15169fda33d
jdk:C 03H