2018-06-17 18:21:52 +00:00
|
|
|
using System;
|
|
|
|
using System.Security.Cryptography;
|
|
|
|
|
2019-04-14 17:17:26 +00:00
|
|
|
namespace XTSSharp
|
|
|
|
{
|
|
|
|
public class Xts
|
|
|
|
{
|
2018-07-08 05:21:58 +00:00
|
|
|
private readonly SymmetricAlgorithm _key1;
|
|
|
|
private readonly SymmetricAlgorithm _key2;
|
2018-06-17 18:21:52 +00:00
|
|
|
|
2019-04-14 17:17:26 +00:00
|
|
|
protected Xts(Func<SymmetricAlgorithm> create, byte[] key1, byte[] key2)
|
|
|
|
{
|
|
|
|
if (create == null)
|
|
|
|
{
|
2018-07-08 05:21:58 +00:00
|
|
|
throw new ArgumentNullException("create");
|
|
|
|
}
|
2019-04-14 17:17:26 +00:00
|
|
|
if (key1 == null)
|
|
|
|
{
|
2018-07-08 05:21:58 +00:00
|
|
|
throw new ArgumentNullException("key1");
|
|
|
|
}
|
2019-04-14 17:17:26 +00:00
|
|
|
if (key2 == null)
|
|
|
|
{
|
2018-07-08 05:21:58 +00:00
|
|
|
throw new ArgumentNullException("key2");
|
|
|
|
}
|
|
|
|
_key1 = create();
|
|
|
|
_key2 = create();
|
2019-04-14 17:17:26 +00:00
|
|
|
if (key1.Length != key2.Length)
|
|
|
|
{
|
2018-07-08 05:21:58 +00:00
|
|
|
throw new ArgumentException("Key lengths don't match");
|
|
|
|
}
|
|
|
|
_key1.KeySize = key1.Length * 8;
|
|
|
|
_key2.KeySize = key2.Length * 8;
|
|
|
|
_key1.Key = key1;
|
|
|
|
_key2.Key = key2;
|
|
|
|
_key1.Mode = CipherMode.ECB;
|
|
|
|
_key2.Mode = CipherMode.ECB;
|
|
|
|
_key1.Padding = PaddingMode.None;
|
|
|
|
_key2.Padding = PaddingMode.None;
|
|
|
|
_key1.BlockSize = 128;
|
|
|
|
_key2.BlockSize = 128;
|
|
|
|
}
|
2018-06-17 18:21:52 +00:00
|
|
|
|
2019-04-14 17:17:26 +00:00
|
|
|
public XtsCryptoTransform CreateEncryptor()
|
|
|
|
{
|
2018-07-08 05:21:58 +00:00
|
|
|
return new XtsCryptoTransform(_key1.CreateEncryptor(), _key2.CreateEncryptor(), false);
|
|
|
|
}
|
2018-06-17 18:21:52 +00:00
|
|
|
|
2019-04-14 17:17:26 +00:00
|
|
|
public XtsCryptoTransform CreateDecryptor()
|
|
|
|
{
|
2018-07-08 05:21:58 +00:00
|
|
|
return new XtsCryptoTransform(_key1.CreateDecryptor(), _key2.CreateEncryptor(), true);
|
|
|
|
}
|
2018-06-17 18:21:52 +00:00
|
|
|
|
2019-04-14 17:17:26 +00:00
|
|
|
protected static byte[] VerifyKey(int expectedSize, byte[] key)
|
|
|
|
{
|
|
|
|
if (key == null)
|
|
|
|
{
|
2018-07-08 05:21:58 +00:00
|
|
|
throw new ArgumentNullException("key");
|
|
|
|
}
|
2019-04-14 17:17:26 +00:00
|
|
|
if (key.Length * 8 != expectedSize)
|
|
|
|
{
|
2018-07-08 05:21:58 +00:00
|
|
|
throw new ArgumentException($"Expected key length of {expectedSize} bits, got {key.Length * 8}");
|
|
|
|
}
|
|
|
|
return key;
|
|
|
|
}
|
|
|
|
}
|
2018-06-17 18:21:52 +00:00
|
|
|
}
|