本示例是用Java技术采用DES加密算法,对给定的信息进行加密,加密密钥为8位(其他长度的总是出错,还不知道为什么,希望高手给出解释),详细代码如下所示:
String info = "Hello,Jerry!Do you have your breakfast?";//明文 String secretKey = "jerryjjj";//加密密钥
//创建密钥对象 SecretKeySpec deskey = new SecretKeySpec(secretKey.getBytes(), 0, secretKey.getBytes().length, "DES"); // 获得加密类的实例,algorithm可取DES,DESeda等 Cipher c1 = Cipher.getInstance("DES"); // 初始化方式为加密 c1.init(Cipher.ENCRYPT_MODE, deskey); // 执行加密,得到加密后的字节 int len = info.getBytes().length; //这一步处理是为了应对不同长度的信息串 len=((len / 8)+1)*8; //加密后的密文长度为比明文长度大的最小的8的倍数 byte[] cipherByte = new byte[len]; c1.doFinal(info.getBytes(), 0, info.getBytes().length, cipherByte, 0);
//获得加密后的密文字符串
String cihper = byte2hex(cipherByte);
System.out.println(cipher);
|
阅读(1392) | 评论(0) | 转发(0) |