we have java library which will do encryption and decryption using AES with Password, which we need to port to .NET.
Here is my java code -
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 "";
}
}
I followed some of the articles below -
- 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
But none of them gave me desired output. What I'm looking for is - both my java and .net functions should give me same result. From last one week I'm trying to get it done, totally frustrated. Your help will be much appreciated.