参考
http://baike.baidu.com/view/350958.htm
http://blog.163.com/zhqh43@126/blog/static/4043302720093276344788/
背景
最近由于公司项目的需要,最近研究了3DES算法运用,我的公司有一个合作的公司,提供webservice接口,是C#写的,用到3DES加密算法,C#代码以下:
public static string Encrypt3DES(string a_strString, string a_strKey) { TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(a_strKey); DES.Mode = CipherMode.ECB; ICryptoTransform DESEncrypt = DES.CreateEncryptor(); byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(a_strString); return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); }
public static string Decrypt3DES(string a_strString, string a_strKey) { TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(a_strKey); DES.Mode = CipherMode.ECB; DES.Padding = System.Security.Cryptography.PaddingMode.PKCS7; ICryptoTransform DESDecrypt = DES.CreateDecryptor(); string result = ""; try { byte[] Buffer = Convert.FromBase64String(a_strString); result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); } catch (Exception e) { } return result; }
解法
直接使用公司框架中的3DES算法类,代码如下:
package com.cn.crypt.implement;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.log4j.Logger;
/**
* <p>
* Title: 3DES加密算法实