两个Java加密解密例子java 加密解密 示例:http://rian.iteye.com/blog/196031
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 |
Java代码 import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.Key; import java.security.MessageDigest; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; public class Demo { public static void main(String args[]) { String password = "administrator"; try { Demo.PrivEncrypt(password,"t.obj"); } catch (Exception e) { e.printStackTrace(); } } /** * * @param oldStr * 要加密的串 * @param keyFile * 私有key所在的文件路径 * @throws Exception */ public static void PrivEncrypt(String oldStr,String keyFile) throws Exception { System.out.println("原始:"+oldStr); byte[] plainText = oldStr.getBytes("GBK"); Key key = getPriveKey(keyFile); // 获得一个私鈅加密类Cipher,ECB是加密方式,PKCS5Padding是填充方法 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key);// 使用私鈅加密 byte[] cipherText = cipher.doFinal(plainText); System.out.println("加密:"+new String(cipherText, "UTF8")); cipher.init(Cipher.DECRYPT_MODE, key);// 使用私钥解密 byte[] newPlainText = cipher.doFinal(cipherText); System.out.println("解密:"+new String(newPlainText, "UTF8")); } // 把Key 写到文件中:生成一个私有Key对象,保存在文件中 public static void setPriveKey(String file) { FileOutputStream fos; try { fos = new FileOutputStream(file); KeyGenerator keyGen = KeyGenerator.getInstance("DES"); keyGen.init(128); Key key = keyGen.generateKey();// 生成私钥Key ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(key); oos.close(); } catch (Exception e1) { e1.printStackTrace(); } } // 从文件中读Key:客户端可以根据管理员提供的私钥Key文件提取Key对象 public static Key getPriveKey(String file) throws Exception { FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); Key key = (Key) ois.readObject(); return key; } } /* 运行结果: * 原始:administrator * 加密:!Y????I?? ??R;? * 解密:administrator */ |
DES加密、解密字符串算法:http://www.icnote.com/des-encrypt/