【发布时间】:2018-12-18 00:52:15
【问题描述】:
我们有 java 库,它将使用带有密码的 AES 进行加密和解密,我们需要将其移植到 .NET。
这是我的 java 代码 -
import java.util.*;
import java.lang.*;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
class Rextester
{
public static void main(String args[])
{
byte[] encrypted = EncryptonToBytes("Hello");
System.out.println("Encrypted: " + encrypted); // Result --> Encrypted: [B@1c53fd30
String decrypted = DecryptionFromBytes(encrypted);
System.out.println("Decrypted: " + decrypted);
}
public static final byte[] EncryptonToBytes(String str)
{
byte[] result = null;
//Create SecretKey object from common secret key string mentioned in constants class
byte[] encoded = new BigInteger("728faf34b64cd55c8d1d500268026ffb", 16).toByteArray();
SecretKey secretKey = new SecretKeySpec(encoded, "AES");
Cipher cipher;
try {
//Cipher class object using AES as transformation
cipher = Cipher.getInstance("AES");
//Initialize cipher in encrypt mode along with secret key object created above.
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//Encrypt input string
result = cipher.doFinal(str.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
//Return null in case of any error
return result;
}
public static String DecryptionFromBytes(byte[] base64Data)
{
try {
//Create SecretKey object from common secret key string mentioned in constants class
byte[] encoded = new BigInteger("728faf34b64cd55c8d1d500268026ffb", 16).toByteArray();
SecretKey secretKey = new SecretKeySpec(encoded, "AES");
//Cipher class object using AES as transformation
Cipher cipher = Cipher.getInstance("AES");
//Initialize cipher in decrypt mode along with secret key object created above.
cipher.init(Cipher.DECRYPT_MODE, secretKey);
//Decrypt input byte array
byte[] decryptedByte = cipher.doFinal(base64Data);
//return decrypted input bytes as string
return (new String(decryptedByte));
} catch (Exception e) {
e.printStackTrace();
}
//return empty string if any error
return "";
}
}
我关注了下面的一些文章 -
- Using AES encryption in C#
- http://csharphelper.com/blog/2014/09/encrypt-or-decrypt-files-in-c/
- https://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt
- Cipher, Java encrypt, C# decrypt
- Password encryption/decryption code in .NET
- https://ourcodeworld.com/articles/read/471/how-to-encrypt-and-decrypt-files-using-the-aes-encryption-algorithm-in-c-sharp
- http://mjremijan.blogspot.com/2014/08/aes-encryption-between-java-and-c.html
但他们都没有给我想要的输出。我正在寻找的是 - 我的 java 和 .net 函数都应该给我相同的结果。 从上周开始,我一直在努力完成它,完全沮丧。非常感谢您的帮助。
【问题讨论】: