C#和Java DES加密值是不相同的 [英] C# and Java DES Encryption value are not identical
问题描述
我想在加密C#和Java相同的数据。但是,如果我的数据是超过7个字节然后Java和C#加密值是不相同的。我坚持要弄明白。
I am trying to encrypt same data in C# and Java. but if my data is more than 7 bytes then java and C# encrypted value are not identical. i am stuck to figure it out.
-
输入1: 结果
Java输出: FrOzOp / 2Io8 = 的结果
C#输出: FrOzOp / 2Io8 = 的
输入2:< STRONG> ABC 结果
J: H9A / ahl8K7I = 的结果$ b $#BC: H9A / ahl8K7I = 的
input 2: abc
j : H9A/ahl8K7I=
c#: H9A/ahl8K7I=
输入3: AAAAAAAA (问题)结果
J: Gxl7e0aWPd7j6l7uIEuMxA == 的结果$ b $#BC: Gxl7e0aWPd7sf1xR6hK4VQ == 的
input 3: aaaaaaaa (Problem)
j : Gxl7e0aWPd7j6l7uIEuMxA==
c#: Gxl7e0aWPd7sf1xR6hK4VQ==
在这里是我实现C#和Java方法。
C#代码:
here is my implementation of C# and Java methods. C# code:
public String saltTxt = "12345678";
public String Encrypt(String txt)
{
byte[] data = Encrypt(Encoding.UTF8.GetBytes(txt));
DESCryptoServiceProvider alg = new DESCryptoServiceProvider();
alg.Key = Encoding.UTF8.GetBytes(saltTxt.ToCharArray(), 0, cprovider.KeySize / 8);
alg.IV = new byte[8];
MemoryStream ms = new MemoryStream();
CryptoStream stem = new CryptoStream( ms, cprovider.CreateEncryptor(),CryptoStreamMode.Write);
stem.Write(txt, 0, txt.Length);
stem.FlushFinalBlock();
data = ms.ToArray();
return Convert.ToBase64String(data);
}
Java代码:
Java Code:
public String saltTxt = "12345678";
public String Encrypt(String str) {
try {
KeySpec myKey = new DESKeySpec(saltTxt.getBytes("UTF8"));
SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(myKey);
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
byte[] data = str.getBytes("UTF8");
byte[] crypt = ecipher.doFinal(data);
return new BASE64Encoder().encode(crypt);
} catch (Exception ex) {
}
return null;
}
期待您的回复。
looking forward for your response.
推荐答案
这个问题是在加密模式
。
SunJCE提供使用 ECB
作为默认模式,和 PKCS5Padding
为DES,DES-EDE和河豚密码默认的填充方案。 ( JCA文件)
SunJCE provider uses
ECB
as the default mode, andPKCS5Padding
as the default padding scheme for DES, DES-EDE and Blowfish ciphers. (JCA Doc)
和
在净
,对称算法的默认操作模式为 CipherMode.CBC
并默认填充是<强> PaddingMode.PKCS7
。 ( msdn..SymmetricAlgorithm )
In
.Net
, The default operation mode for the symmetric algorithm isCipherMode.CBC
and default padding isPaddingMode.PKCS7
. (msdn..SymmetricAlgorithm)
以下更改解决问题。
// in C#
DESCryptoServiceProvider alg = new DESCryptoServiceProvider();
alg.Mode = CipherMode.ECB; // specified
或
// in java
chiper = Cipher.getInstance("DES/CBC/PKCS5Padding");
不要在两侧改变。
don't change in both side.
这篇关于C#和Java DES加密值是不相同的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!