forked from BornToBeRoot/NETworkManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCryptoHelper.cs
More file actions
63 lines (48 loc) · 2.23 KB
/
Copy pathCryptoHelper.cs
File metadata and controls
63 lines (48 loc) · 2.23 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
using System;
using System.Security.Cryptography;
namespace NETworkManager.Utilities;
public static class CryptoHelper
{
private static readonly int blockSize = 128;
/// <summary>
/// </summary>
/// <param name="decryptedBytes"></param>
/// <param name="password"></param>
/// <param name="keySize"></param>
/// <param name="iterations"></param>
/// <returns></returns>
public static byte[] Encrypt(byte[] decryptedBytes, string password, int keySize, int iterations)
{
ReadOnlySpan<byte> salt = RandomNumberGenerator.GetBytes(keySize / 8); // Generate salt based
ReadOnlySpan<byte>
iv = RandomNumberGenerator.GetBytes(blockSize / 8); // Generate iv, has to be the same as the block size
var key = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA512, keySize / 8);
using var aes = Aes.Create();
aes.Key = key;
var encryptedSize = aes.GetCiphertextLengthCbc(decryptedBytes.Length);
var cipher = new byte[salt.Length + iv.Length + encryptedSize];
Span<byte> cipherSpan = cipher;
salt.CopyTo(cipherSpan);
iv.CopyTo(cipherSpan[salt.Length..]);
var encrypted = aes.EncryptCbc(decryptedBytes, iv, cipherSpan[(salt.Length + iv.Length)..]);
return cipher;
}
/// <summary>
/// </summary>
/// <param name="encryptedBytesWithSaltAndIV"></param>
/// <param name="password"></param>
/// <param name="keySize"></param>
/// <param name="iterations"></param>
/// <returns></returns>
public static byte[] Decrypt(byte[] encryptedBytesWithSaltAndIV, string password, int keySize, int iterations)
{
ReadOnlySpan<byte> salt = encryptedBytesWithSaltAndIV.AsSpan(0, keySize / 8); // Take salt bytes
ReadOnlySpan<byte>
iv = encryptedBytesWithSaltAndIV.AsSpan(keySize / 8, blockSize / 8); // Skip salt bytes, take iv bytes
ReadOnlySpan<byte> cipher = encryptedBytesWithSaltAndIV.AsSpan(keySize / 8 + blockSize / 8);
var key = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA512, keySize / 8);
using var aes = Aes.Create();
aes.Key = key;
return aes.DecryptCbc(cipher, iv);
}
}