forked from RevenantX/LiteNetLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetKeyExchange.cs
More file actions
78 lines (64 loc) · 1.92 KB
/
NetKeyExchange.cs
File metadata and controls
78 lines (64 loc) · 1.92 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#if !WINRT || UNITY_EDITOR
using System.Security.Cryptography;
namespace LiteNetLib.Encryption
{
public class NetKeyExchange
{
private readonly RSACryptoServiceProvider _rsa;
private const int KeySize = 2048;
public NetKeyExchange()
{
_rsa = new RSACryptoServiceProvider(KeySize);
}
public byte[] ExportPublicKey()
{
return _rsa.ExportCspBlob(false);
}
public void ImportPublicKey(byte[] data)
{
_rsa.ImportCspBlob(data);
}
public byte[] EncryptKey(byte[] key)
{
return _rsa.Encrypt(key, false);
}
public byte[] DecryptKey(byte[] data)
{
return _rsa.Decrypt(data, false);
}
}
}
#else
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Security.Cryptography.Core;
namespace LiteNetLib.Encryption
{
public class NetKeyExchange
{
private readonly AsymmetricKeyAlgorithmProvider _rsa;
private CryptographicKey _key;
private const int KeySize = 2048;
public NetKeyExchange()
{
_rsa = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
}
public byte[] ExportPublicKey()
{
_key = _rsa.CreateKeyPair(KeySize);
return _key.ExportPublicKey(CryptographicPublicKeyBlobType.Capi1PublicKey).ToArray();
}
public void ImportPublicKey(byte[] data)
{
_key = _rsa.ImportPublicKey(data.AsBuffer(), CryptographicPublicKeyBlobType.Capi1PublicKey);
}
public byte[] EncryptKey(byte[] key)
{
return CryptographicEngine.Encrypt(_key, key.AsBuffer(), null).ToArray();
}
public byte[] DecryptKey(byte[] data)
{
return CryptographicEngine.Decrypt(_key, data.AsBuffer(), null).ToArray();
}
}
}
#endif