Java DES 加密 解密 示例1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
package com.techzero.des; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; /** * DESTest.java * * @author Techzero * @Email techzero@163.com * @Time 2013-12-12 下午2:22:58 */ public class DESTest { /** * @param args */ public static void main(String[] args) { String content = "DESTest"; // 密码长度必须是8的倍数 String password = "12345678"; System.out.println("密 钥:" + password); System.out.println("加密前:" + content); byte[] result = encrypt(content, password); System.out.println("加密后:" + new String(result)); String decryResult = decrypt(result, password); System.out.println("解密后:" + decryResult); } /** * 加密 * * @param content * 待加密内容 * @param key * 加密的密钥 * @return */ public static byte[] encrypt(String content, String key) { try { SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, securekey, random); byte[] result = cipher.doFinal(content.getBytes()); return result; } catch (Throwable e) { e.printStackTrace(); } return null; } /** * 解密 * * @param content * 待解密内容 * @param key * 解密的密钥 * @return */ public static String decrypt(byte[] content, String key) { try { SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, securekey, random); byte[] result = cipher.doFinal(content); return new String(result); } catch (Throwable e) { e.printStackTrace(); } return null; } } |
&nb…