summaryrefslogtreecommitdiffstats
path: root/mobile/android/services/src/main/java/org/mozilla/gecko/browserid/RSACryptoImplementation.java
blob: 902f6fb4d68af1d29395c5c6d58b63f8298f46ae (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko.browserid;

import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import org.mozilla.gecko.sync.ExtendedJSONObject;
import org.mozilla.gecko.sync.NonObjectJSONException;

public class RSACryptoImplementation {
  public static final String SIGNATURE_ALGORITHM = "SHA256withRSA";

  /**
   * Parameters are serialized as decimal strings. Hex-versus-decimal was
   * reverse-engineered from what the Persona public verifier accepted. We
   * expect to follow the JOSE/JWT spec as it solidifies, and that will probably
   * mean unifying this base.
   */
  protected static final int SERIALIZATION_BASE = 10;

  protected static class RSAVerifyingPublicKey implements VerifyingPublicKey {
    protected final RSAPublicKey publicKey;

    public RSAVerifyingPublicKey(RSAPublicKey publicKey) {
      this.publicKey = publicKey;
    }

    /**
     * Serialize to a JSON object.
     * <p>
     * Parameters are serialized as decimal strings. Hex-versus-decimal was
     * reverse-engineered from what the Persona public verifier accepted.
     */
    @Override
    public ExtendedJSONObject toJSONObject() {
      ExtendedJSONObject o = new ExtendedJSONObject();
      o.put("algorithm", "RS");
      o.put("n", publicKey.getModulus().toString(SERIALIZATION_BASE));
      o.put("e", publicKey.getPublicExponent().toString(SERIALIZATION_BASE));
      return o;
    }

    @Override
    public boolean verifyMessage(byte[] bytes, byte[] signature)
        throws GeneralSecurityException {
      final Signature signer = Signature.getInstance(SIGNATURE_ALGORITHM);
      signer.initVerify(publicKey);
      signer.update(bytes);
      return signer.verify(signature);
    }
  }

  protected static class RSASigningPrivateKey implements SigningPrivateKey {
    protected final RSAPrivateKey privateKey;

    public RSASigningPrivateKey(RSAPrivateKey privateKey) {
      this.privateKey = privateKey;
    }

    @Override
    public String getAlgorithm() {
      return "RS" + (privateKey.getModulus().bitLength() + 7)/8;
    }

    /**
     * Serialize to a JSON object.
     * <p>
     * Parameters are serialized as decimal strings. Hex-versus-decimal was
     * reverse-engineered from what the Persona public verifier accepted.
     */
    @Override
    public ExtendedJSONObject toJSONObject() {
      ExtendedJSONObject o = new ExtendedJSONObject();
      o.put("algorithm", "RS");
      o.put("n", privateKey.getModulus().toString(SERIALIZATION_BASE));
      o.put("d", privateKey.getPrivateExponent().toString(SERIALIZATION_BASE));
      return o;
    }

    @Override
    public byte[] signMessage(byte[] bytes)
        throws GeneralSecurityException {
      final Signature signer = Signature.getInstance(SIGNATURE_ALGORITHM);
      signer.initSign(privateKey);
      signer.update(bytes);
      return signer.sign();
    }
  }

  public static BrowserIDKeyPair generateKeyPair(final int keysize) throws NoSuchAlgorithmException {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(keysize);
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    return new BrowserIDKeyPair(new RSASigningPrivateKey(privateKey), new RSAVerifyingPublicKey(publicKey));
  }

  public static SigningPrivateKey createPrivateKey(BigInteger n, BigInteger d) throws NoSuchAlgorithmException, InvalidKeySpecException {
    if (n == null) {
      throw new IllegalArgumentException("n must not be null");
    }
    if (d == null) {
      throw new IllegalArgumentException("d must not be null");
    }
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    KeySpec keySpec = new RSAPrivateKeySpec(n, d);
    RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    return new RSASigningPrivateKey(privateKey);
  }

  public static VerifyingPublicKey createPublicKey(BigInteger n, BigInteger e) throws NoSuchAlgorithmException, InvalidKeySpecException {
    if (n == null) {
      throw new IllegalArgumentException("n must not be null");
    }
    if (e == null) {
      throw new IllegalArgumentException("e must not be null");
    }
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    KeySpec keySpec = new RSAPublicKeySpec(n, e);
    RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
    return new RSAVerifyingPublicKey(publicKey);
  }

  public static SigningPrivateKey createPrivateKey(ExtendedJSONObject o) throws InvalidKeySpecException, NoSuchAlgorithmException {
    String algorithm = o.getString("algorithm");
    if (!"RS".equals(algorithm)) {
      throw new InvalidKeySpecException("algorithm must equal RS, was " + algorithm);
    }
    try {
      BigInteger n = new BigInteger(o.getString("n"), SERIALIZATION_BASE);
      BigInteger d = new BigInteger(o.getString("d"), SERIALIZATION_BASE);
      return createPrivateKey(n, d);
    } catch (NullPointerException | NumberFormatException e) {
      throw new InvalidKeySpecException("n and d must be integers encoded as strings, base " + SERIALIZATION_BASE);
    }
  }

  public static VerifyingPublicKey createPublicKey(ExtendedJSONObject o) throws InvalidKeySpecException, NoSuchAlgorithmException {
    String algorithm = o.getString("algorithm");
    if (!"RS".equals(algorithm)) {
      throw new InvalidKeySpecException("algorithm must equal RS, was " + algorithm);
    }
    try {
      BigInteger n = new BigInteger(o.getString("n"), SERIALIZATION_BASE);
      BigInteger e = new BigInteger(o.getString("e"), SERIALIZATION_BASE);
      return createPublicKey(n, e);
    } catch (NullPointerException | NumberFormatException e) {
      throw new InvalidKeySpecException("n and e must be integers encoded as strings, base " + SERIALIZATION_BASE);
    }
  }

  public static BrowserIDKeyPair fromJSONObject(ExtendedJSONObject o) throws InvalidKeySpecException, NoSuchAlgorithmException {
    try {
      ExtendedJSONObject privateKey = o.getObject(BrowserIDKeyPair.JSON_KEY_PRIVATEKEY);
      ExtendedJSONObject publicKey = o.getObject(BrowserIDKeyPair.JSON_KEY_PUBLICKEY);
      if (privateKey == null) {
        throw new InvalidKeySpecException("privateKey must not be null");
      }
      if (publicKey == null) {
        throw new InvalidKeySpecException("publicKey must not be null");
      }
      return new BrowserIDKeyPair(createPrivateKey(privateKey), createPublicKey(publicKey));
    } catch (NonObjectJSONException e) {
      throw new InvalidKeySpecException("privateKey and publicKey must be JSON objects");
    }
  }
}