forked from sshnet/SSH.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAesGcmCipher.BclImpl.cs
More file actions
62 lines (53 loc) · 2.42 KB
/
AesGcmCipher.BclImpl.cs
File metadata and controls
62 lines (53 loc) · 2.42 KB
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
#if !NETSTANDARD
using System;
using System.Security.Cryptography;
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Transport;
namespace Renci.SshNet.Security.Cryptography.Ciphers
{
internal partial class AesGcmCipher
{
private sealed class BclImpl : Impl
{
private readonly AesGcm _aesGcm;
private readonly byte[] _nonce;
public BclImpl(byte[] key, byte[] nonce)
{
_aesGcm = new AesGcm(key, TagSizeInBytes);
_nonce = nonce;
}
public override void Encrypt(byte[] input, int plainTextOffset, int plainTextLength, int associatedDataOffset, int associatedDataLength, byte[] output, int cipherTextOffset)
{
var cipherTextLength = plainTextLength;
var plainText = new ReadOnlySpan<byte>(input, plainTextOffset, plainTextLength);
var cipherText = new Span<byte>(output, cipherTextOffset, cipherTextLength);
var tag = new Span<byte>(output, cipherTextOffset + cipherTextLength, TagSizeInBytes);
var associatedData = new ReadOnlySpan<byte>(input, associatedDataOffset, associatedDataLength);
_aesGcm.Encrypt(_nonce, plainText, cipherText, tag, associatedData);
}
public override void Decrypt(byte[] input, int cipherTextOffset, int cipherTextLength, int associatedDataOffset, int associatedDataLength, byte[] output, int plainTextOffset)
{
var cipherText = new ReadOnlySpan<byte>(input, cipherTextOffset, cipherTextLength);
var tag = new ReadOnlySpan<byte>(input, cipherTextOffset + cipherTextLength, TagSizeInBytes);
var associatedData = new ReadOnlySpan<byte>(input, associatedDataOffset, associatedDataLength);
try
{
_aesGcm.Decrypt(_nonce, cipherText, tag, output.AsSpan(plainTextOffset), associatedData);
}
catch (AuthenticationTagMismatchException ex)
{
throw new SshConnectionException("MAC error", DisconnectReason.MacError, ex);
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_aesGcm.Dispose();
}
}
}
}
}
#endif