blob: 606423d53a40d266de97f52be4bd0d1e2d8e7cf2 [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26package sun.security.mscapi;
27
28import java.nio.ByteBuffer;
29import java.security.PublicKey;
30import java.security.PrivateKey;
31import java.security.InvalidKeyException;
32import java.security.InvalidParameterException;
33import java.security.InvalidAlgorithmParameterException;
34import java.security.NoSuchAlgorithmException;
35import java.security.ProviderException;
36import java.security.MessageDigest;
37import java.security.SecureRandom;
38import java.security.Signature;
39import java.security.SignatureSpi;
40import java.security.SignatureException;
41
42/**
43 * RSA signature implementation. Supports RSA signing using PKCS#1 v1.5 padding.
44 *
45 * Objects should be instantiated by calling Signature.getInstance() using the
46 * following algorithm names:
47 *
48 * . "SHA1withRSA"
49 * . "MD5withRSA"
50 * . "MD2withRSA"
51 *
52 * Note: RSA keys must be at least 512 bits long
53 *
54 * @since 1.6
55 * @author Stanley Man-Kit Ho
56 */
57abstract class RSASignature extends java.security.SignatureSpi
58{
59 // message digest implementation we use
60 private final MessageDigest messageDigest;
61
62 // flag indicating whether the digest is reset
63 private boolean needsReset;
64
65 // the signing key
66 private Key privateKey = null;
67
68 // the verification key
69 private Key publicKey = null;
70
71
72 RSASignature(String digestName) {
73
74 try {
75 messageDigest = MessageDigest.getInstance(digestName);
76
77 } catch (NoSuchAlgorithmException e) {
78 throw new ProviderException(e);
79 }
80
81 needsReset = false;
82 }
83
84 public static final class SHA1 extends RSASignature {
85 public SHA1() {
86 super("SHA1");
87 }
88 }
89
90 public static final class MD5 extends RSASignature {
91 public MD5() {
92 super("MD5");
93 }
94 }
95
96 public static final class MD2 extends RSASignature {
97 public MD2() {
98 super("MD2");
99 }
100 }
101
102 /**
103 * Initializes this signature object with the specified
104 * public key for verification operations.
105 *
106 * @param publicKey the public key of the identity whose signature is
107 * going to be verified.
108 *
109 * @exception InvalidKeyException if the key is improperly
110 * encoded, parameters are missing, and so on.
111 */
112 protected void engineInitVerify(PublicKey key)
113 throws InvalidKeyException
114 {
115 // This signature accepts only RSAPublicKey
116 if ((key instanceof java.security.interfaces.RSAPublicKey) == false) {
117 throw new InvalidKeyException("Key type not supported");
118 }
119
120 java.security.interfaces.RSAPublicKey rsaKey =
121 (java.security.interfaces.RSAPublicKey) key;
122
123 if ((key instanceof sun.security.mscapi.RSAPublicKey) == false) {
124
125 // convert key to MSCAPI format
126
127 byte[] modulusBytes = rsaKey.getModulus().toByteArray();
128
129 // Adjust key length due to sign bit
130 int keyBitLength = (modulusBytes[0] == 0)
131 ? (modulusBytes.length - 1) * 8
132 : modulusBytes.length * 8;
133
134 byte[] keyBlob = generatePublicKeyBlob(
135 keyBitLength, modulusBytes,
136 rsaKey.getPublicExponent().toByteArray());
137
138 publicKey = importPublicKey(keyBlob, keyBitLength);
139
140 } else {
141 publicKey = (sun.security.mscapi.RSAPublicKey) key;
142 }
143
144 if (needsReset) {
145 messageDigest.reset();
146 needsReset = false;
147 }
148 }
149
150 /**
151 * Initializes this signature object with the specified
152 * private key for signing operations.
153 *
154 * @param privateKey the private key of the identity whose signature
155 * will be generated.
156 *
157 * @exception InvalidKeyException if the key is improperly
158 * encoded, parameters are missing, and so on.
159 */
160 protected void engineInitSign(PrivateKey key)
161 throws InvalidKeyException
162 {
163 // This signature accepts only RSAPrivateKey
164 if ((key instanceof sun.security.mscapi.RSAPrivateKey) == false) {
165 throw new InvalidKeyException("Key type not supported");
166 }
167 privateKey = (sun.security.mscapi.RSAPrivateKey) key;
168
169 // Determine byte length from bit length
170 int keySize = (privateKey.bitLength() + 7) >> 3;
171
172 if (keySize < 64)
173 throw new InvalidKeyException(
174 "RSA keys must be at least 512 bits long");
175
176 if (needsReset) {
177 messageDigest.reset();
178 needsReset = false;
179 }
180 }
181
182 /**
183 * Updates the data to be signed or verified
184 * using the specified byte.
185 *
186 * @param b the byte to use for the update.
187 *
188 * @exception SignatureException if the engine is not initialized
189 * properly.
190 */
191 protected void engineUpdate(byte b) throws SignatureException
192 {
193 messageDigest.update(b);
194 needsReset = true;
195 }
196
197 /**
198 * Updates the data to be signed or verified, using the
199 * specified array of bytes, starting at the specified offset.
200 *
201 * @param b the array of bytes
202 * @param off the offset to start from in the array of bytes
203 * @param len the number of bytes to use, starting at offset
204 *
205 * @exception SignatureException if the engine is not initialized
206 * properly
207 */
208 protected void engineUpdate(byte[] b, int off, int len)
209 throws SignatureException
210 {
211 messageDigest.update(b, off, len);
212 needsReset = true;
213 }
214
215 /**
216 * Updates the data to be signed or verified, using the
217 * specified ByteBuffer.
218 *
219 * @param input the ByteBuffer
220 */
221 protected void engineUpdate(ByteBuffer input)
222 {
223 messageDigest.update(input);
224 needsReset = true;
225 }
226
227 /**
228 * Returns the signature bytes of all the data
229 * updated so far.
230 * The format of the signature depends on the underlying
231 * signature scheme.
232 *
233 * @return the signature bytes of the signing operation's result.
234 *
235 * @exception SignatureException if the engine is not
236 * initialized properly or if this signature algorithm is unable to
237 * process the input data provided.
238 */
239 protected byte[] engineSign() throws SignatureException {
240
241 byte[] hash = messageDigest.digest();
242 needsReset = false;
243
244 // Sign hash using MS Crypto APIs
245
246 byte[] result = signHash(hash, hash.length,
247 messageDigest.getAlgorithm(), privateKey.getHCryptProvider(),
248 privateKey.getHCryptKey());
249
250 // Convert signature array from little endian to big endian
251 return convertEndianArray(result);
252 }
253
254 /**
255 * Convert array from big endian to little endian, or vice versa.
256 */
257 private byte[] convertEndianArray(byte[] byteArray)
258 {
259 if (byteArray == null || byteArray.length == 0)
260 return byteArray;
261
262 byte [] retval = new byte[byteArray.length];
263
264 // make it big endian
265 for (int i=0;i < byteArray.length;i++)
266 retval[i] = byteArray[byteArray.length - i - 1];
267
268 return retval;
269 }
270
271 /**
272 * Sign hash using Microsoft Crypto API with HCRYPTKEY.
273 * The returned data is in little-endian.
274 */
275 private native static byte[] signHash(byte[] hash, int hashSize,
276 String hashAlgorithm, long hCryptProv, long hCryptKey)
277 throws SignatureException;
278
279 /**
280 * Verify a signed hash using Microsoft Crypto API with HCRYPTKEY.
281 */
282 private native static boolean verifySignedHash(byte[] hash, int hashSize,
283 String hashAlgorithm, byte[] signature, int signatureSize,
284 long hCryptProv, long hCryptKey) throws SignatureException;
285
286 /**
287 * Verifies the passed-in signature.
288 *
289 * @param sigBytes the signature bytes to be verified.
290 *
291 * @return true if the signature was verified, false if not.
292 *
293 * @exception SignatureException if the engine is not
294 * initialized properly, the passed-in signature is improperly
295 * encoded or of the wrong type, if this signature algorithm is unable to
296 * process the input data provided, etc.
297 */
298 protected boolean engineVerify(byte[] sigBytes)
299 throws SignatureException
300 {
301 byte[] hash = messageDigest.digest();
302 needsReset = false;
303
304 return verifySignedHash(hash, hash.length,
305 messageDigest.getAlgorithm(), convertEndianArray(sigBytes),
306 sigBytes.length, publicKey.getHCryptProvider(),
307 publicKey.getHCryptKey());
308 }
309
310 /**
311 * Sets the specified algorithm parameter to the specified
312 * value. This method supplies a general-purpose mechanism through
313 * which it is possible to set the various parameters of this object.
314 * A parameter may be any settable parameter for the algorithm, such as
315 * a parameter size, or a source of random bits for signature generation
316 * (if appropriate), or an indication of whether or not to perform
317 * a specific but optional computation. A uniform algorithm-specific
318 * naming scheme for each parameter is desirable but left unspecified
319 * at this time.
320 *
321 * @param param the string identifier of the parameter.
322 *
323 * @param value the parameter value.
324 *
325 * @exception InvalidParameterException if <code>param</code> is an
326 * invalid parameter for this signature algorithm engine,
327 * the parameter is already set
328 * and cannot be set again, a security exception occurs, and so on.
329 *
330 * @deprecated Replaced by {@link
331 * #engineSetParameter(java.security.spec.AlgorithmParameterSpec)
332 * engineSetParameter}.
333 */
334 protected void engineSetParameter(String param, Object value)
335 throws InvalidParameterException
336 {
337 throw new InvalidParameterException("Parameter not supported");
338 }
339
340
341 /**
342 * Gets the value of the specified algorithm parameter.
343 * This method supplies a general-purpose mechanism through which it
344 * is possible to get the various parameters of this object. A parameter
345 * may be any settable parameter for the algorithm, such as a parameter
346 * size, or a source of random bits for signature generation (if
347 * appropriate), or an indication of whether or not to perform a
348 * specific but optional computation. A uniform algorithm-specific
349 * naming scheme for each parameter is desirable but left unspecified
350 * at this time.
351 *
352 * @param param the string name of the parameter.
353 *
354 * @return the object that represents the parameter value, or null if
355 * there is none.
356 *
357 * @exception InvalidParameterException if <code>param</code> is an
358 * invalid parameter for this engine, or another exception occurs while
359 * trying to get this parameter.
360 *
361 * @deprecated
362 */
363 protected Object engineGetParameter(String param)
364 throws InvalidParameterException
365 {
366 throw new InvalidParameterException("Parameter not supported");
367 }
368
369 /**
370 * Generates a public-key BLOB from a key's components.
371 */
372 private native byte[] generatePublicKeyBlob(
373 int keyBitLength, byte[] modulus, byte[] publicExponent);
374
375 /**
376 * Imports a public-key BLOB.
377 */
378 private native RSAPublicKey importPublicKey(byte[] keyBlob, int keySize);
379}