summaryrefslogtreecommitdiffstats
path: root/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1withDSA_SignatureImpl.java
blob: d2a9c6dd6f8f8f4a7388171bfd0d37cfc280e3b9 (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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.apache.harmony.security.provider.crypto;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.InvalidParameterException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.DSAKey;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;

public class SHA1withDSA_SignatureImpl extends Signature {

    private MessageDigest msgDigest;

    private DSAKey dsaKey;

    /**
     * The solo constructor.
     */
    public SHA1withDSA_SignatureImpl() throws NoSuchAlgorithmException {

        super("SHA1withDSA");

        msgDigest = MessageDigest.getInstance("SHA1");
    }

    /**
     * Deprecated method.
     *
     * @return
     *    null
     */
    protected Object engineGetParameter(String param)
            throws InvalidParameterException {
        if (param == null) {
            throw new NullPointerException();
        }
        return null;
    }

    /**
     * Initializes this signature object with PrivateKey object
     * passed as argument to the method.
     *
     * @params
     *    privateKey DSAPrivateKey object
     * @throws
     *    InvalidKeyException if privateKey is not DSAPrivateKey object
     */
    protected void engineInitSign(PrivateKey privateKey)
            throws InvalidKeyException {

        DSAParams params;

        // parameters and private key
        BigInteger p, q, x;

        int n;

        if (privateKey == null || !(privateKey instanceof DSAPrivateKey)) {
            throw new InvalidKeyException();
        }

        params = ((DSAPrivateKey) privateKey).getParams();
        p = params.getP();
        q = params.getQ();
        x = ((DSAPrivateKey) privateKey).getX();

        // checks described in DSA standard
        n = p.bitLength();
        if (p.compareTo(BigInteger.valueOf(1)) != 1 || n < 512 || n > 1024 || (n & 077) != 0) {
            throw new InvalidKeyException("bad p");
        }
        if (q.signum() != 1 && q.bitLength() != 160) {
            throw new InvalidKeyException("bad q");
        }
        if (x.signum() != 1 || x.compareTo(q) != -1) {
            throw new InvalidKeyException("x <= 0 || x >= q");
        }

        dsaKey = (DSAKey) privateKey;

        msgDigest.reset();
    }

    /**
     * Initializes this signature object with PublicKey object
     * passed as argument to the method.
     *
     * @params
     *    publicKey DSAPublicKey object
     * @throws
     *    InvalidKeyException if publicKey is not DSAPublicKey object
     */
    protected void engineInitVerify(PublicKey publicKey)
            throws InvalidKeyException {

        // parameters and public key
        BigInteger p, q, y;

        int n1;

        if (publicKey == null || !(publicKey instanceof DSAPublicKey)) {
            throw new InvalidKeyException("publicKey is not an instance of DSAPublicKey");
        }

        DSAParams params = ((DSAPublicKey) publicKey).getParams();
        p = params.getP();
        q = params.getQ();
        y = ((DSAPublicKey) publicKey).getY();

        // checks described in DSA standard
        n1 = p.bitLength();
        if (p.compareTo(BigInteger.valueOf(1)) != 1 || n1 < 512 || n1 > 1024 || (n1 & 077) != 0) {
            throw new InvalidKeyException("bad p");
        }
        if (q.signum() != 1 || q.bitLength() != 160) {
            throw new InvalidKeyException("bad q");
        }
        if (y.signum() != 1) {
            throw new InvalidKeyException("y <= 0");
        }

        dsaKey = (DSAKey) publicKey;

        msgDigest.reset();
    }

    /*
     * Deprecated method.
     *
     * @throws
     *    InvalidParameterException
     */
    protected void engineSetParameter(String param, Object value) throws InvalidParameterException {
        if (param == null) {
            throw new NullPointerException("param == null");
        }
        throw new InvalidParameterException("invalid parameter for this engine");
    }

    /**
     * Returns signature bytes as byte array containing
     * ASN1 representation for two BigInteger objects
     * which is SEQUENCE of two INTEGERS.
     * Length of sequence varies from less than 46 to 48.
     *
     * Resets object to the state it was in
     * when previous call to either "initSign" method was called.
     *
     * @return
     *    byte array containing signature in ASN1 representation
     * @throws
     *    SignatureException if object's state is not SIGN or
     *                       signature algorithm cannot process data
     */

    protected byte[] engineSign() throws SignatureException {

        // names of below BigIntegers are the same as they are defined in DSA standard
        BigInteger r = null;
        BigInteger s = null;
        BigInteger k = null;

        // parameters and private key
        BigInteger p, q, g, x;

        // BigInteger for message digest
        BigInteger digestBI;

        // various byte array being used in computing signature
        byte[] randomBytes;
        byte[] rBytes;
        byte[] sBytes;
        byte[] signature;

        int n, n1, n2;

        DSAParams params;

        if (appRandom == null) {
            appRandom = new SecureRandom();
        }

        params = dsaKey.getParams();
        p = params.getP();
        q = params.getQ();
        g = params.getG();
        x = ((DSAPrivateKey) dsaKey).getX();

        // forming signature according algorithm described in chapter 5 of DSA standard

        digestBI = new BigInteger(1, msgDigest.digest());

        randomBytes = new byte[20];

        for (;;) {

            appRandom.nextBytes(randomBytes);

            k = new BigInteger(1, randomBytes);
            if (k.compareTo(q) != -1) {
                continue;
            }
            r = g.modPow(k, p).mod(q);
            if (r.signum() == 0) {
                continue;
            }

            s = k.modInverse(q).multiply(digestBI.add(x.multiply(r)).mod(q))
                    .mod(q);

            if (s.signum() != 0) {
                break;
            }
        }

        // forming signature's ASN1 representation which is SEQUENCE of two INTEGERs
        //
        rBytes = r.toByteArray();
        n1 = rBytes.length;
        if ((rBytes[0] & 0x80) != 0) {
            n1++;
        }
        sBytes = s.toByteArray();
        n2 = sBytes.length;
        if ((sBytes[0] & 0x80) != 0) {
            n2++;
        }

        signature = new byte[6 + n1 + n2]; // 48 is max. possible length of signature
        signature[0] = (byte) 0x30; // ASN1 SEQUENCE tag
        signature[1] = (byte) (4 + n1 + n2); // total length of two INTEGERs
        signature[2] = (byte) 0x02; // ASN1 INTEGER tag
        signature[3] = (byte) n1; // length of r
        signature[4 + n1] = (byte) 0x02; // ASN1 INTEGER tag
        signature[5 + n1] = (byte) n2; // length of s

        if (n1 == rBytes.length) {
            n = 4;
        } else {
            n = 5;
        }
        System.arraycopy(rBytes, 0, signature, n, rBytes.length);

        if (n2 == sBytes.length) {
            n = 6 + n1;
        } else {
            n = 7 + n1;
        }
        System.arraycopy(sBytes, 0, signature, n, sBytes.length);

        return signature;
    }

    /**
     * Updates data to sign or to verify.
     *
     * @params
     *    b byte to update
     * @throws
     *    SignatureException if object was not initialized for signing or verifying
     */
    protected void engineUpdate(byte b) throws SignatureException {

        msgDigest.update(b);
    }

    /**
     * Updates data to sign or to verify.
     *
     * @params
     *    b byte array containing bytes to update
     * @params
     *    off offset in byte array to start from
     * @params
     *    len number of bytes to use for updating
     * @throws
     *    SignatureException if object was not initialized for signing or verifying
     */
    protected void engineUpdate(byte[] b, int off, int len)
            throws SignatureException {

        msgDigest.update(b, off, len);
    }

    private boolean checkSignature(byte[] sigBytes, int offset, int length)
            throws SignatureException {

        // names of below BigIntegers are the same as they are defined in DSA standard
        BigInteger r, s, w;
        BigInteger u1, u2, v;

        // parameters and public key
        BigInteger p, q, g, y;

        DSAParams params;

        int n1, n2;

        byte[] bytes;
        byte[] digest;

        // checking up on signature's ASN1
        try {
            byte dummy;
            n1 = sigBytes[offset + 3];
            n2 = sigBytes[offset + n1 + 5];

            if (sigBytes[offset + 0] != 0x30 || sigBytes[offset + 2] != 2
                    || sigBytes[offset + n1 + 4] != 2
                    || sigBytes[offset + 1] != (n1 + n2 + 4) || n1 > 21
                    || n2 > 21
                    || (length != 0 && (sigBytes[offset + 1] + 2) > length)) {
                throw new SignatureException("signature bytes have invalid encoding");
            }

            dummy = sigBytes[5 + n1 + n2]; // to check length of sigBytes
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new SignatureException("bad argument: byte[] is too small");
        }

        digest = msgDigest.digest();

        bytes = new byte[n1];
        System.arraycopy(sigBytes, offset + 4, bytes, 0, n1);
        r = new BigInteger(bytes);

        bytes = new byte[n2];
        System.arraycopy(sigBytes, offset + 6 + n1, bytes, 0, n2);
        s = new BigInteger(bytes);

        params = dsaKey.getParams();
        p = params.getP();
        q = params.getQ();
        g = params.getG();
        y = ((DSAPublicKey) dsaKey).getY();

        // forming signature according algorithm described in chapter 6 of DSA standard

        if (r.signum() != 1 || r.compareTo(q) != -1 || s.signum() != 1
                || s.compareTo(q) != -1) {
            return false;
        }

        w = s.modInverse(q);

        u1 = (new BigInteger(1, digest)).multiply(w).mod(q);
        u2 = r.multiply(w).mod(q);

        v = g.modPow(u1, p).multiply(y.modPow(u2, p)).mod(p).mod(q);

        if (v.compareTo(r) != 0) {
            return false;
        }
        return true;
    }

    /**
     * Verifies the signature bytes.
     *
     * @params
     *    sigBytes byte array with signature bytes to verify.
     * @return
     *    true if signature bytes were verified, false otherwise
     * @throws
     *    SignatureException if object's state is not VERIFY or
     *                       signature format is not ASN1 representation or
     *                       signature algorithm cannot process data
     */
    protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
        if (sigBytes == null) {
            throw new NullPointerException("sigBytes == null");
        }

        return checkSignature(sigBytes, 0, 0);
    }

    /**
     * Verifies the signature bytes.
     *
     * @params
     *    sigBytes byte array with signature bytes to verify.
     * @params
     *    offset index in sigBytes to start from
     * @params
     *    length number of bytes allotted for signature
     * @return
     *    true if signature bytes were verified, false otherwise
     * @throws
     *    SignatureException if object's state is not VERIFY or
     *                       signature format is not ASN1 representation or
     *                       signature algorithm cannot process data
     */
    protected boolean engineVerify(byte[] sigBytes, int offset, int length)
            throws SignatureException {
        return checkSignature(sigBytes, offset, length);
    }
}