I have a DLL in C# that encrypts and decrypts string texts (something basic), but now I need to implement the same encryption method in Java, so that some applications can encrypt data and send it to the library.
I can't modify the C# code, because it's already in production, but the Java don't, so please, any suggestion must be done at the Java side.
Basically I'm trying to implement the same C# encryption method in Java. Here are my C# codes:
NOTE: the passphrase, salt, etc. values obviously are just referential.
const string PassPhrase = "IhDyHz6bgQyS0Ff1/1s=";
const string SaltValue = "0A0Qvv09OXd3GsYHVrA=";
const string HashAlgorithm = "SHA1";
const int PasswordIterations = 3;
const string InitVector = "GjrlRZ6INgNckBqv";
const int KeySize = 256;
public static string Encrypt(string plainText)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(InitVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(SaltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(
PassPhrase,
saltValueBytes,
HashAlgorithm,
PasswordIterations);
byte[] keyBytes = password.GetBytes(KeySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
encryptor,
CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
return cipherText;
}
public static string Decrypt(string cipherText)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(InitVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(SaltValue);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(
PassPhrase,
saltValueBytes,
HashAlgorithm,
PasswordIterations);
byte[] keyBytes = password.GetBytes(KeySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream,
decryptor,
CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes,
0,
plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
string plainText = Encoding.UTF8.GetString(plainTextBytes,
0,
decryptedByteCount);
return plainText;
}
Here is my java code, it encrypts the data, but not at the same way as the C# encryption code, so when I try to decrypt it using the C# library it throws the exception: "Length of the data to decrypt is invalid"
static final String PassPhrase = "IhDyHz6bgQyS0Ff1/1s=";
static final String SaltValue = "0A0Qvv09OXd3GsYHVrA=";
static final String HashAlgorithm = "SHA1";
static final int PasswordIterations = 3;
static final String InitVector = "GjrlRZ6INgNckBqv";
static final int KeySize = 256;
public static String encrypt(String plainText)
{
char[] password = PassPhrase.toCharArray();
byte[] salt = SaltValue.getBytes();
byte[] iv = InitVector.getBytes();
byte[] ciphertext = new byte[0];
SecretKeyFactory factory;
try {
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, PasswordIterations, 256);
SecretKey tmp;
tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
//iv = params.getParameterSpec(IvParameterSpec.class).getIV();
ciphertext = cipher.doFinal(plainText.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//catch (InvalidParameterSpecException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
//}
catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Base64.encode(new String(ciphertext));
}
EDIT 1: I fixed the final byte array conversion to String in the Java code, as Jon Skeet suggested.
This is what's wrong, in the Java code:
return Base64.encode(ciphertext.toString());
You're calling toString() on the byte array, which will always give a string such as [B#3e25a5.
EDIT: Ooh, just noticed that you can change the Java side. Hooray.
Basically, you need to use a Base64 API which allows:
return Base64.encode(ciphertext);
I'm always disappointed in Base64 APIs which allow you to "encode" a string, to be honest... base64 fundamentally encodes binary data to text, and decodes text data to binary. Oh well...
Anyway, use this API (the encodeBytes method) if you need one which allows you to pass in a byte array.
I haven't checked over the actual encryption part in detail, but the C# code at least looks like it's doing the right thing in terms of encodings. It could do with using statements though :)
Here is a C# example, you need the IterationCount and PaddingMode.None
protected void Page_Load(object sender, EventArgs e)
{
string value = "";
string password = "";
string salt = "";
string iv = "";
byte[] vectorBytes = Convert.FromBase64String(Server.UrlDecode(iv));
byte[] cipherText = Convert.FromBase64String(Server.UrlDecode(value));
Rfc2898DeriveBytes key1 = new Rfc2898DeriveBytes(password, StringToByteArray(salt)); //same as PBKDF2WithHmacSHA1
key1.IterationCount = 32;
byte[] keyBytes = key1.GetBytes(16);
string Answer = DecryptDataAES(cipherText, keyBytes, vectorBytes); //vectorBytes is good
//litAnswer.Text = Answer;
}
public static string DecryptDataAES(byte[] cipherText, byte[] key, byte[] iv)
{
string plaintext = null;
using (Rijndael rijndael = Rijndael.Create())
{
rijndael.Key = key;
rijndael.IV = iv;
rijndael.Padding = PaddingMode.None;
ICryptoTransform decryptor = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length / 2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
}
return bytes;
}
Related
C#
public void start()
{
Constants.APIENCRYPTKEY = Convert.ToBase64String(Encoding.Default.GetBytes(Session(32)));
Constants.APIENCRYPTSALT = Convert.ToBase64String(Encoding.Default.GetBytes(Session(16)));
string results = EncryptService("start");
}
private static string Session(int length)
{
Random random = new Random();
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
public static string DecryptService(string value)
{
string message = value;
string password = Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTKEY));
SHA256 mySHA256 = SHA256Managed.Create();
byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(password));
byte[] iv = Encoding.ASCII.GetBytes(Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTSALT)));
string decrypted = DecryptString(message, key, iv);
return decrypted;
}
public static string DecryptString(string cipherText, byte[] key, byte[] iv)
{
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
encryptor.Key = key;
encryptor.IV = iv;
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform aesDecryptor = encryptor.CreateDecryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);
string plainText = String.Empty;
try
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] plainBytes = memoryStream.ToArray();
plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
}
finally
{
memoryStream.Close();
cryptoStream.Close();
}
return plainText;
}
public static string EncryptService(string value)
{
string message = value;
string password = Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTKEY));
SHA256 mySHA256 = SHA256Managed.Create();
byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(password));
byte[] iv = Encoding.ASCII.GetBytes(Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTSALT)));
string encrypted = EncryptString(message, key, iv);
int property = Int32.Parse((OnProgramStart.AID.Substring(0, 2)));
string final = encrypted + Security.Obfuscate(property);
return final;
}
public static string EncryptString(string plainText, byte[] key, byte[] iv)
{
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
encryptor.Key = key;
encryptor.IV = iv;
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
return cipherText;
}
This is what I got so far in PHP
function decrypt_string($msg='', $salt='', $key='')
{
$key = utf8_encode(base64_decode($key));
$key = hash('sha256', $key);
$salt = utf8_encode(base64_decode($salt));
$salt = EncodingASCII($salt);
$method = 'aes-256-cbc';
$msg = openssl_decrypt($msg, $method, $key, OPENSSL_RAW_DATA, $salt);
return $msg;
}
The encrypt and decrypt works perfect on c#, but I can't get it to decrypt on php. Haven't attempted to make the encrypt in php yet. My c# application calls on the php script with a encrypted data and needs to be decrypted on the php side then encrypted data sent back to the c# application.
I have got a string for you guys.
Normal string = nmrufETK
Encrypted string = ultYIi4GtHhb//Cl0J8wIg==
Here is the things that I know so far, the old decyrption method was :
public static List<string> hadibuloc = new List<string>();
Functions.hadibuloc.Add("OZt4nd8ZZpAEnZBdU3Z7");
Functions.hadibuloc.Add("fkheb1PFtPIKTi05Zpzz");
Functions.hadibuloc.Add("0kx96D8OzZ3rznUk4qyi");
Functions.hadibuloc.Add("TgAji9cqMALlhJV12elB");
Functions.hadibuloc.Add("0XQ3XXjUo3HTzzevUmDm");
Functions.hadibuloc.Add("F3Ib4qRHXDgQwoJyhWra");
Functions.hadibuloc.Add("eRWoJ0s1B0uln8fFgxqX");
Functions.hadibuloc.Add("iUE0FKl2Ntawpt6sbV7u");
Functions.hadibuloc.Add("me9fMa0WTreWRrmYpBh7");
Functions.hadibuloc.Add("kyJB0qCUq269fzREzRxD");
Functions.hadibuloc.Add("WnTufxOov40st4L6qZF9");
Functions.hadibuloc.Add("7csfQq3YunqM9ziygmw8");
Functions.hadibuloc.Add("EyqWVpgOvZkyJCAmlgCh");
Functions.hadibuloc.Add("D2RAYhyatrMYrZjLdlqL");
Functions.hadibuloc.Add("nSdcM6NAAyekiwYHQqZl");
Functions.hadibuloc.Add("B3RPgAHYEpwKsFCkrLSq");
Functions.hadibuloc.Add("JgQuRU88IQC5Z77JUTiD");
Functions.hadibuloc.Add("v57wd6YIJTGhettATB8L");
Functions.hadibuloc.Add("Qzc1nrxQwuIOMrGynhXu");
Functions.hadibuloc.Add("ad5AKkogV91AfmdNwkEO");
Functions.hadibuloc.Add("vaG2jNiDHa5p18hazzyZ");
Functions.hadibuloc.Add("BbYJbJOcX4w5F84nrWYl");
Functions.hadibuloc.Add("QGMq1ffFpBV64UpWeLCP");
Functions.hadibuloc.Add("lrLJqwoJGAuwmqA12MWR");
Functions.hadibuloc.Add("VFqyK09HS3920srKbBvp");
Functions.hadibuloc.Add("wVjVwspocrBWWAnFz53M");
Functions.hadibuloc.Add("oGMgDdEBpy8vHa5RZQHa");
Functions.hadibuloc.Add("BAUsGUgYBvi7tGMJRmy6");
Functions.hadibuloc.Add("l1nEhAHzWbRlGQeOi9pz");
Functions.hadibuloc.Add("PLpbqWSUnkAoLJam79cD");
Functions.hadibuloc.Add("SWbChkYzbfB0XKKcE1wb");
Functions.hadibuloc.Add("ZRlERlOLlbbW7l4u4SLB");
Functions.hadibuloc.Add("4FaDBRIw2bRkeqLALQwq");
Functions.hadibuloc.Add("Z3Yb3QdFgAbOUMD4TT2E");
Functions.hadibuloc.Add("0QjIrotDsTJrBMVOUGEx");
Functions.hadibuloc.Add("rrBABwOTnnjoZH81Y10w");
Functions.hadibuloc.Add("Ig8OIDYp7SaHel8gQhYE");
Functions.hadibuloc.Add("Zkcq9DLCmmMb2pvgsnox");
Functions.hadibuloc.Add("Ta9QRpW1vH3vYNaWDuaT");
Functions.hadibuloc.Add("I5B3gCvXSrgfg7aKdyJ8");
Functions.hadibuloc.Add("F5U7PteCDqjtT2YYMbte");
Functions.hadibuloc.Add("NOzV5qhSRxEmEwHGrjSv");
Functions.hadibuloc.Add("9Ocg4R5TAqIQLJVY9aJA");
Functions.hadibuloc.Add("AoXect0Wd914NAKW957w");
Functions.hadibuloc.Add("ebNIGbCQ5e4vRkoKQ4SN");
Functions.hadibuloc.Add("DyQb0qmcovqZS6xA5Nbq");
Functions.hadibuloc.Add("7HjmPVonDspqmixH2FrJ");
Functions.hadibuloc.Add("EqU8wj6HBrXi5nW9l16l");
Functions.hadibuloc.Add("NI85VXOjCS0dgtylMyt1");
Functions.hadibuloc.Add("zFjG4ZJbkzrZxPwW5C1P");
Functions.hadibuloc.Add("sqkTwAiMc5iMRvam2AHs");
Functions.hadibuloc.Add("Kd2XiFoFdCheMCsD5SNk");
Functions.hadibuloc.Add("2PcWLkcAiLOo4AcM1n6f");
Functions.hadibuloc.Add("fZKaPRgxgb6EGc9A4epo");
Functions.hadibuloc.Add("pJCNj8hiQYd0mSwAAlG9");
Functions.hadibuloc.Add("FHLEOcgR8nZkPETgIau7");
Functions.hadibuloc.Add("fP0IIV133SBrSAhcm2xL");
Functions.hadibuloc.Add("J7dYgJsix1trFydJBCiD");
Functions.hadibuloc.Add("kuy5ZNe3SKh6NNwKsusq");
Functions.hadibuloc.Add("yw35qZxwIPY4vAndktx3");
Functions.hadibuloc.Add("lFIn4TrpaXAL6TUXTfRa");
Functions.hadibuloc.Add("2ajBkzl7mSl08rm0m9qq");
Functions.hadibuloc.Add("rQiGJrCD2qOw2cbTrHdX");
Functions.hadibuloc.Add("08Gm5pOBmKQPIpWw7NIu");
Functions.hadibuloc.Add("WRjgeZMotIAmyiGalpt3");
Functions.hadibuloc.Add("rYy1MGiBLxfMBufX9IJn");
Functions.hadibuloc.Add("LIv4dk2eh1DbWmuP2Xao");
Functions.hadibuloc.Add("xeNNc12ef0pmgBs3rYpV");
Functions.hadibuloc.Add("6IcTB4F0MYf3XEvPZ3Pp");
Functions.hadibuloc.Add("4FEEfd1l5qNsoX7VPkiS");
Functions.hadibuloc.Add("0kGF2Rb8HKT4Spn41RW1");
Functions.hadibuloc.Add("HDEsDvrgokF0b5jgXJ3J");
Functions.hadibuloc.Add("iU1NeT7jYaN7HB8eNn9V");
Functions.hadibuloc.Add("NT4HJ9M77hkWK3TqaFRR");
Functions.hadibuloc.Add("GEFxqMf38desyg3wO1K4");
Functions.hadibuloc.Add("Zgwk37JrBl9o3JMeQtZA");
Functions.hadibuloc.Add("64YkqXguAr8AmWTNKQj3");
Functions.hadibuloc.Add("tGWLK6h9TPrSFSA4ZocS");
Functions.hadibuloc.Add("9yHnDOfweXcCXOp1chBx");
Functions.hadibuloc.Add("LTuAf0bPkFYrQ5TbMD6U");
Functions.hadibuloc.Add("M4k0pUF7P04bLHs6dJV1");
Functions.hadibuloc.Add("x5X0gVtjCe8GDrfOFsaX");
Functions.hadibuloc.Add("BrFjmwvJMKjmLg5mYWRQ");
Functions.hadibuloc.Add("4iAcBuNr58pP2gux67ud");
Functions.hadibuloc.Add("jLuuVi2la7KfxRNNecG5");
Functions.hadibuloc.Add("3QssdnIkbDrMcQWQ2lsb");
Functions.hadibuloc.Add("7wvkS2KuPwCOApEMJW2s");
Functions.hadibuloc.Add("1ZxJdP8JxP4PR1t4yE9D");
Functions.hadibuloc.Add("aFL5rH066RA3eLF6BSrm");
Functions.hadibuloc.Add("pAvKpwz4fc4lmtsbNjHO");
Functions.hadibuloc.Add("ukOhB5O7NxLMgyC0q1rb");
Functions.hadibuloc.Add("69qB4rzAA4BsCYfY3c74");
Functions.hadibuloc.Add("fKYNy6gkdPDyk0pTkkN2");
Functions.hadibuloc.Add("l0SPSH2CeMdpPAa6tVP8");
Functions.hadibuloc.Add("NQkNZKgSFEq8sDHUCLAf");
Functions.hadibuloc.Add("yzM5F818BdeRcC8pHNjB");
Functions.hadibuloc.Add("tj8hZFSq4blLgTdPMlv1");
Functions.hadibuloc.Add("wXP72vnkO9eLMslKSphJ");
Functions.hadibuloc.Add("hdtln0yAp9O2StGrXkZL");
Functions.hadibuloc.Add("Ujvws8KLRf7fyz1oo9Fm");
public static string Uzaksunucudangelenmetnicoz(string metin)
{
string result = "";
try
{
List<string> list = new List<string>();
list.Add("6MRVk2iHrsSWxY739uU6");
list.Add("JNEbV73AIVv01UI4cCN9");
list.Add("fRUzPptifIk7mYhAGuwq");
list.Add("4okJUC1Nv8hT2RjIOlDH");
list.Add("jWJjtopKxt27xbPUmigk");
list.Add("cQiqthahKNnbJXUsXNai");
list.Add("LrGUCKUxIKsbHEoGNoZB");
list.Add("j3UVDV6B5P3ZTewgLs1J");
list.Add("a864WixaWMit6RdbnowV");
list.Add("bLfWxqaXSEsa9uNoDY1z");
list.Add("aTwGuGAL1aDEYLqZdydm");
list.Add("fipquWXp6Fde1l1yoePJ");
list.Add("xEFesiTXtE8GNiJoPURP");
list.Add("z1rleac3uxRnrwrlZ47P");
list.Add("HnauZy36NMCbnKQpBvXy");
list.Add("LsenKihueSeUm5D3vyGm");
list.Add("fBAvk2yApQGD90wPmTuz");
list.Add("kL61T5rai5sq1fPDPQIG");
list.Add("u4lTisX4LxhTouLGiVqv");
list.Add("dhgB32wDm0PgUccGC7vi");
list.Add("pDMQv1GbeU2h3aOP2aFf");
list.Add("Z9tMsKaXoC9569dQWLoH");
list.Add("wwl9YoScNaklEk6lYBRk");
list.Add("61oIv3D0asY8qHcsMvvn");
list.Add("AcUgy8GNAKmUmsi1wJZ2");
list.Add("cxAIFZaLeEYooksNACUm");
list.Add("hXtoz3WI4WWcD15U1HVj");
list.Add("1xU1M828PODASWox3CWc");
list.Add("XGJ6H04SndlopxeuJR2X");
list.Add("7XsDr8tAklPAUhRwgS31");
list.Add("SyUH2DS12ObKTXYzapMm");
list.Add("eyRb3S2EOIfnfHJZImOr");
list.Add("x47P7emhboAYBbSGN9BP");
list.Add("u2hp1Lnq0dJWqh5CXwFx");
list.Add("2DwFQJGsQdd46liK6YfI");
list.Add("qzlgXi9wFVsevBVljM7P");
list.Add("7iaN5LVfWpes5IZtvNJs");
list.Add("BjTUTmlDb9Haj3iiL4H8");
list.Add("E0vZK3rAmSD5TJQYqo06");
list.Add("cV0nXoWnC2qfAF6ijKti");
list.Add("ZnXX4xjkWxyhVzAE5f4T");
list.Add("uiBq4ynA6zVpvYcLG3Rr");
list.Add("iQddCas3XU4Wg1kJd0VG");
list.Add("TbLVNp3vf1d3uVYpNA9V");
list.Add("S9VKQiW7fMONpIZLoiZp");
list.Add("782urFNgLyB4NsVMF5PL");
list.Add("d0FetEyv8Kcpb4xsq4WL");
list.Add("vDxNe5VujuZxfmVWFzDO");
list.Add("eqSfybAFoNRwaWjTwGKl");
list.Add("pme5Rz3bm3afIJUNvGao");
list.Add("5GYm7wSxmD2XTfa1fMW2");
list.Add("G4pMJhDsO95pIAL8cPmS");
list.Add("htdFa3r1vnR3YfHoj518");
list.Add("AVwD2PBtkLy2IC6WPG3x");
list.Add("PCbXpVgmU0psYRcRLhDj");
list.Add("aoHChiGFaFSa4fy5lVcY");
list.Add("nDGKEbbKdNn1qF7YziCT");
list.Add("g9Caz2rzK3BrZM9Yywnk");
list.Add("9MDd0QU1Wasw7PARMzfC");
list.Add("BDTGEK8nSErokxtpx5qI");
list.Add("kAoxMqmbts92s2SvjXCQ");
list.Add("tI2AMshUkr7NvwjWWMWK");
list.Add("wjwPea52QEF5XteTWTBR");
list.Add("6QcQXhY6YhfaBOof38X9");
list.Add("T3ztIItPddcqCa6l4W9q");
list.Add("fk61VH7gogvZqScilAjc");
list.Add("rNiGeeaesugz1EuIhlkA");
list.Add("MUo3726lbUu1noFFdNQL");
list.Add("hXh5Ojy9M2mhscBQIFsU");
list.Add("UOC2A4ql6K0FnExnuy5N");
list.Add("jgQBAXfvMZ4anhRJkrhw");
list.Add("BCaFEzbVQZDSDePt2aOK");
list.Add("WwK7FAI1M3P6iLHChuDe");
list.Add("UyQTMeFsYPFWPmwSsyAn");
list.Add("LCJI9dPxYZUIpbVOLRXa");
list.Add("AljvoFtljUvbetI2uAm8");
list.Add("J9dS4PNwjQY95ZJrWgZK");
list.Add("LNXcRGdEUfZoaFUxYvnz");
list.Add("9TGNyTWYec9O5j77yKH2");
list.Add("0VfAzTM1kSPW1AEPgUgy");
list.Add("oPPBTadoRQuryClE6Set");
list.Add("LK5Taw6rC5LIqD8XlMuw");
list.Add("zydeLNO5dDco6rcniPQo");
list.Add("qorqKozLU6AEK00sij17");
list.Add("em5FrXNJf7dlUrPmMZAb");
list.Add("XGhnM6PUAbF6rqnumKN6");
list.Add("xobFyWikgplryg4zJ71Y");
list.Add("r7xh75Hg3Q1tjzx01zlb");
list.Add("3cUXFakPJAzY8TlO1g6t");
list.Add("ZaM8ELOP57j8wvagTkgj");
list.Add("YZtR13683gxaYnfHt2m2");
list.Add("uXjIph0fYIQUApaDhswh");
list.Add("yDewQ1dWb39AKRszMl2x");
list.Add("8wf1DTnyLhDICzoppHex");
list.Add("ubO0rGOZpD4WMN1zZYMS");
list.Add("iXS26dUzA4NFOAwHgHyg");
list.Add("XOHZ5TOPuMF8YqqWRXb8");
list.Add("oJzOJ5zoZKA6wnHJcJNZ");
list.Add("rzWXMzAgaWwZ2POulBbU");
list.Add("g7LoA9c7fNTnBbTWPBPu");
list.Add("uVCH6x1GfXEkB561Lx61");
list.Add("BJruYhyvqBtXTvZk93ua");
list.Add("uCkfQp4gFBOzlZTM59kn");
list.Add("yZD9B59o92Eqmbe3mJG5");
list.Add("vgdoztnujq9BTPoiQaQP");
list.Add("jfyJazaJJ3HgyUCmbVhN");
list.Add("MoZTMDMVMg3pFE94Q0Hp");
list.Add("sSHRIeqtDRWRIl3hqA50");
list.Add("4Bz3N3tfDwkyckMoJjVO");
list.Add("hBS3Dk5CN2VpWRmtbaxa");
SHA256 sha = SHA256.Create();
byte[] key = sha.ComputeHash(Encoding.ASCII.GetBytes(list[6].Substring(6)));
byte[] iv = new byte[16];
sha.Dispose();
result = Functions.DecryptString(metin, key, iv);
}
catch
{
result = "undefined";
}
return result;
}
public static string DecryptString(string cipherText, byte[] key, byte[] iv)
{
Aes aes = Aes.Create();
aes.Mode = CipherMode.CBC;
byte[] array = new byte[32];
Array.Copy(key, 0, array, 0, 32);
aes.Key = array;
aes.IV = iv;
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform transform = aes.CreateDecryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
string result = string.Empty;
try
{
byte[] array2 = Convert.FromBase64String(cipherText);
cryptoStream.Write(array2, 0, array2.Length);
cryptoStream.FlushFinalBlock();
byte[] array3 = memoryStream.ToArray();
result = Encoding.ASCII.GetString(array3, 0, array3.Length);
}
finally
{
memoryStream.Close();
cryptoStream.Close();
}
return result;
}
And this was the old encrytion method :
public static string AES256Hash(string plaintext)
{
SHA256 sha = SHA256.Create();
byte[] key = sha.ComputeHash(Encoding.ASCII.GetBytes(Functions.hadibuloc[87].Substring(8)));
byte[] iv = new byte[16];
sha.Dispose();
return Functions.EncryptString(plaintext, key, iv);
}
public static string EncryptString(string plainText, byte[] key, byte[] iv)
{
Aes aes = Aes.Create();
aes.Mode = CipherMode.CBC;
byte[] array = new byte[32];
Array.Copy(key, 0, array, 0, 32);
aes.Key = array;
aes.IV = iv;
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform transform = aes.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
byte[] bytes = Encoding.ASCII.GetBytes(plainText);
cryptoStream.Write(bytes, 0, bytes.Length);
cryptoStream.FlushFinalBlock();
byte[] array2 = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(array2, 0, array2.Length);
}
But as I said these were old codes that used. And I think he used a method that similar to these. I want the method that he used to encrypt. My english is not good if theres and spelling or grammer mistake sorry for that if you didnt understand my question you feel free to ask again.
It will be impossible to determine an encryption algorithm without source code or some amount of reverse engineering. The old encryption uses AES256 in CBC mode, but that is obvious.
If you don't have access to the new code, then you probably shouldn't be attempting this anyways..
I encrypt password in postgres
and i want to decrypt it in c#, but two ways can not matching
.How can i do that?
private static byte[] TruncateHash(string key, int length)
{
SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
// Hash the key.
byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(key);
byte[] hash = sha1.ComputeHash(keyBytes);
// Truncate or pad the hash.
Array.Resize(ref hash, length);
return hash;
}
public static string EncryptString(string plaintext, string Passphrase)
{
TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();
// Initialize the crypto provider.
tripleDes.Key = TruncateHash(Passphrase, tripleDes.KeySize / 8);
tripleDes.IV = TruncateHash("", tripleDes.BlockSize / 8);
// Convert the plaintext string to a byte array.
byte[] plaintextBytes = System.Text.Encoding.Unicode.GetBytes(plaintext);
// Create the stream.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
// Create the encoder to write to the stream.
CryptoStream encStream = new CryptoStream(ms, tripleDes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
// Use the crypto stream to write the byte array to the stream.
encStream.Write(plaintextBytes, 0, plaintextBytes.Length);
encStream.FlushFinalBlock();
// Convert the encrypted stream to a printable string.
return Convert.ToBase64String(ms.ToArray());
}
public static string DecryptString(string encryptedtext, string Passphrase)
{
TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();
// Initialize the crypto provider.
tripleDes.Key = TruncateHash(Passphrase, tripleDes.KeySize / 8);
tripleDes.IV = TruncateHash("", tripleDes.BlockSize / 8);
// Convert the encrypted text string to a byte array.
byte[] encryptedBytes = Convert.FromBase64String(encryptedtext);
// Create the stream.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
// Create the decoder to write to the stream.
CryptoStream decStream = new CryptoStream(ms, tripleDes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
// Use the crypto stream to write the byte array to the stream.
decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
decStream.FlushFinalBlock();
// Convert the plaintext stream to a string.
return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
I found a way to encrypt in postgres using pgcrypto.
And below is encrypt and decrypt in postgres.
SELECT encode(encrypt_iv('ABCDE121212','Key123', '','3des'), 'base64');
select decrypt_iv(decode('jEI4V5q6h5/p12NRJm666g==','base64'),'Key123','','3des')
What's wrong in my code, c# and postgres can't not matching.
I want to keep c# code and change postgres code to matching
Source Url
Encrypt function:
public static String AES_encrypt(String input, string key, string Iv, int keyLength)
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = keyLength;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = mkey(key,keyLength);
aes.IV = mkey(Iv,128);
var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] xBuff = null;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
{
byte[] xXml = Encoding.UTF8.GetBytes(input);
cs.Write(xXml, 0, xXml.Length);
cs.FlushFinalBlock();
}
xBuff = ms.ToArray();
}
return Convert.ToBase64String(xBuff,Base64FormattingOptions.None);
}
Decrypt function:
public static String AES_decrypt(String Input, string key, string Iv, int keyLength)
{
try
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = keyLength;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = mkey(key,keyLength);
aes.IV = mkey(Iv,128);
var decrypt = aes.CreateDecryptor();
byte[] encryptedStr = Convert.FromBase64String(Input);
string Plain_Text;
using (var ms = new MemoryStream(encryptedStr))
{
using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
Plain_Text = reader.ReadToEnd();
}
}
}
return Plain_Text;
}
catch (Exception ex)
{
return null;
}
}
Helper function:
private static byte[] mkey(string skey, int keyLength)
{
int length = keyLength / 8;
byte[] key = Encoding.UTF8.GetBytes(skey);
byte[] k = GenerateEmptyArray(length);
for (int i = 0; i < key.Length; i++)
{
//k[i % 16] = (byte)(k[i % 16] ^ key[i]);
k[i] = key[i];
if(i == length-1)
break;
}
return k;
}
Variables:
input = "Hello World"
key = "NBJ42RKQ2vQoYFZO"
Iv = "j1C83921vHExVhVp"
keyLength = 128
Info about variables:
input - string that is not encrypted or encrypted. If it's encrypted it will be in Base64 format
key - Any Unicode character that will match the AES key size(in this example it's 128). I have written a function that will extract the specific length of characters and add them to a byte array
Code:
public static string PasswordFixer(string skey,int keyLength)
{
int length = keyLength / 8;
byte[] key = Encoding.UTF8.GetBytes(skey);
byte[] k = GenerateEmptyArray(length);
for (int i = 0; i < key.Length; i++)
{
k[i] = key[i];
if(i == length-1)
break;
}
return Encoding.UTF8.GetString(k);
}
Iv - it's always 128bit long meaning 16bytes. you can ignore Iv if you want, in PostgreSQL if you planing to use `encrypt` function then you can ignore the Iv by hard coding like this `aes.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };`
keylength-
This is the AES key length in this example we use 128bit meaning 16 bytes. whatever the characters that you use as the Key need to match the length of 16 bytes.
PostgreSQL
The equivalent SQL statement for the encryption and decryption is this
encrypt_iv,decrypt_iv
select convert_from(decrypt_iv(decode(tbl1.encrypted,'base64')::bytea ,'NBJ42RKQ2vQoYFZO','j1C83921vHExVhVp', 'aes-cbc/pad:pkcs'), 'UTF-8') as decrypted,tbl1.encrypted from (select encode(encrypt_iv('Hello World', 'NBJ42RKQ2vQoYFZO','j1C83921vHExVhVp', 'aes-cbc/pad:pkcs'), 'base64') as encrypted) as tbl1
encrypt,decrypt
select convert_from(decrypt(decode(tbl1.encrypted,'base64')::bytea ,'NBJ42RKQ2vQoYFZO', 'aes-cbc/pad:pkcs'), 'UTF-8') as decrypted,tbl1.encrypted from (select encode(encrypt('Hello World', 'NBJ42RKQ2vQoYFZO', 'aes-cbc/pad:pkcs'), 'base64') as encrypted) as tbl1
So, I am having an issue with decrypting the decoded base64 aes string. Is this possible? I wrote a small console program to work this out but no luck. Here is my example:
As depicted, I have successfully converted the base64 back the aes encrypted string, but when I try to decrypt it I get more junk. If a code snippet is need let me. Thank you all for your help :)
UPDATE: Code snippet for decrypting method
static void Main(string[] args)
{
string plainText;
string decrypted;
string decryptedFromB64EncodedDecoded;
string fromBase64ToEncryptedText;
string encryptedText;
string encryptedTextBase64;
byte[] encryptedBytes;
byte[] encryptedBytes2;
byte[] encryptedBytesBase64;
RijndaelManaged crypto = new RijndaelManaged();
UTF8Encoding UTF = new UTF8Encoding();
Console.WriteLine("Please put in the text to be encrypted.");
plainText = Console.ReadLine();
try
{
encryptedBytes = encrypt(plainText, crypto.Key, crypto.IV);
encryptedText = Encoding.ASCII.GetString(encryptedBytes);
//encryptedBytes2 = Encoding.ASCII.GetBytes(encryptedText);
encryptedTextBase64 = toBase64String(encryptedText);
encryptedBytesBase64 = fromBase64String(encryptedTextBase64);
fromBase64ToEncryptedText = Encoding.ASCII.GetString(encryptedBytesBase64);
encryptedBytes2 = Encoding.ASCII.GetBytes(fromBase64ToEncryptedText);
decrypted = decrypt(encryptedBytes, crypto.Key, crypto.IV);
decryptedFromB64EncodedDecoded = decrypt(encryptedBytes2, crypto.Key, crypto.IV);
Console.WriteLine("Start: {0}", plainText);
Console.WriteLine("Encrypted: {0}", encryptedText);
Console.WriteLine("Encrypted Base64: {0}", encryptedTextBase64);
Console.WriteLine("From Base64 To AES Encypted Text: {0}", fromBase64ToEncryptedText);
Console.WriteLine("Decrypted: {0}", decrypted);
Console.WriteLine("Decrypted From Encode and then Decode Base64 Text: {0}", decryptedFromB64EncodedDecoded);
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
Console.ReadLine();
}
public static string decrypt (byte[] textToDecrypt, byte[] key, byte[] IV)
{
RijndaelManaged crypto = new RijndaelManaged();
MemoryStream stream = new MemoryStream(textToDecrypt) ;
ICryptoTransform decryptor = null;
CryptoStream cryptoStream = null;
StreamReader readStream = null;
string text = string.Empty;
try
{
crypto.Key = key;
crypto.IV = IV;
crypto.Padding = PaddingMode.None;
decryptor = crypto.CreateDecryptor(crypto.Key, crypto.IV);
cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read);
//cryptoStream.Read(textToDecrypt, 0, textToDecrypt.Length);
readStream = new StreamReader(cryptoStream);
text = readStream.ReadToEnd();
cryptoStream.Close();
byte[] decodedValue = stream.ToArray();
return text;
}
catch (Exception)
{
throw;
}
finally
{
if (crypto != null)
{
crypto.Clear();
}
stream.Flush();
stream.Close();
}
}
public static byte[] encrypt(string text, byte[] key, byte[] IV)
{
RijndaelManaged crypto = null;
MemoryStream stream = null;
//ICryptoTransform is used to perform the actual decryption vs encryption, hash function are a version crypto transforms
ICryptoTransform encryptor = null;
//CryptoStream allows for encrption in memory
CryptoStream cryptoStream = null;
UTF8Encoding byteTransform = new UTF8Encoding();
byte[] bytes = byteTransform.GetBytes(text);
try
{
crypto = new RijndaelManaged();
crypto.Key = key;
crypto.IV = IV;
stream = new MemoryStream();
encryptor = crypto.CreateEncryptor(crypto.Key, crypto.IV);
cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(bytes, 0, bytes.Length);
}
catch (Exception)
{
throw;
}
finally
{
if (crypto != null)
{
crypto.Clear();
}
cryptoStream.Close();
}
return stream.ToArray();
}
public static string toBase64String(string value)
{
UTF8Encoding UTF = new UTF8Encoding();
byte[] myarray = UTF.GetBytes(value);
return Convert.ToBase64String(myarray);
}
public static byte[] fromBase64String(string mystring)
{
//UTF8Encoding UTF = new UTF8Encoding();
//byte[] myarray = UTF.GetBytes(value);
return Convert.FromBase64String(mystring);
}
I don't know how you're decrypting but before you decrypt, you should convert the base 64 string to a byte array before sending it into the decryption.
byte[] encryptedStringAsBytes = Convert.FromBase64String(base64EncodedEncryptedValue);
Then with the byte array you can pass to the CryptoStream via a MemoryStream.
UPDATE
I believe the issue is how you're setting up your streams
using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
{
rijndaelManaged.Padding = paddingMode;
rijndaelManaged.Key = key;
rijndaelManaged.IV = initVector;
MemoryStream memoryStream = null;
try
{
memoryStream = new MemoryStream(valueToDecrypt);
using (ICryptoTransform cryptoTransform = rijndaelManaged.CreateDecryptor())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read))
{
using (StreamReader streamReader = new StreamReader(cryptoStream))
{
return streamReader.ReadToEnd();
}
}
}
}
finally
{
if (memoryStream != null)
memoryStream.Dispose();
}
}
UPDATE 2
This is how you should basically perform the steps.
To encrypt
Encode your plain text string using the Encoding.GetBytes(stringToEncrypt)
pass the byte[] into the crypto API (via memory stream, etc.)
get the bytes from the encrypted stream and encode the results as Base64
To Decrypt (do the reverse)
Convert the base64 encoded string to bytes using Convert.FromBase64String(base64EncodedEncryptedValue)
pass that byte array into your decryption function above
Try:
encryptedBytes2 = Encoding.ASCII.GetBytes(encryptedText);
Based on your comment. The bytes are just that bytes, so in order to decrypt the ciphertext you need to undo any encoding or series of encodings you have done.
If you really want to go from Encrypted Bytes -> Base64String -> ASCII string -> then decrypt that ASCII string? you would need to base64 decode the ascii string then convert that string to bytes using
Encoding.ASCII.GetBytes(yourdecodedstring);
Note that base 64 decoding is not the same as using Convert.FromBase84String.
I've searched a lot before asking, but none of the ideas I found work in my problem so here's my problem :
In C# the code (which I cannot change because it is from another application) for encryption is detailed after.
I have to decrypt the encrypted token in Java but nothing works so far, can anyone help ?
For 1. C# code :
static public string Encrypt3DES(string toEncrypt, string SecKey, string IV){
byte[] keyArray;
try
{
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(SecKey));
hashmd5.Clear();
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.CBC;
tdes.Padding = PaddingMode.PKCS7;
tdes.IV = UTF8Encoding.UTF8.GetBytes(IV);
ICryptoTransform cTransform = tdes.CreateEncryptor();
//transform the specified region of bytes array to resultArray
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
//Return the encrypted data into unreadable string format
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
catch (Exception e) { return string.Empty; }
}
For 2 Java code that does not work :
public class TripleDesTest {
private KeySpec keySpec;
private SecretKey key;
private IvParameterSpec iv;
public TripleDesTest() {
String keyString = "THE_KEY";
String ivString = "THE_IV";
try {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest(Base64.decodeBase64(keyString.getBytes("UTF-8")));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
keySpec = new DESedeKeySpec(keyBytes);
key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
iv = new IvParameterSpec(ivString.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
public String decrypt(String value) {
try {
Cipher dcipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");
dcipher.init(Cipher.DECRYPT_MODE, key, iv);
if (value == null)
return null;
// Decode base64 to get bytes
byte[] dec = Base64.decodeBase64(value.getBytes("UTF-8"));
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using UTF-8
return new String(utf8, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Here is the solution to the problem (I finally was able to solve this myself) :
In Java, replace
final byte[] digestOfPassword = md.digest(Base64.decodeBase64(keyString.getBytes("UTF-8")));`
with :
final byte[] digestOfPassword = md.digest(keyString.getBytes("UTF-8"));
Because on the C# side, no Base64 is used for the key :
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(SecKey));