summary refs log tree commit diff
path: root/crypto/src/pqc/crypto/bike/BikeKemGenerator.cs
blob: 51efbd67dbbe5d7855bc2c2aba15b808634daeba (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
using System;

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Pqc.Crypto.Bike
{
    public sealed class BikeKemGenerator
        : IEncapsulatedSecretGenerator
    {
        private readonly SecureRandom sr;

        public BikeKemGenerator(SecureRandom random)
        {
            this.sr = random;
        }

        public ISecretWithEncapsulation GenerateEncapsulated(AsymmetricKeyParameter recipientKey)
        {
            BikePublicKeyParameters key = (BikePublicKeyParameters)recipientKey;
            BikeParameters parameters = key.Parameters;
            BikeEngine engine = parameters.BikeEngine;

            byte[] K = new byte[parameters.LByte];
            byte[] c01 = new byte[parameters.RByte + parameters.LByte];
            byte[] h = key.PublicKey;

            engine.Encaps(c01, K, h, sr);

            return new SecretWithEncapsulationImpl(Arrays.CopyOfRange(K, 0, parameters.DefaultKeySize / 8), c01);
        }

        private sealed 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)
                {
                    Arrays.Clear(sessionKey);
                    Arrays.Clear(cipher_text);
                    hasBeenDestroyed = true;
                }
                GC.SuppressFinalize(this);
            }

            public bool IsDestroyed()
            {
                return hasBeenDestroyed;
            }

            void CheckDestroyed()
            {
                if (IsDestroyed())
                    throw new Exception("data has been destroyed");
            }
        }
    }
}