-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathHexEncoder.cs
73 lines (61 loc) · 1.65 KB
/
HexEncoder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Composition;
using System.Text;
namespace Science.Cryptography.Ciphers.Specialized;
[Export("Hex", typeof(ICipher))]
public class HexEncoder : ICipher
{
public HexEncoder(Encoding encoding)
{
Encoding = encoding;
}
public HexEncoder()
: this(Encoding.UTF8)
{ }
public Encoding Encoding { get; }
public int MaxOutputCharactersPerInputCharacter => Encoding.GetMaxByteCount(1) * 2;
public void Encrypt(ReadOnlySpan<char> plaintext, Span<char> ciphertext, out int written)
{
var count = Encoding.GetByteCount(plaintext);
Span<byte> buffer = stackalloc byte[count];
Encoding.GetBytes(plaintext, buffer);
var result = Convert.ToHexString(buffer); // TODO: optimize string allocation
result.CopyTo(ciphertext);
written = result.Length;
}
public void Decrypt(ReadOnlySpan<char> ciphertext, Span<char> plaintext, out int written)
{
int start = 0, end = 0;
var writtenPosition = 0;
for (int i = 0; i < ciphertext.Length; i++)
{
var ch = ciphertext[i];
if (ch is (>= 'a' and <= 'f') or (>= '0' and <= '9') or (>= 'A' and <= 'F'))
{
if (start == end)
{
start = i;
}
end = i + 1;
}
else
{
if (start < end && (end - start) % 2 == 0)
{
var span = ciphertext[start..end];
var bytes = Convert.FromHexString(span);
writtenPosition += Encoding.GetChars(bytes, plaintext);
}
plaintext[writtenPosition++] = ch;
start = end = 0;
}
}
if (start < end && (end - start) % 2 == 0)
{
var span = ciphertext[start..end];
var bytes = Convert.FromHexString(span);
writtenPosition += Encoding.GetChars(bytes, plaintext);
}
written = writtenPosition;
}
}