1.加密
Java代碼
- 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);
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代碼
- 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);