C#
其中
provider.Mode加密為CBC
provider.Padding為PKCS7
string data="-1";
byte[] rgbKey = {69, 70, 67, 49, 56, 49, 69, 70};
byte[] rgbIV = {54, 57, 51, 69, 52, 48, 55, 70};
MemoryStream ms = new MemoryStream();
CryptoStream encStream = new CryptoStream(ms, provider.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(encStream);
sw.Write(data);
sw.Flush();
encStream.FlushFinalBlock();
sw.Flush();
byte[] bufferb = ms.ToArray();
String buffer = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
算出來的buffer值rLrYBUc04hM=,
bufferb
[0] 172 byte
[1] 186 byte
[2] 216 byte
[3] 5 byte
[4] 71 byte
[5] 52 byte
[6] 226 byte
[7] 19 byte
下面為我轉為java的代碼,3個變量值同上面
public static String encrypt(String data,byte[] rgbKey, byte[] rgbIV) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(rgbKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(rgbIV);
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] datadd=data.getBytes("ASCII");
byte[] bytes = cipher.doFinal(datadd);
return new String(bytes,"ASCII");
}
算出來的結果是���G4�,bytes為[-84, -70, -40, 5, 71, 52, -30, 19]
java結果是錯的。
求大神幫查看下java哪裡地方寫錯了,謝謝。
java最後一句改成
return Base64.encodeBase64String(bytes);
就和C#一致
編碼方式不一致。就是手機和PC機用java加密出來的還不一致呢。
把數據轉換成base64編碼後再做加密解密。