blob: a3df648ff471869dad683dc35c2792fcad50836e (
plain) (
blame)
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
|
using System;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pqc.Crypto.Cmce;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
public class CmceKemGenerator
: IEncapsulatedSecretGenerator
{
// the source of randomness
private SecureRandom sr;
public CmceKemGenerator(SecureRandom random)
{
this.sr = random;
}
public ISecretWithEncapsulation GenerateEncapsulated(AsymmetricKeyParameter recipientKey)
{
CmcePublicKeyParameters key = (CmcePublicKeyParameters)recipientKey;
CmceEngine engine = key.Parameters.Engine;
return GenerateEncapsulated(recipientKey, engine.DefaultSessionKeySize);
}
public ISecretWithEncapsulation GenerateEncapsulated(AsymmetricKeyParameter recipientKey, int sessionKeySizeInBits)
{
CmcePublicKeyParameters key = (CmcePublicKeyParameters)recipientKey;
CmceEngine engine = key.Parameters.Engine;
byte[] cipher_text = new byte[engine.CipherTextSize];
byte[] sessionKey = new byte[sessionKeySizeInBits / 8]; // document as 32 - l/8 - Section 2.5.2
engine.kem_enc(cipher_text, sessionKey, key.PublicKey, sr);
return new SecretWithEncapsulationImpl(sessionKey, cipher_text);
}
private class SecretWithEncapsulationImpl
: ISecretWithEncapsulation
{
private volatile bool hasBeenDestroyed = false;
private byte[] sessionKey;
private byte[] cipher_text;
public SecretWithEncapsulationImpl(byte[] sessionKey, byte[] cipher_text)
{
this.sessionKey = sessionKey;
this.cipher_text = cipher_text;
}
public byte[] GetSecret()
{
CheckDestroyed();
return Arrays.Clone(sessionKey);
}
public byte[] GetEncapsulation()
{
CheckDestroyed();
return Arrays.Clone(cipher_text);
}
public void Dispose()
{
if (!hasBeenDestroyed)
{
hasBeenDestroyed = true;
Arrays.Clear(sessionKey);
Arrays.Clear(cipher_text);
}
}
public bool IsDestroyed()
{
return hasBeenDestroyed;
}
void CheckDestroyed()
{
if (IsDestroyed())
{
throw new Exception("data has been destroyed");
}
}
}
}
|