【发布时间】:2022-03-01 01:58:13
【问题描述】:
我有 C# 代码可以解密另一个应用程序传递的加密令牌。我不能改变这部分。 现在我正在用 java 编写一个应用程序,它将加密我的令牌,并将其传递给 C# 应用程序。
我无法将加密字符串与 java 代码匹配。任何帮助,将不胜感激。 谢谢。
C#代码
public class Crypto
{
private TripleDES DesInstance = null;
public Crypto(string key)
{
byte[] password = Encoding.GetEncoding(1252).GetBytes(key);
DesInstance = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, null);
DesInstance.IV = new byte[8];
DesInstance.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, DesInstance.IV);
}
public string Decrypt(string cipheredText)
{
byte[] cipherText = StringToByteArray(cipheredText);
string plainText = null;
ICryptoTransform transform = DesInstance.CreateDecryptor();
MemoryStream memStreamEncryptedData = new MemoryStream(cipherText, 0, cipherText.Length - 1);
CryptoStream encStream = new CryptoStream(memStreamEncryptedData, transform, CryptoStreamMode.Read);
using (StreamReader srDecrypt = new StreamReader(encStream, Encoding.GetEncoding(1252)))
{
plainText = srDecrypt.ReadToEnd();
}
return plainText;
}
private byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
}
Java 代码
public class TripleDes {
private static final String UNICODE_FORMAT = "UTF-8";
public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
private KeySpec ks;
private SecretKeyFactory skf;
private Cipher cipher;
byte[] arrayBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;
public TripleDes() throws Exception {
myEncryptionKey = "045e466ccc34a1f1688640d0441601b7ae2c";
myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
ks = new DESedeKeySpec(arrayBytes);
skf = SecretKeyFactory.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = skf.generateSecret(ks);
}
public String encrypt(String unencryptedString) {
String encryptedString = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
encryptedString = new String(Base64.encodeBase64(encryptedText));
} catch (Exception e) {
e.printStackTrace();
}
return encryptedString;
}
public String decrypt(String encryptedString) {
String decryptedText = null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText = Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText = new String(plainText);
} catch (Exception e) {
e.printStackTrace();
}
return decryptedText;
}
}
【问题讨论】:
-
myEncryptionKey是否与传递给Crypto构造函数的字符串相同? -
@JimRhodes 甚至不尝试实现
PasswordDeriveBytes是否重要?请注意,这基本上是 PBKDF1,但如果结果大于散列(在本例中为 SHA-1),则使用“特殊”Microsoft 代码对其进行扩展。特殊之处在于它完全不安全,应该直接替换。 -
C#代码没有使用MS扩展的基于PBKDF1的算法,而是MS CAPI的
CryptoDeriveKey()的算法。
标签: java c# encryption tripledes