I have a method used to convert a String into an encoded String with a key and a salt in C# that I am trying to create an equivalent for in Java.
The C# method is as follows:
public static string Encrypt<T>(string Value, string Key, string Salt) where T : SymmetricAlgorithm, new()
{
DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Key, Encoding.Unicode.GetBytes(Salt));
SymmetricAlgorithm algorithm = new T();
byte[] keyBytes = deriveBytes.GetBytes(algorithm.KeySize >> 3);
byte[] ivBytes = deriveBytes.GetBytes(algorithm.BlockSize >> 3);
ICryptoTransform transform = algorithm.CreateEncryptor(keyBytes, ivBytes);
using (MemoryStream buffer = new MemoryStream())
{
using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
{
writer.Write(Value);
}
}
return Convert.ToBase64String(buffer.ToArray());
}
}
I have tried many different solutions throughout SO and all over the web with no avail. I even have a sample:
value("YourId|YourFacId")
,
key("6JxI1HOSg7KQj4fJ1Xb3L1T6AVdLZLBAPFSqOjh2UoA=")
,
salt("FPSJxiSMpAavjKqyGvVe1A==")
These all get sent to the above method and come back with the return string of:
"Y5w4A3pDZwTcq+FGyqUMO/mZSr6hSst8qiac9zDbfso9FQQbdTDsKnkKDT7SHl4y"
.
I have yet to find anything in SO that matches my issue, so I am looking for help here. Any leads would be appreciated. Thanks.
The attempted link to the other question showed me nothing that I haven't already seen. There are no passwords to deal with in my example. Here is one of my many failed attempts at this:
private String encrypt(String user) throws Exception
{
Cipher deCipher;
Cipher enCipher;
SecretKeySpec key;
IvParameterSpec ivSpec;
String plainKey = "6JxI1HOSg7KQj4fJ1Xb3L1T6AVdLZLBAPFSqOjh2UoA=";
String salt = "FPSJxiSMpAavjKqyGvVe1A==";
String result = "";
ivSpec = new IvParameterSpec(salt.getBytes());
key = new SecretKeySpec(plainkey.getBytes(), "AES");
enCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] input = convertToByteArray(user);
enCipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
return new String(enCipher.doFinal(input).toString());
}