-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAsciiXorCipher.cs
40 lines (32 loc) · 1005 Bytes
/
AsciiXorCipher.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
using System;
using System.Composition;
using System.Text;
namespace Science.Cryptography.Ciphers.Specialized;
/// <summary>
/// Represents the XOR cipher.
/// </summary>
[Export("ASCII-XOR", typeof(IKeyedCipher<>))]
public class AsciiXorCipher : ReciprocalKeyedCipher<byte[]>
{
private static Encoding Encoding = Encoding.ASCII;
protected override void Crypt(ReadOnlySpan<char> input, Span<char> output, byte[] key, out int written)
{
if (key.Length == 0)
{
throw new ArgumentException("Key can't be zero-length.", nameof(key));
}
if (output.Length < input.Length)
{
throw new ArgumentException("Size of output buffer is insufficient.", nameof(output));
}
// prepare buffer
var length = input.Length;
Span<byte> inputBytes = stackalloc byte[length];
Encoding.GetBytes(input, inputBytes);
Span<byte> outputBytes = stackalloc byte[length];
// crypt
BinaryXor.Xor(inputBytes, outputBytes, key);
// decode
written = Encoding.GetChars(outputBytes, output);
}
}