aboutsummaryrefslogtreecommitdiffstats
path: root/libraries/spongycastle/core/src/main/java/org/spongycastle/pqc/crypto/mceliece/McElieceKobaraImaiCipher.java
blob: 0be981be3feaa829017d7ede6d1caea109cba0f0 (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package org.spongycastle.pqc.crypto.mceliece;

import java.security.SecureRandom;

import org.spongycastle.crypto.CipherParameters;
import org.spongycastle.crypto.Digest;
import org.spongycastle.crypto.digests.SHA1Digest;
import org.spongycastle.crypto.params.ParametersWithRandom;
import org.spongycastle.crypto.prng.DigestRandomGenerator;
import org.spongycastle.pqc.crypto.MessageEncryptor;
import org.spongycastle.pqc.math.linearalgebra.ByteUtils;
import org.spongycastle.pqc.math.linearalgebra.GF2Vector;
import org.spongycastle.pqc.math.linearalgebra.IntegerFunctions;

/**
 * This class implements the Kobara/Imai conversion of the McEliecePKCS. This is
 * a conversion of the McEliecePKCS which is CCA2-secure. For details, see D.
 * Engelbert, R. Overbeck, A. Schmidt, "A summary of the development of the
 * McEliece Cryptosystem", technical report.
 */
public class McElieceKobaraImaiCipher
    implements MessageEncryptor
{

    /**
     * The OID of the algorithm.
     */
    public static final String OID = "1.3.6.1.4.1.8301.3.1.3.4.2.3";

    private static final String DEFAULT_PRNG_NAME = "SHA1PRNG";

    /**
     * A predetermined public constant.
     */
    public static final byte[] PUBLIC_CONSTANT = "a predetermined public constant"
        .getBytes();


    private Digest messDigest;

    private SecureRandom sr;

    McElieceCCA2KeyParameters key;

    /**
     * The McEliece main parameters
     */
    private int n, k, t;


    public void init(boolean forSigning,
                     CipherParameters param)
    {

        if (forSigning)
        {
            if (param instanceof ParametersWithRandom)
            {
                ParametersWithRandom rParam = (ParametersWithRandom)param;

                this.sr = rParam.getRandom();
                this.key = (McElieceCCA2PublicKeyParameters)rParam.getParameters();
                this.initCipherEncrypt((McElieceCCA2PublicKeyParameters)key);

            }
            else
            {
                this.sr = new SecureRandom();
                this.key = (McElieceCCA2PublicKeyParameters)param;
                this.initCipherEncrypt((McElieceCCA2PublicKeyParameters)key);
            }
        }
        else
        {
            this.key = (McElieceCCA2PrivateKeyParameters)param;
            this.initCipherDecrypt((McElieceCCA2PrivateKeyParameters)key);
        }

    }

    /**
     * Return the key size of the given key object.
     *
     * @param key the McElieceCCA2KeyParameters object
     * @return the key size of the given key object
     */
    public int getKeySize(McElieceCCA2KeyParameters key)
    {
        if (key instanceof McElieceCCA2PublicKeyParameters)
        {
            return ((McElieceCCA2PublicKeyParameters)key).getN();

        }
        if (key instanceof McElieceCCA2PrivateKeyParameters)
        {
            return ((McElieceCCA2PrivateKeyParameters)key).getN();
        }
        throw new IllegalArgumentException("unsupported type");
    }

    private void initCipherEncrypt(McElieceCCA2PublicKeyParameters pubKey)
    {
        this.messDigest = pubKey.getParameters().getDigest();
        n = pubKey.getN();
        k = pubKey.getK();
        t = pubKey.getT();

    }

    public void initCipherDecrypt(McElieceCCA2PrivateKeyParameters privKey)
    {
        this.messDigest = privKey.getParameters().getDigest();
        n = privKey.getN();
        k = privKey.getK();
        t = privKey.getT();
    }

    public byte[] messageEncrypt(byte[] input)
        throws Exception
    {

        int c2Len = messDigest.getDigestSize();
        int c4Len = k >> 3;
        int c5Len = (IntegerFunctions.binomial(n, t).bitLength() - 1) >> 3;


        int mLen = c4Len + c5Len - c2Len - PUBLIC_CONSTANT.length;
        if (input.length > mLen)
        {
            mLen = input.length;
        }

        int c1Len = mLen + PUBLIC_CONSTANT.length;
        int c6Len = c1Len + c2Len - c4Len - c5Len;

        // compute (m||const)
        byte[] mConst = new byte[c1Len];
        System.arraycopy(input, 0, mConst, 0, input.length);
        System.arraycopy(PUBLIC_CONSTANT, 0, mConst, mLen,
            PUBLIC_CONSTANT.length);

        // generate random r of length c2Len bytes
        byte[] r = new byte[c2Len];
        sr.nextBytes(r);

        // get PRNG object
                // get PRNG object
        DigestRandomGenerator sr0 = new DigestRandomGenerator(new SHA1Digest());

        // seed PRNG with r'
        sr0.addSeedMaterial(r);

        // generate random sequence ...
        byte[] c1 = new byte[c1Len];
        sr0.nextBytes(c1);

        // ... and XOR with (m||const) to obtain c1
        for (int i = c1Len - 1; i >= 0; i--)
        {
            c1[i] ^= mConst[i];
        }

        // compute H(c1) ...
        byte[] c2 = new byte[messDigest.getDigestSize()];
        messDigest.update(c1, 0, c1.length);
        messDigest.doFinal(c2, 0);

        // ... and XOR with r
        for (int i = c2Len - 1; i >= 0; i--)
        {
            c2[i] ^= r[i];
        }

        // compute (c2||c1)
        byte[] c2c1 = ByteUtils.concatenate(c2, c1);

        // split (c2||c1) into (c6||c5||c4), where c4Len is k/8 bytes, c5Len is
        // floor[log(n|t)]/8 bytes, and c6Len is c1Len+c2Len-c4Len-c5Len (may be
        // 0).
        byte[] c6 = new byte[0];
        if (c6Len > 0)
        {
            c6 = new byte[c6Len];
            System.arraycopy(c2c1, 0, c6, 0, c6Len);
        }

        byte[] c5 = new byte[c5Len];
        System.arraycopy(c2c1, c6Len, c5, 0, c5Len);

        byte[] c4 = new byte[c4Len];
        System.arraycopy(c2c1, c6Len + c5Len, c4, 0, c4Len);

        // convert c4 to vector over GF(2)
        GF2Vector c4Vec = GF2Vector.OS2VP(k, c4);

        // convert c5 to error vector z
        GF2Vector z = Conversions.encode(n, t, c5);

        // compute encC4 = E(c4, z)
        byte[] encC4 = McElieceCCA2Primitives.encryptionPrimitive((McElieceCCA2PublicKeyParameters)key,
            c4Vec, z).getEncoded();

        // if c6Len > 0
        if (c6Len > 0)
        {
            // return (c6||encC4)
            return ByteUtils.concatenate(c6, encC4);
        }
        // else, return encC4
        return encC4;
    }


    public byte[] messageDecrypt(byte[] input)
        throws Exception
    {

        int nDiv8 = n >> 3;

        if (input.length < nDiv8)
        {
            throw new Exception("Bad Padding: Ciphertext too short.");
        }

        int c2Len = messDigest.getDigestSize();
        int c4Len = k >> 3;
        int c6Len = input.length - nDiv8;

        // split cipher text (c6||encC4), where c6 may be empty
        byte[] c6, encC4;
        if (c6Len > 0)
        {
            byte[][] c6EncC4 = ByteUtils.split(input, c6Len);
            c6 = c6EncC4[0];
            encC4 = c6EncC4[1];
        }
        else
        {
            c6 = new byte[0];
            encC4 = input;
        }

        // convert encC4 into vector over GF(2)
        GF2Vector encC4Vec = GF2Vector.OS2VP(n, encC4);

        // decrypt encC4Vec to obtain c4 and error vector z
        GF2Vector[] c4z = McElieceCCA2Primitives.decryptionPrimitive((McElieceCCA2PrivateKeyParameters)key,
            encC4Vec);
        byte[] c4 = c4z[0].getEncoded();
        GF2Vector z = c4z[1];

        // if length of c4 is greater than c4Len (because of padding) ...
        if (c4.length > c4Len)
        {
            // ... truncate the padding bytes
            c4 = ByteUtils.subArray(c4, 0, c4Len);
        }

        // compute c5 = Conv^-1(z)
        byte[] c5 = Conversions.decode(n, t, z);

        // compute (c6||c5||c4)
        byte[] c6c5c4 = ByteUtils.concatenate(c6, c5);
        c6c5c4 = ByteUtils.concatenate(c6c5c4, c4);

        // split (c6||c5||c4) into (c2||c1), where c2Len = mdLen and c1Len =
        // input.length-c2Len bytes.
        int c1Len = c6c5c4.length - c2Len;
        byte[][] c2c1 = ByteUtils.split(c6c5c4, c2Len);
        byte[] c2 = c2c1[0];
        byte[] c1 = c2c1[1];

        // compute H(c1) ...
        byte[] rPrime = new byte[messDigest.getDigestSize()];
        messDigest.update(c1, 0, c1.length);
        messDigest.doFinal(rPrime, 0);

        // ... and XOR with c2 to obtain r'
        for (int i = c2Len - 1; i >= 0; i--)
        {
            rPrime[i] ^= c2[i];
        }

        // get PRNG object
        DigestRandomGenerator sr0 = new DigestRandomGenerator(new SHA1Digest());

        // seed PRNG with r'
        sr0.addSeedMaterial(rPrime);

        // generate random sequence R(r') ...
        byte[] mConstPrime = new byte[c1Len];
        sr0.nextBytes(mConstPrime);

        // ... and XOR with c1 to obtain (m||const')
        for (int i = c1Len - 1; i >= 0; i--)
        {
            mConstPrime[i] ^= c1[i];
        }

        if (mConstPrime.length < c1Len)
        {
            throw new Exception("Bad Padding: invalid ciphertext");
        }

        byte[][] temp = ByteUtils.split(mConstPrime, c1Len
            - PUBLIC_CONSTANT.length);
        byte[] mr = temp[0];
        byte[] constPrime = temp[1];

        if (!ByteUtils.equals(constPrime, PUBLIC_CONSTANT))
        {
            throw new Exception("Bad Padding: invalid ciphertext");
        }

        return mr;
    }


}