|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | +using System.Security.Cryptography; |
| 4 | +using System.Text; |
| 5 | + |
| 6 | +namespace LibSample |
| 7 | +{ |
| 8 | + class AesEncryptionTest |
| 9 | + { |
| 10 | + public void Run() => AesLayerEncryptDecrypt(); |
| 11 | + |
| 12 | + private void AesLayerEncryptDecrypt() |
| 13 | + { |
| 14 | + var keyGen = RandomNumberGenerator.Create(); |
| 15 | + byte[] key = new byte[AesEncryptLayer.KeySizeInBytes]; |
| 16 | + keyGen.GetBytes(key); |
| 17 | + const string testData = "This text is long enough to need multiple blocks to encrypt"; |
| 18 | + |
| 19 | + var outboudLayer = new AesEncryptLayer(key); |
| 20 | + byte[] outbound = Encoding.ASCII.GetBytes(testData); |
| 21 | + int lengthOfPacket = outbound.Length; |
| 22 | + int start = 0; |
| 23 | + int length = outbound.Length; |
| 24 | + outboudLayer.ProcessOutBoundPacket(ref outbound, ref start, ref length); |
| 25 | + |
| 26 | + int minLenth = lengthOfPacket + AesEncryptLayer.BlockSizeInBytes; |
| 27 | + int maxLength = lengthOfPacket + outboudLayer.ExtraPacketSizeForLayer; |
| 28 | + if (length < minLenth || length > maxLength) |
| 29 | + { |
| 30 | + throw new Exception("Packet length out of bounds"); |
| 31 | + } |
| 32 | + |
| 33 | + var inboundLayer = new AesEncryptLayer(key); |
| 34 | + //Copy array so we dont read and write to same array |
| 35 | + byte[] inboundData = new byte[outbound.Length]; |
| 36 | + outbound.CopyTo(inboundData, 0); |
| 37 | + inboundLayer.ProcessInboundPacket(ref inboundData, ref length); |
| 38 | + |
| 39 | + Console.WriteLine(Encoding.ASCII.GetString(inboundData, 0, length)); |
| 40 | + byte[] expectedPlaintext = Encoding.ASCII.GetBytes(testData); |
| 41 | + |
| 42 | + var isEqualLength = expectedPlaintext.Length == length; |
| 43 | + var areContentEqual = expectedPlaintext.SequenceEqual(inboundData); |
| 44 | + if (isEqualLength && areContentEqual) |
| 45 | + { |
| 46 | + Console.WriteLine("Test complete"); |
| 47 | + } |
| 48 | + else |
| 49 | + { |
| 50 | + throw new Exception("Test failed, decrypted data not equal to original"); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments