|
| 1 | +import javax.crypto.Cipher; |
| 2 | +import javax.crypto.KeyGenerator; |
| 3 | +import javax.crypto.SecretKey; |
| 4 | + |
| 5 | +public class DESEncrypt { |
| 6 | + public static void main(String args[]) |
| 7 | + { |
| 8 | + String codeStringBegin="Sunny Liu"; //要加密的明文 |
| 9 | + String codeStringEnd=null; //加密后的密文 |
| 10 | + String decodeString=null; //密文解密后得到的明文 |
| 11 | + String cipherType = "DESede"; //加密算法类型,可设置为DES、DESede、AES等字符串 |
| 12 | + int keyLength = 112; //设置密钥长度 |
| 13 | + try |
| 14 | + { |
| 15 | + //获取密钥生成器 |
| 16 | + KeyGenerator keyGen=KeyGenerator.getInstance(cipherType); |
| 17 | + //初始化密钥生成器,不同的加密算法其密钥长度可能不同 |
| 18 | + keyGen.init(keyLength); |
| 19 | + //生成密钥 |
| 20 | + SecretKey key=keyGen.generateKey(); |
| 21 | + |
| 22 | + //得到密钥字节码 |
| 23 | + byte[] keyByte=key.getEncoded(); |
| 24 | + //输出密钥的字节码 |
| 25 | + System.out.println("密钥是:"); |
| 26 | + for(int i=0;i<keyByte.length;i++) |
| 27 | + { |
| 28 | + System.out.print(keyByte[i]+","); |
| 29 | + } |
| 30 | + System.out.println(""); |
| 31 | + //创建密码器 |
| 32 | + Cipher cp=Cipher.getInstance(cipherType); |
| 33 | + //初始化密码器 |
| 34 | + cp.init(Cipher.ENCRYPT_MODE,key); |
| 35 | + System.out.println("要加密的字符串是:"+ codeStringBegin); |
| 36 | + byte[] codeStringByte=codeStringBegin.getBytes("UTF8"); |
| 37 | + System.out.println("要加密的字符串对应的字节码是:"); |
| 38 | + for(int i=0;i<codeStringByte.length;i++) |
| 39 | + { |
| 40 | + System.out.print(codeStringByte[i]+","); |
| 41 | + } |
| 42 | + System.out.println(""); |
| 43 | + //开始加密 |
| 44 | + byte[] codeStringByteEnd=cp.doFinal(codeStringByte); |
| 45 | + System.out.println("加密后的字符串对应的字节码是:"); |
| 46 | + for(int i=0;i<codeStringByteEnd.length;i++) |
| 47 | + { |
| 48 | + System.out.print(codeStringByteEnd[i]+","); |
| 49 | + } |
| 50 | + System.out.println(""); |
| 51 | + codeStringEnd=new String(codeStringByteEnd); |
| 52 | + System.out.println("加密后的字符串是:" + codeStringEnd); |
| 53 | + System.out.println(""); |
| 54 | + //重新初始化密码器 |
| 55 | + cp.init(Cipher.DECRYPT_MODE,key); |
| 56 | + //开始解密 |
| 57 | + byte[] decodeStringByteEnd=cp.doFinal(codeStringByteEnd); |
| 58 | + System.out.println("解密后的字符串对应的字节码是:"); |
| 59 | + for(int i=0;i<decodeStringByteEnd.length;i++) |
| 60 | + { |
| 61 | + System.out.print(decodeStringByteEnd[i]+","); |
| 62 | + } |
| 63 | + System.out.println(""); |
| 64 | + decodeString=new String(decodeStringByteEnd); |
| 65 | + System.out.println("解密后的字符串是:" + decodeString); |
| 66 | + System.out.println(""); |
| 67 | + } |
| 68 | + catch(Exception e) |
| 69 | + { |
| 70 | + e.printStackTrace(); |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | + |
0 commit comments