歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java處理url加解密

Java處理url加解密

日期:2017/3/1 10:34:51   编辑:Linux編程
1.加密
Java代碼
  1. MessageDigest md = MessageDigest.getInstance("MD5");
  2. byte[] byteKeyMd5 = md.digest(encryptKey.getBytes());
  3. byte[] byteKey = new byte[24];
  4. System.arraycopy(byteKeyMd5, 0, byteKey, 0, 16);
  5. System.arraycopy(byteKeyMd5, 0, byteKey, 16, 8);
  6. Key deskey = null;
  7. DESedeKeySpec spec = new DESedeKeySpec(byteKey);
  8. SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
  9. deskey = keyfactory.generateSecret(spec);
  10. Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
  11. cipher.init(Cipher.ENCRYPT_MODE, deskey);
  12. byte[] encryptedBytes = cipher.doFinal(source.getBytes("UTF-8"));
  13. BASE64Encoder encoder = new BASE64Encoder();
  14. encryptedString = encoder.encode(encryptedBytes);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] byteKeyMd5 = md.digest(encryptKey.getBytes());

byte[] byteKey = new byte[24];
System.arraycopy(byteKeyMd5, 0, byteKey, 0, 16); 
System.arraycopy(byteKeyMd5, 0, byteKey, 16, 8); 

Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(byteKey);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, deskey);
byte[] encryptedBytes = cipher.doFinal(source.getBytes("UTF-8"));

BASE64Encoder encoder = new BASE64Encoder();
encryptedString = encoder.encode(encryptedBytes);


2.解密
Java代碼
  1. byte[] decodedBytes;
  2. BASE64Decoder decoder = new BASE64Decoder();
  3. decodedBytes = decoder.decodeBuffer(cipherText);
  4. MessageDigest md = MessageDigest.getInstance("MD5");
  5. byte[] byteKeyMd5 = md.digest(decryptKey.getBytes());
  6. byte[] byteKey = new byte[24];
  7. System.arraycopy(byteKeyMd5, 0, byteKey, 0, 16);
  8. System.arraycopy(byteKeyMd5, 0, byteKey, 16, 8);
  9. Key deskey = null;
  10. DESedeKeySpec spec = new DESedeKeySpec(byteKey);
  11. SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
  12. deskey = keyfactory.generateSecret(spec);
  13. Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
  14. cipher.init(Cipher.DECRYPT_MODE, deskey);
  15. byte[] plainTextBytes = cipher.doFinal(decodedBytes);
  16. plainText = new String(plainTextBytes);
Copyright © Linux教程網 All Rights Reserved