Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CramerShoupCoreEngine.java « engines « crypto « spongycastle « org « java « main « src « core - gitlab.com/quite/humla-spongycastle.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 894b13d8b72a3a249f715e12450393c0eaa922b1 (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
package org.spongycastle.crypto.engines;

import java.math.BigInteger;
import java.security.SecureRandom;

import org.spongycastle.crypto.CipherParameters;
import org.spongycastle.crypto.DataLengthException;
import org.spongycastle.crypto.Digest;
import org.spongycastle.crypto.params.CramerShoupKeyParameters;
import org.spongycastle.crypto.params.CramerShoupPrivateKeyParameters;
import org.spongycastle.crypto.params.CramerShoupPublicKeyParameters;
import org.spongycastle.crypto.params.ParametersWithRandom;
import org.spongycastle.util.BigIntegers;

/**
 * Essentially the Cramer-Shoup encryption / decryption algorithms according to
 * "A practical public key cryptosystem provably secure against adaptive chosen ciphertext attack." (Crypto 1998)
 */
public class CramerShoupCoreEngine
{

    private static final BigInteger ONE = BigInteger.valueOf(1);

    private CramerShoupKeyParameters key;
    private SecureRandom random;
    private boolean forEncryption;
    private String label = null;

    /**
     * initialise the CramerShoup engine.
     *
     * @param forEncryption whether this engine should encrypt or decrypt
     * @param param         the necessary CramerShoup key parameters.
     * @param label         the label for labelled CS as {@link String}
     */
    public void init(boolean forEncryption, CipherParameters param, String label)
    {
        init(forEncryption, param);

        this.label = label;
    }

    /**
     * initialise the CramerShoup engine.
     *
     * @param forEncryption whether this engine should encrypt or decrypt
     * @param param         the necessary CramerShoup key parameters.
     */
    public void init(boolean forEncryption, CipherParameters param)
    {
        SecureRandom providedRandom = null;

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

            key = (CramerShoupKeyParameters)rParam.getParameters();
            providedRandom = rParam.getRandom();
        }
        else
        {
            key = (CramerShoupKeyParameters)param;
        }

        this.random = initSecureRandom(forEncryption, providedRandom);
        this.forEncryption = forEncryption;
    }

    /**
     * Return the maximum size for an input block to this engine. For Cramer
     * Shoup this is always one byte less than the key size on encryption, and
     * the same length as the key size on decryption.
     *
     * @return maximum size for an input block.
     * <p/>
     * TODO: correct?
     */
    public int getInputBlockSize()
    {
        int bitSize = key.getParameters().getP().bitLength();

        if (forEncryption)
        {
            return (bitSize + 7) / 8 - 1;
        }
        else
        {
            return (bitSize + 7) / 8;
        }
    }

    /**
     * Return the maximum size for an output block to this engine. For Cramer
     * Shoup this is always one byte less than the key size on decryption, and
     * the same length as the key size on encryption.
     *
     * @return maximum size for an output block.
     * <p/>
     * TODO: correct?
     */
    public int getOutputBlockSize()
    {
        int bitSize = key.getParameters().getP().bitLength();

        if (forEncryption)
        {
            return (bitSize + 7) / 8;
        }
        else
        {
            return (bitSize + 7) / 8 - 1;
        }
    }

    public BigInteger convertInput(byte[] in, int inOff, int inLen)
    {
        if (inLen > (getInputBlockSize() + 1))
        {
            throw new DataLengthException("input too large for Cramer Shoup cipher.");
        }
        else if (inLen == (getInputBlockSize() + 1) && forEncryption)
        {
            throw new DataLengthException("input too large for Cramer Shoup cipher.");
        }

        byte[] block;

        if (inOff != 0 || inLen != in.length)
        {
            block = new byte[inLen];

            System.arraycopy(in, inOff, block, 0, inLen);
        }
        else
        {
            block = in;
        }

        BigInteger res = new BigInteger(1, block);
        if (res.compareTo(key.getParameters().getP()) >= 0)
        {
            throw new DataLengthException("input too large for Cramer Shoup cipher.");
        }

        return res;
    }

    public byte[] convertOutput(BigInteger result)
    {
        byte[] output = result.toByteArray();

        if (!forEncryption)
        {
            if (output[0] == 0 && output.length > getOutputBlockSize())
            { // have ended up with an extra zero byte, copy down.
                byte[] tmp = new byte[output.length - 1];

                System.arraycopy(output, 1, tmp, 0, tmp.length);

                return tmp;
            }

            if (output.length < getOutputBlockSize())
            {// have ended up with less bytes than normal, lengthen
                byte[] tmp = new byte[getOutputBlockSize()];

                System.arraycopy(output, 0, tmp, tmp.length - output.length, output.length);

                return tmp;
            }
        }
        else
        {
            if (output[0] == 0)
            { // have ended up with an extra zero byte, copy down.
                byte[] tmp = new byte[output.length - 1];

                System.arraycopy(output, 1, tmp, 0, tmp.length);

                return tmp;
            }
        }

        return output;
    }

    public CramerShoupCiphertext encryptBlock(BigInteger input)
    {

        CramerShoupCiphertext result = null;

        if (!key.isPrivate() && this.forEncryption && key instanceof CramerShoupPublicKeyParameters)
        {
            CramerShoupPublicKeyParameters pk = (CramerShoupPublicKeyParameters)key;
            BigInteger p = pk.getParameters().getP();
            BigInteger g1 = pk.getParameters().getG1();
            BigInteger g2 = pk.getParameters().getG2();

            BigInteger h = pk.getH();

            if (!isValidMessage(input, p))
            {
                return result;
            }

            BigInteger r = generateRandomElement(p, random);

            BigInteger u1, u2, v, e, a;

            u1 = g1.modPow(r, p);
            u2 = g2.modPow(r, p);
            e = h.modPow(r, p).multiply(input).mod(p);

            Digest digest = pk.getParameters().getH();
            byte[] u1Bytes = u1.toByteArray();
            digest.update(u1Bytes, 0, u1Bytes.length);
            byte[] u2Bytes = u2.toByteArray();
            digest.update(u2Bytes, 0, u2Bytes.length);
            byte[] eBytes = e.toByteArray();
            digest.update(eBytes, 0, eBytes.length);
            if (this.label != null)
            {
                byte[] lBytes = this.label.getBytes();
                digest.update(lBytes, 0, lBytes.length);
            }
            byte[] out = new byte[digest.getDigestSize()];
            digest.doFinal(out, 0);
            a = new BigInteger(1, out);

            v = pk.getC().modPow(r, p).multiply(pk.getD().modPow(r.multiply(a), p)).mod(p);

            result = new CramerShoupCiphertext(u1, u2, e, v);
        }
        return result;
    }

    public BigInteger decryptBlock(CramerShoupCiphertext input)
        throws CramerShoupCiphertextException
    {

        BigInteger result = null;

        if (key.isPrivate() && !this.forEncryption && key instanceof CramerShoupPrivateKeyParameters)
        {
            CramerShoupPrivateKeyParameters sk = (CramerShoupPrivateKeyParameters)key;

            BigInteger p = sk.getParameters().getP();

            Digest digest = sk.getParameters().getH();
            byte[] u1Bytes = input.getU1().toByteArray();
            digest.update(u1Bytes, 0, u1Bytes.length);
            byte[] u2Bytes = input.getU2().toByteArray();
            digest.update(u2Bytes, 0, u2Bytes.length);
            byte[] eBytes = input.getE().toByteArray();
            digest.update(eBytes, 0, eBytes.length);
            if (this.label != null)
            {
                byte[] lBytes = this.label.getBytes();
                digest.update(lBytes, 0, lBytes.length);
            }
            byte[] out = new byte[digest.getDigestSize()];
            digest.doFinal(out, 0);

            BigInteger a = new BigInteger(1, out);
            BigInteger v = input.u1.modPow(sk.getX1().add(sk.getY1().multiply(a)), p).
                multiply(input.u2.modPow(sk.getX2().add(sk.getY2().multiply(a)), p)).mod(p);

            // check correctness of ciphertext
            if (input.v.equals(v))
            {
                result = input.e.multiply(input.u1.modPow(sk.getZ(), p).modInverse(p)).mod(p);
            }
            else
            {
                throw new CramerShoupCiphertextException("Sorry, that ciphertext is not correct");
            }
        }
        return result;
    }

    private BigInteger generateRandomElement(BigInteger p, SecureRandom random)
    {
        return BigIntegers.createRandomInRange(ONE, p.subtract(ONE), random);
    }

    /**
     * just checking whether the message m is actually less than the group order p
     */
    private boolean isValidMessage(BigInteger m, BigInteger p)
    {
        return m.compareTo(p) < 0;
    }

    protected SecureRandom initSecureRandom(boolean needed, SecureRandom provided)
    {
        return !needed ? null : (provided != null) ? provided : new SecureRandom();
    }

    /**
     * CS exception for wrong cipher-texts
     */
    public static class CramerShoupCiphertextException
        extends Exception
    {
        private static final long serialVersionUID = -6360977166495345076L;

        public CramerShoupCiphertextException(String msg)
        {
            super(msg);
        }

    }
}