Created
April 21, 2016 09:21
-
-
Save zhekaby/11e1e0f41211535bf0e82f24157ab7e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AesProvider : ISymetricProvider | |
{ | |
private readonly RijndaelManaged _sa = new RijndaelManaged() | |
{ | |
Mode = CipherMode.CBC | |
}; | |
private const int SymmetricKeyLength = 32; | |
public byte[] Encrypt(byte[] bytes, byte[] key) | |
{ | |
var iv = ScaleVector(key, 16); | |
if (key.Length != SymmetricKeyLength) key = ScaleVector(key, SymmetricKeyLength); | |
using (var encryptor = _sa.CreateEncryptor(key, iv)) | |
using (var memoryStream = new MemoryStream()) | |
{ | |
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) | |
{ | |
cryptoStream.Write(bytes, 0, bytes.Length); | |
} | |
return memoryStream.ToArray(); | |
} | |
} | |
public byte[] Decrypt(byte[] bytes, byte[] key) | |
{ | |
var iv = ScaleVector(key, 16); | |
using (var decryptor = _sa.CreateDecryptor(key, iv)) | |
using (var memoryStream = new MemoryStream()) | |
{ | |
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write)) | |
{ | |
cryptoStream.Write(bytes, 0, bytes.Length); | |
} | |
return memoryStream.ToArray(); | |
} | |
} | |
private static byte[] ScaleVector(IReadOnlyList<byte> vector, int newLength) | |
{ | |
if (vector == null) throw new ArgumentNullException(); | |
if (vector.Count < 1) throw new ArgumentException("Key too short"); | |
var result = new byte[newLength]; | |
var multiplier = (newLength << 16) / vector.Count; | |
for (var i = 0; i < newLength; i++) | |
{ | |
var m = i * multiplier; | |
result[i] = (byte)(vector[m >> 16] ^ (byte)m); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment