Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 實現 URL 的加解密處理

URL 的加解密在資料傳輸中十分常見。以下示範如何以 Java 結合 MD5 摘要與 DESede(Triple DES)演算法,對資料進行加密與解密,並以 Base64 編碼承載密文。

一、加密

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);

加密流程說明:先以 MD5 對金鑰求摘要,再將 16 位元組的摘要拼接成 24 位元組,構造出 DESede 所需的金鑰;接著以 DESede/ECB/PKCS5Padding 加密原文,最後用 Base64 編碼得到可安全傳輸的密文字串。

二、解密

byte[] decodedBytes;
BASE64Decoder decoder = new BASE64Decoder();
decodedBytes = decoder.decodeBuffer(cipherText);

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] byteKeyMd5 = md.digest(decryptKey.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.DECRYPT_MODE, deskey);

byte[] plainTextBytes = cipher.doFinal(decodedBytes);
plainText = new String(plainTextBytes);

解密可視為加密的逆過程:先以 Base64 還原密文位元組,再以相同方式重建 DESede 金鑰,然後以 DECRYPT_MODE 還原出原始位元組,最終轉回字串。整個過程要求加解密雙方使用一致的金鑰與演算法參數。

Copyright © Linux教程網 All Rights Reserved