Answer the question
In order to leave comments, you need to log in
How to correctly transfer the salt from the client to the server and back when encrypting?
As a server I use ASP.NET WebApi 2.
As a client, a universal application on Windows 10.
NET.Framework 4.6 is used everywhere
. Data is sent via http.
For encryption I use PCLCrypto
https://github.com/aarnott/pclcrypto
Below is the class for encryption:
public static class Crypto
{
public static byte[] CreateSalt(uint lengthInBytes)
{
return WinRTCrypto.CryptographicBuffer.GenerateRandom(lengthInBytes);
}
public static byte[] CreateDerivedKey(string password, byte[] salt, int keyLengthInBytes = 32, int iterations = 10000)
{
byte[] key = NetFxCrypto.DeriveBytes.GetBytes(password, salt, iterations, keyLengthInBytes);
return key;
}
public static byte[] EncryptAes(string data, string password, byte[] salt)
{
byte[] key = CreateDerivedKey(password, salt);
ISymmetricKeyAlgorithmProvider aes = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesEcbPkcs7);
ICryptographicKey symetricKey = aes.CreateSymmetricKey(key);
var bytes = WinRTCrypto.CryptographicEngine.Encrypt(symetricKey, Encoding.UTF8.GetBytes(data));
return bytes;
}
public static string DecryptAes(byte[] data, string password, byte[] salt)
{
byte[] key = CreateDerivedKey(password, salt);
ISymmetricKeyAlgorithmProvider aes = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesEcbPkcs7);
ICryptographicKey symetricKey = aes.CreateSymmetricKey(key);
var bytes = WinRTCrypto.CryptographicEngine.Decrypt(symetricKey, data);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
}
var salt = Crypto.CreateSalt(16);
var bytes = Crypto.EncryptAes(data, pass, salt);
var str = Crypto.DecryptAes(bytes, pass, salt);
static byte[] GetBytes(string str)
{
var bytes = new byte[str.Length * sizeof(char)];
Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
var chars = new char[bytes.Length / sizeof(char)];
Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
Answer the question
In order to leave comments, you need to log in
The comment correctly says that the result may depend on the type of client / server architecture, and specifically on the byte
order You can check the byte order using BitConverter.IsLittleEndian
As for the idea itself, that is, standard for platform-independent serialization / deserialization of binary data: Base64 , ProtoBuf , BSON , etc.
In your case, it is better to use Base64, because it's fairly common, simple, and doesn't require additional dependencies. Look at the Convert.ToBase64String and Convert.FromBase64String methods
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question