-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
CngPkcs8Tests.cs
87 lines (71 loc) · 3.05 KB
/
CngPkcs8Tests.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
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
77
78
79
80
81
82
83
84
85
86
87
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Security.Cryptography.Cng.Tests
{
public abstract class CngPkcs8Tests<T> where T : AsymmetricAlgorithm
{
protected abstract T CreateKey(out CngKey cngKey);
protected abstract void VerifyMatch(T exported, T imported);
[Fact]
public void NoPlaintextExportFailsPkcs8()
{
using (T key = CreateKey(out CngKey cngKey))
{
SetExportPolicy(cngKey, CngExportPolicies.AllowExport);
Assert.ThrowsAny<CryptographicException>(
() => key.ExportPkcs8PrivateKey());
Assert.ThrowsAny<CryptographicException>(
() => key.TryExportPkcs8PrivateKey(Span<byte>.Empty, out _));
}
}
[Theory]
[InlineData(PbeEncryptionAlgorithm.Aes256Cbc)]
[InlineData(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12)]
public void NoPlaintextExportAllowsEncryptedPkcs8(PbeEncryptionAlgorithm algorithm)
{
PbeParameters pbeParameters = new PbeParameters(
algorithm,
HashAlgorithmName.SHA1,
2048);
using (T key = CreateKey(out CngKey cngKey))
{
SetExportPolicy(cngKey, CngExportPolicies.AllowExport);
byte[] data = key.ExportEncryptedPkcs8PrivateKey(
(ReadOnlySpan<char>)nameof(NoPlaintextExportAllowsEncryptedPkcs8),
pbeParameters);
Assert.False(
key.TryExportEncryptedPkcs8PrivateKey(
(ReadOnlySpan<char>)nameof(NoPlaintextExportAllowsEncryptedPkcs8),
pbeParameters,
data.AsSpan(0, data.Length - 1),
out int bytesWritten));
Assert.Equal(0, bytesWritten);
Assert.True(
key.TryExportEncryptedPkcs8PrivateKey(
(ReadOnlySpan<char>)nameof(NoPlaintextExportAllowsEncryptedPkcs8),
pbeParameters,
data.AsSpan(),
out bytesWritten));
Assert.Equal(data.Length, bytesWritten);
using (T key2 = CreateKey(out _))
{
key2.ImportEncryptedPkcs8PrivateKey(
(ReadOnlySpan<char>)nameof(NoPlaintextExportAllowsEncryptedPkcs8),
data,
out int bytesRead);
Assert.Equal(data.Length, bytesRead);
VerifyMatch(key, key2);
}
}
}
private static void SetExportPolicy(CngKey key, CngExportPolicies policy)
{
key.SetProperty(
new CngProperty(
"Export Policy",
BitConverter.GetBytes((int)policy),
CngPropertyOptions.Persist));
}
}
}