我在這裏有一個棘手的情況。我有用C#編寫的Web服務,它返回用下面描述的方法加密的JSON內容。這個Web服務被Java客戶端使用,但我無法在客戶端解密我的字符串,我嘗試了幾個使用DES算法的Java函數的Java示例,但沒有運氣,因爲我總是得到這個錯誤:如何在Java客戶端使用apache.commons.codec Base64解密字符串(用.NET加密)?
java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.decodeBase64
(我的環境是Eclipse的,jdk1.6.0_26,Android的2.1update模擬器)
請幫助!
我的C#的功能是:
/// <summary>
///
/// </summary>
/// <param name="stringToEncrypt"></param>
/// <returns></returns>
public static string Encrypt(string stringToEncrypt)
{
try
{
const string key1 = "MY KEY HERE";
byte[] iv = { Convert.ToByte("1"), Convert.ToByte("4"), Convert.ToByte("6"), Convert.ToByte("8"), Convert.ToByte("0"), Convert.ToByte("2"), Convert.ToByte("4"), Convert.ToByte("8") };
byte[] key = Encoding.UTF8.GetBytes(key1);
var des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
var ms = new MemoryStream();
var cs = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception ex)
{
Logger.Write(new ExceptionLogEntry(ex.ToString()));
}
return null;
}
/// <summary>
///
/// </summary>
/// <param name="stringToDecrypt"></param>
/// <returns></returns>
public static string Decrypt(string stringToDecrypt)
{
try
{
const string key1 = "MY KEY HERE";
byte[] iv = { Convert.ToByte("1"), Convert.ToByte("4"), Convert.ToByte("6"), Convert.ToByte("8"), Convert.ToByte("0"), Convert.ToByte("2"), Convert.ToByte("4"), Convert.ToByte("8") };
byte[] key = Encoding.UTF8.GetBytes(key1);
var des = new DESCryptoServiceProvider();
byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt);
var ms = new MemoryStream();
var cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
var encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch(Exception ex)
{
Logger.Write(new ExceptionLogEntry(ex.ToString()));
return "-1";
}
}
使用公地編解碼器1.5.jar我的Java函數是:
KeySpec ks = new DESKeySpec("MY KEY HERE".getBytes("UTF-8"));
SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(ks);
IvParameterSpec iv = new IvParameterSpec(Hex.decodeHex("1234567890ABCDEF".toCharArray()));
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] decoded = cipher.doFinal(Base64.decodeBase64("MY ENCRYPTED STRING HERE"));
Log.e(TAG, "DECODED->" + new String(decoded, "UTF-8"));
但我總是得到這個錯誤:
07-05 04:48:20.822: ERROR/AndroidRuntime(1270): java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.decodeBase64
嗨,喬恩,其實我已經嘗試了幾個版本的Apache庫(我沒有預料到來自Apache的東西會崩潰),我會嘗試Android的base64類。謝謝! – Jafet
@Jafet:這不是方法本身的失敗 - 而是虛擬機無法找到*方法。 –
我分享了我對這個問題的最終解決方案,轉到我的博客:http://jafetsanchez.com/post/7562162652/rijndael-on-c-and-java – Jafet