summaryrefslogtreecommitdiffstats
path: root/pki/base/util/src/netscape/security/provider
diff options
context:
space:
mode:
Diffstat (limited to 'pki/base/util/src/netscape/security/provider')
-rw-r--r--pki/base/util/src/netscape/security/provider/CMS.java48
-rw-r--r--pki/base/util/src/netscape/security/provider/DSA.java686
-rwxr-xr-xpki/base/util/src/netscape/security/provider/DSAKeyFactory.java248
-rw-r--r--pki/base/util/src/netscape/security/provider/DSAKeyPairGenerator.java405
-rwxr-xr-xpki/base/util/src/netscape/security/provider/DSAParameterGenerator.java300
-rwxr-xr-xpki/base/util/src/netscape/security/provider/DSAParameters.java133
-rw-r--r--pki/base/util/src/netscape/security/provider/DSAPrivateKey.java150
-rw-r--r--pki/base/util/src/netscape/security/provider/DSAPublicKey.java135
-rw-r--r--pki/base/util/src/netscape/security/provider/MD5.java390
-rw-r--r--pki/base/util/src/netscape/security/provider/RSAPublicKey.java148
-rw-r--r--pki/base/util/src/netscape/security/provider/SHA.java362
-rw-r--r--pki/base/util/src/netscape/security/provider/Sun.java133
-rw-r--r--pki/base/util/src/netscape/security/provider/SystemIdentity.java76
-rw-r--r--pki/base/util/src/netscape/security/provider/SystemSigner.java84
-rw-r--r--pki/base/util/src/netscape/security/provider/X509CertificateFactory.java59
15 files changed, 3357 insertions, 0 deletions
diff --git a/pki/base/util/src/netscape/security/provider/CMS.java b/pki/base/util/src/netscape/security/provider/CMS.java
new file mode 100644
index 000000000..62f0e1392
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/CMS.java
@@ -0,0 +1,48 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.io.*;
+import java.util.*;
+import java.security.*;
+/**
+ * The CMS Security Provider.
+ */
+
+public final class CMS extends Provider {
+
+ private static final String INFO = "CMS " +
+ "(DSA key/parameter generation; DSA signing; " +
+ "SHA-1, MD5 digests; SecureRandom; X.509 certificates)";
+
+ public CMS() {
+ /* We are the SUN provider */
+ super("CMS", 1.0, INFO);
+
+ AccessController.doPrivileged(new java.security.PrivilegedAction() {
+ public Object run() {
+ /*
+ * Certificates
+ */
+ put("CertificateFactory.X.509", "netscape.security.provider.X509CertificateFactory");
+ put("Alg.Alias.CertificateFactory.X.509", "X.509");
+ return null;
+ }
+ });
+ }
+}
diff --git a/pki/base/util/src/netscape/security/provider/DSA.java b/pki/base/util/src/netscape/security/provider/DSA.java
new file mode 100644
index 000000000..507627e15
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/DSA.java
@@ -0,0 +1,686 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.io.*;
+import java.util.*;
+import java.math.BigInteger;
+import java.security.AlgorithmParameters;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.InvalidParameterException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.PublicKey;
+import java.security.PrivateKey;
+import java.security.SecureRandom;
+import java.security.Signature;
+import java.security.SignatureException;
+import java.security.interfaces.*;
+import java.security.spec.DSAParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
+
+import netscape.security.util.BigInt;
+import netscape.security.util.DerValue;
+import netscape.security.util.DerInputStream;
+import netscape.security.util.DerOutputStream;
+import netscape.security.x509.AlgIdDSA;
+
+/**
+ * The Digital Signature Standard (using the Digital Signature
+ * Algorithm), as described in fips186 of the National Instute of
+ * Standards and Technology (NIST), using fips180-1 (SHA-1).
+ *
+ * @author Benjamin Renaud
+ *
+ * @version 1.86, 97/09/17
+ *
+ * @see DSAPublicKey
+ * @see DSAPrivateKey
+ */
+
+public final class DSA extends Signature {
+
+ /* Are we debugging? */
+ private static boolean debug = false;
+
+ /* The parameter object */
+ private DSAParams params;
+
+ /* algorithm parameters */
+ private BigInteger presetP, presetQ, presetG;
+
+ /* The public key, if any */
+ private BigInteger presetY;
+
+ /* The private key, if any */
+ private BigInteger presetX;
+
+ /* The SHA hash for the data */
+ private MessageDigest dataSHA;
+
+ /* The random seed used to generate k */
+ private int[] Kseed;
+
+ /* The random seed used to generate k (specified by application) */
+ private byte[] KseedAsByteArray;
+
+ /*
+ * The random seed used to generate k
+ * (prevent the same Kseed from being used twice in a row
+ */
+ private int[] previousKseed;
+
+ /* The RNG used to output a seed for generating k */
+ private SecureRandom signingRandom;
+
+ /**
+ * Construct a blank DSA object. It can generate keys, but must be
+ * initialized before being usable for signing or verifying.
+ */
+ public DSA() throws NoSuchAlgorithmException {
+ super("SHA/DSA");
+ dataSHA = MessageDigest.getInstance("SHA");
+ }
+
+ /**
+ * Initialize the DSA object with a DSA private key.
+ *
+ * @param privateKey the DSA private key
+ *
+ * @exception InvalidKeyException if the key is not a valid DSA private
+ * key.
+ */
+ protected void engineInitSign(PrivateKey privateKey)
+ throws InvalidKeyException {
+ if (!(privateKey instanceof java.security.interfaces.DSAPrivateKey)) {
+ throw new InvalidKeyException("not a DSA private key: " +
+ privateKey);
+ }
+ java.security.interfaces.DSAPrivateKey priv =
+ (java.security.interfaces.DSAPrivateKey)privateKey;
+
+ this.presetX = priv.getX();
+ initialize(priv.getParams());
+ }
+
+ /**
+ * Initialize the DSA object with a DSA public key.
+ *
+ * @param publicKey the DSA public key.
+ *
+ * @exception InvalidKeyException if the key is not a valid DSA public
+ * key.
+ */
+ protected void engineInitVerify(PublicKey publicKey)
+ throws InvalidKeyException {
+ if (!(publicKey instanceof java.security.interfaces.DSAPublicKey)) {
+ throw new InvalidKeyException("not a DSA public key: " +
+ publicKey);
+ }
+ java.security.interfaces.DSAPublicKey pub =
+ (java.security.interfaces.DSAPublicKey)publicKey;
+ this.presetY = pub.getY();
+ initialize(pub.getParams());
+ }
+
+ private void initialize(DSAParams params) {
+ dataSHA.reset();
+ setParams(params);
+ }
+
+ private void initialize(AlgorithmParameters params)
+ throws InvalidAlgorithmParameterException {
+ try {
+ DSAParameterSpec dsaParamSpec;
+ dsaParamSpec = (DSAParameterSpec)params.getParameterSpec
+ (DSAParameterSpec.class);
+ dataSHA.reset();
+ setParams(dsaParamSpec);
+ } catch (InvalidParameterSpecException e) {
+ throw new InvalidAlgorithmParameterException
+ ("Inappropriate parameter");
+ }
+ }
+
+ /**
+ * Sign all the data thus far updated. The signature is formatted
+ * according to the Canonical Encoding Rules, returned as a DER
+ * sequence of Integer, r and s.
+ *
+ * @return a signature block formatted according to the Canonical
+ * Encoding Rules.
+ *
+ * @exception SignatureException if the signature object was not
+ * properly initialized, or if another exception occurs.
+ *
+ * @see netscape.security.provider.DSA#engineUpdate
+ * @see netscape.security.provider.DSA#engineVerify
+ */
+ protected byte[] engineSign() throws SignatureException {
+ BigInteger k = generateK(presetQ);
+ BigInteger r = generateR(presetP, presetQ, presetG, k);
+ BigInteger s = generateS(presetX, presetQ, r, k);
+
+ // got to convert to BigInt...
+ BigInt rAsBigInt = new BigInt(r.toByteArray());
+ BigInt sAsBigInt = new BigInt(s.toByteArray());
+
+ try {
+ DerOutputStream outseq = new DerOutputStream(100);
+ outseq.putInteger(rAsBigInt);
+ outseq.putInteger(sAsBigInt);
+ DerValue result = new DerValue(DerValue.tag_Sequence,
+ outseq.toByteArray());
+
+ return result.toByteArray();
+
+ } catch (IOException e) {
+ throw new SignatureException("error encoding signature");
+ }
+ }
+
+ /**
+ * Verify all the data thus far updated.
+ *
+ * @param signature the alledged signature, encoded using the
+ * Canonical Encoding Rules, as a sequence of integers, r and s.
+ *
+ * @exception SignatureException if the signature object was not
+ * properly initialized, or if another exception occurs.
+ *
+ * @see netscape.security.provider.DSA#engineUpdate
+ * @see netscape.security.provider.DSA#engineSign
+ */
+ protected boolean engineVerify(byte[] signature)
+ throws SignatureException {
+
+ BigInteger r = null;
+ BigInteger s = null;
+ // first decode the signature.
+ try {
+ DerInputStream in = new DerInputStream(signature);
+ DerValue[] values = in.getSequence(2);
+
+ r = values[0].getInteger().toBigInteger();
+ s = values[1].getInteger().toBigInteger();
+
+ } catch (IOException e) {
+ throw new SignatureException("invalid encoding for signature");
+ }
+ BigInteger w = generateW(presetP, presetQ, presetG, s);
+ BigInteger v = generateV(presetY, presetP, presetQ, presetG, w, r);
+
+ return v.equals(r);
+ }
+
+ private void reset() {
+ dataSHA.reset();
+ }
+
+ BigInteger generateR(BigInteger p, BigInteger q, BigInteger g,
+ BigInteger k) {
+ BigInteger temp = g.modPow(k, p);
+ return temp.remainder(q);
+
+ }
+
+ BigInteger generateS(BigInteger x, BigInteger q,
+ BigInteger r, BigInteger k) {
+
+ byte[] s2 = dataSHA.digest();
+ BigInteger temp = new BigInteger(1, s2);
+ BigInteger k1 = k.modInverse(q);
+
+ BigInteger s = x.multiply(r);
+ s = temp.add(s);
+ s = k1.multiply(s);
+ return s.remainder(q);
+ }
+
+ BigInteger generateW(BigInteger p, BigInteger q,
+ BigInteger g, BigInteger s) {
+ return s.modInverse(q);
+ }
+
+ BigInteger generateV(BigInteger y, BigInteger p,
+ BigInteger q, BigInteger g,
+ BigInteger w, BigInteger r) {
+
+ byte[] s2 = dataSHA.digest();
+ BigInteger temp = new BigInteger(1, s2);
+
+ temp = temp.multiply(w);
+ BigInteger u1 = temp.remainder(q);
+
+ BigInteger u2 = (r.multiply(w)).remainder(q);
+
+ BigInteger t1 = g.modPow(u1,p);
+ BigInteger t2 = y.modPow(u2,p);
+ BigInteger t3 = t1.multiply(t2);
+ BigInteger t5 = t3.remainder(p);
+ return t5.remainder(q);
+ }
+
+ /*
+ * Please read bug report 4044247 for an alternative, faster,
+ * NON-FIPS approved method to generate K
+ */
+ BigInteger generateK(BigInteger q) {
+
+ BigInteger k = null;
+
+ // The application specified a Kseed for us to use.
+ // Note that we do not allow usage of the same Kseed twice in a row
+ if (Kseed != null && compareSeeds(Kseed, previousKseed) != 0) {
+ k = generateK(Kseed, q);
+ if (k.signum() > 0 && k.compareTo(q) < 0) {
+ previousKseed = new int [Kseed.length];
+ System.arraycopy(Kseed, 0, previousKseed, 0, Kseed.length);
+ return k;
+ }
+ }
+
+ // The application did not specify a Kseed for us to use.
+ // We'll generate a new Kseed by getting random bytes from
+ // a SecureRandom object.
+ SecureRandom random = getSigningRandom();
+
+ while (true) {
+ int[] seed = new int[5];
+
+ for (int i = 0; i < 5; i++)
+ seed[i] = random.nextInt();
+ k = generateK(seed, q);
+ if (k.signum() > 0 && k.compareTo(q) < 0) {
+ previousKseed = new int [seed.length];
+ System.arraycopy(seed, 0, previousKseed, 0, seed.length);
+ return k;
+ }
+ }
+ }
+
+ // Use the application-specified SecureRandom Object if provided.
+ // Otherwise, use our default SecureRandom Object.
+ private SecureRandom getSigningRandom() {
+ if (signingRandom == null) {
+ if (appRandom != null)
+ signingRandom = appRandom;
+ else
+ signingRandom = new SecureRandom();
+ }
+ return signingRandom;
+ }
+
+ /*
+ * return 0 if equal
+ * return 1 if not equal
+ */
+ private int compareSeeds(int []seed1, int []seed2) {
+
+ if ((seed1 == null && seed1 == null) ||
+ (seed1 == null && seed2 != null) ||
+ (seed1 != null && seed2 == null) ||
+ seed1.length != seed2.length)
+ return 1;
+
+ for (int i = 0; i < seed1.length; i++) {
+ if (seed1[i] != seed2[i])
+ return 1;
+ }
+
+ return 0;
+
+ }
+
+ /**
+ * Compute k for a DSA signature.
+ *
+ * @param seed the seed for generating k. This seed should be
+ * secure. This is what is refered to as the KSEED in the DSA
+ * specification.
+ *
+ * @param g the g parameter from the DSA key pair.
+ */
+ BigInteger generateK(int[] seed, BigInteger q) {
+
+ // check out t in the spec.
+ int[] t = { 0xEFCDAB89, 0x98BADCFE, 0x10325476,
+ 0xC3D2E1F0, 0x67452301 };
+ //
+ int[] tmp = DSA.SHA_7(seed, t);
+ byte[] tmpBytes = new byte[tmp.length * 4];
+ for (int i = 0; i < tmp.length; i++) {
+ int k = tmp[i];
+ for (int j = 0; j < 4; j++) {
+ tmpBytes[(i * 4) + j] = (byte) (k >>> (24 - (j * 8)));
+ }
+ }
+ BigInteger k = new BigInteger(1, tmpBytes).mod(q);
+ return k;
+ }
+
+ // Constants for each round
+ private static final int round1_kt = 0x5a827999;
+ private static final int round2_kt = 0x6ed9eba1;
+ private static final int round3_kt = 0x8f1bbcdc;
+ private static final int round4_kt = 0xca62c1d6;
+
+ /**
+ * Computes set 1 thru 7 of SHA-1 on m1. */
+ static int[] SHA_7(int [] m1, int[] h) {
+
+ int[] W = new int[80];
+ System.arraycopy(m1,0,W,0,m1.length);
+ int temp = 0;
+
+ for (int t = 16; t <= 79; t++){
+ temp = W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16];
+ W[t] = ((temp << 1) | (temp >>>(32 - 1)));
+ }
+
+ int a = h[0],b = h[1],c = h[2], d = h[3], e = h[4];
+ for (int i = 0; i < 20; i++) {
+ temp = ((a<<5) | (a>>>(32-5))) +
+ ((b&c)|((~b)&d))+ e + W[i] + round1_kt;
+ e = d;
+ d = c;
+ c = ((b<<30) | (b>>>(32-30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 2
+ for (int i = 20; i < 40; i++) {
+ temp = ((a<<5) | (a>>>(32-5))) +
+ (b ^ c ^ d) + e + W[i] + round2_kt;
+ e = d;
+ d = c;
+ c = ((b<<30) | (b>>>(32-30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 3
+ for (int i = 40; i < 60; i++) {
+ temp = ((a<<5) | (a>>>(32-5))) +
+ ((b&c)|(b&d)|(c&d)) + e + W[i] + round3_kt;
+ e = d;
+ d = c;
+ c = ((b<<30) | (b>>>(32-30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 4
+ for (int i = 60; i < 80; i++) {
+ temp = ((a<<5) | (a>>>(32-5))) +
+ (b ^ c ^ d) + e + W[i] + round4_kt;
+ e = d;
+ d = c;
+ c = ((b<<30) | (b>>>(32-30)));
+ b = a;
+ a = temp;
+ }
+ int[] md = new int[5];
+ md[0] = h[0] + a;
+ md[1] = h[1] + b;
+ md[2] = h[2] + c;
+ md[3] = h[3] + d;
+ md[4] = h[4] + e;
+ return md;
+ }
+
+
+ /**
+ * This implementation recognizes the following parameter:<dl>
+ *
+ * <dt><tt>Kseed</tt>
+ *
+ * <dd>a byte array.
+ *
+ * </dl>
+ *
+ * @deprecated
+ */
+ protected void engineSetParameter(String key, Object param) {
+
+ if (key.equals("KSEED")) {
+
+ if (param instanceof byte[]) {
+
+ Kseed = byteArray2IntArray((byte[])param);
+ KseedAsByteArray = (byte[])param;
+
+ } else {
+ debug("unrecognized param: " + key);
+ throw new InvalidParameterException("Kseed not a byte array");
+ }
+
+ } else {
+ throw new InvalidParameterException("invalid parameter");
+ }
+ }
+
+ /**
+ * Return the value of the requested parameter. Recognized
+ * parameters are:
+ *
+ * <dl>
+ *
+ * <dt><tt>Kseed</tt>
+ *
+ * <dd>a byte array.
+ *
+ * </dl>
+ *
+ * @return the value of the requested parameter.
+ *
+ * @deprecated
+ */
+ protected Object engineGetParameter(String key) {
+ if (key.equals("KSEED")) {
+ return KseedAsByteArray;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Set the algorithm object.
+ */
+ private void setParams(DSAParams params) {
+ this.params = params;
+ this.presetP = params.getP();
+ this.presetQ = params.getQ();
+ this.presetG = params.getG();
+ }
+
+ private void setParams(DSAParameterSpec params) {
+ this.presetP = params.getP();
+ this.presetQ = params.getQ();
+ this.presetG = params.getG();
+ }
+
+ /**
+ * Update a byte to be signed or verified.
+ *
+ * @param b the byte to updated.
+ */
+ protected void engineUpdate(byte b) {
+ dataSHA.update(b);
+ }
+
+ /**
+ * Update an array of bytes to be signed or verified.
+ *
+ * @param data the bytes to be updated.
+ */
+ protected void engineUpdate(byte[] data, int off, int len) {
+ dataSHA.update(data, off, len);
+ }
+
+ /**
+ * Return a human readable rendition of the engine.
+ */
+ public String toString() {
+ String printable = "DSA Signature";
+ if (presetP != null && presetQ != null && presetG != null) {
+ printable += "\n\tp: " + presetP.toString(16);
+ printable += "\n\tq: " + presetQ.toString(16);
+ printable += "\n\tg: " + presetG.toString(16);
+ } else {
+ printable += "\n\t P, Q or G not initialized.";
+ }
+ if (presetY != null) {
+ printable += "\n\ty: " + presetY.toString(16);
+ }
+ if (presetY == null && presetX == null) {
+ printable += "\n\tUNINIIALIZED";
+ }
+ return printable;
+ }
+
+ /*
+ * Utility routine for converting a byte array into an int array
+ */
+ private int[] byteArray2IntArray(byte[] byteArray) {
+
+ int j = 0;
+ byte[] newBA;
+ int mod = byteArray.length % 4;
+
+ // guarantee that the incoming byteArray is a multiple of 4
+ // (pad with 0's)
+ switch (mod) {
+ case 3: newBA = new byte[byteArray.length + 1]; break;
+ case 2: newBA = new byte[byteArray.length + 2]; break;
+ case 1: newBA = new byte[byteArray.length + 3]; break;
+ default: newBA = new byte[byteArray.length + 0]; break;
+ }
+ System.arraycopy(byteArray, 0, newBA, 0, byteArray.length);
+
+ // copy each set of 4 bytes in the byte array into an integer
+ int[] newSeed = new int[newBA.length / 4];
+ for (int i = 0; i < newBA.length; i += 4) {
+ newSeed[j] = newBA[i + 3] & 0xFF;
+ newSeed[j] |= (newBA[i + 2] << 8) & 0xFF00;
+ newSeed[j] |= (newBA[i + 1] << 16) & 0xFF0000;
+ newSeed[j] |= (newBA[i + 0] << 24) & 0xFF000000;
+ j++;
+ }
+
+ return newSeed;
+ }
+
+ /* We include the test vectors from the DSA specification, FIPS
+ 186, and the FIPS 186 Change No 1, which updates the test
+ vector using SHA-1 instead of SHA (for both the G function and
+ the message hash. */
+
+ static void testDSA() throws Exception {
+ PrintStream p = System.out;
+
+ DSA dsa = new DSA();
+ int[] Kseed = { 0x687a66d9, 0x0648f993, 0x867e121f,
+ 0x4ddf9ddb, 0x1205584 };
+ BigInteger k = dsa.generateK(Kseed, q512);
+ p.println("k: " + k.toString(16));
+ BigInteger r = dsa.generateR(p512, q512, g512, k);
+ p.println("r: " + r.toString(16));
+ byte[] abc = { 0x61, 0x62, 0x63 };
+ dsa.dataSHA.update(abc);
+ BigInteger s = dsa.generateS(x512, q512, r, k);
+ p.println("s: " + s.toString(16));
+
+ dsa.dataSHA.update(abc);
+ BigInteger w = dsa.generateW(p512, q512, g512, s);
+ p.println("w: " + w.toString(16));
+ BigInteger v = dsa.generateV(y512, p512, q512, g512, w, r);
+ p.println("v: " + v.toString(16));
+ if (v.equals(r)) {
+ p.println("signature verifies.");
+ } else {
+ p.println("signature does not verify.");
+ }
+ }
+
+ /* Test vector: 512-bit keys generated by our key generator. */
+
+ static BigInteger p512 =
+ new BigInteger("fca682ce8e12caba26efccf7110e526db078b05edecb" +
+ "cd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e1" +
+ "2ed0899bcd132acd50d99151bdc43ee737592e17", 16);
+
+ static BigInteger q512 =
+ new BigInteger("962eddcc369cba8ebb260ee6b6a126d9346e38c5", 16);
+
+ static BigInteger g512 =
+ new BigInteger("678471b27a9cf44ee91a49c5147db1a9aaf244f05a43" +
+ "4d6486931d2d14271b9e35030b71fd73da179069b32e" +
+ "2935630e1c2062354d0da20a6c416e50be794ca4", 16);
+
+ static BigInteger x512 =
+ new BigInteger("3406c2d71b04b5fc0db62afcad58a6607d3de688", 16);
+
+ static BigInteger y512 =
+ new BigInteger("2d335d76b8ec9d610aa8f2cbb4b149fd96fdd" +
+ "3a9a6e62bd6c2e01d406be4d1d72718a2fe08bea6d12f5e452474461f70f4" +
+ "dea60508e9fe2eaec23d2ec5d1a866", 16);
+
+ /* Official NIST 512-bit test keys */
+
+ static String pString = "8df2a494492276aa3d25759bb06869cbeac0d83afb8d0" +
+ "cf7cbb8324f0d7882e5d0762fc5b7210eafc2e9adac32ab7aac49693dfbf83724c2ec" +
+ "0736ee31c80291";
+
+ static BigInteger testP = new BigInteger(pString, 16);
+
+ static String gString = "626d027839ea0a13413163a55b4cb500299d5522956ce" +
+ "fcb3bff10f399ce2c2e71cb9de5fa24babf58e5b79521925c9cc42e9f6f464b088cc5" +
+ "72af53e6d78802";
+
+ static BigInteger testG = new BigInteger(gString, 16);
+
+ static BigInteger testQ = new BigInteger("c773218c737ec8ee993b4f2ded30" +
+ "f48edace915f", 16);
+
+ static BigInteger testX = new BigInteger("2070b3223dba372fde1c0ffc7b2e" +
+ "3b498b260614", 16);
+
+ static String yString = "19131871d75b1612a819f29d78d1b0d7346f7aa77" +
+ "bb62a859bfd6c5675da9d212d3a36ef1672ef660b8c7c255cc0ec74858fba33f44c06" +
+ "699630a76b030ee333";
+
+ static BigInteger testY = new BigInteger(yString, 16);
+
+ /* End test vector values */
+
+ private static void debug(Exception e) {
+ if (debug) {
+ e.printStackTrace();
+ }
+ }
+
+ private static void debug(String s) {
+ if (debug) {
+ System.err.println(s);
+ }
+ }
+
+}
diff --git a/pki/base/util/src/netscape/security/provider/DSAKeyFactory.java b/pki/base/util/src/netscape/security/provider/DSAKeyFactory.java
new file mode 100755
index 000000000..e97544a49
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/DSAKeyFactory.java
@@ -0,0 +1,248 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.util.*;
+import java.lang.*;
+import java.security.Key;
+import java.security.PublicKey;
+import java.security.PrivateKey;
+import java.security.KeyFactorySpi;
+import java.security.InvalidKeyException;
+import java.security.interfaces.DSAParams;
+import java.security.spec.DSAPublicKeySpec;
+import java.security.spec.DSAPrivateKeySpec;
+import java.security.spec.KeySpec;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.X509EncodedKeySpec;
+import java.security.spec.PKCS8EncodedKeySpec;
+
+/**
+ * This class implements the DSA key factory of the Sun provider.
+ *
+ * @author Jan Luehe
+ *
+ * @version 1.8, 97/12/10
+ *
+ * @since JDK1.2
+ */
+
+public class DSAKeyFactory extends KeyFactorySpi {
+
+ /**
+ * Generates a public key object from the provided key specification
+ * (key material).
+ *
+ * @param keySpec the specification (key material) of the public key
+ *
+ * @return the public key
+ *
+ * @exception InvalidKeySpecException if the given key specification
+ * is inappropriate for this key factory to produce a public key.
+ */
+ protected PublicKey engineGeneratePublic(KeySpec keySpec)
+ throws InvalidKeySpecException {
+ try {
+ if (keySpec instanceof DSAPublicKeySpec) {
+ DSAPublicKeySpec dsaPubKeySpec = (DSAPublicKeySpec)keySpec;
+ return new DSAPublicKey(dsaPubKeySpec.getY(),
+ dsaPubKeySpec.getP(),
+ dsaPubKeySpec.getQ(),
+ dsaPubKeySpec.getG());
+
+ } else if (keySpec instanceof X509EncodedKeySpec) {
+ return new DSAPublicKey
+ (((X509EncodedKeySpec)keySpec).getEncoded());
+
+ } else {
+ throw new InvalidKeySpecException
+ ("Inappropriate key specification");
+ }
+ } catch (InvalidKeyException e) {
+ throw new InvalidKeySpecException
+ ("Inappropriate key specification: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Generates a private key object from the provided key specification
+ * (key material).
+ *
+ * @param keySpec the specification (key material) of the private key
+ *
+ * @return the private key
+ *
+ * @exception InvalidKeySpecException if the given key specification
+ * is inappropriate for this key factory to produce a private key.
+ */
+ protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
+ throws InvalidKeySpecException {
+ try {
+ if (keySpec instanceof DSAPrivateKeySpec) {
+ DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
+ return new DSAPrivateKey(dsaPrivKeySpec.getX(),
+ dsaPrivKeySpec.getP(),
+ dsaPrivKeySpec.getQ(),
+ dsaPrivKeySpec.getG());
+
+ } else if (keySpec instanceof PKCS8EncodedKeySpec) {
+ return new DSAPrivateKey
+ (((PKCS8EncodedKeySpec)keySpec).getEncoded());
+
+ } else {
+ throw new InvalidKeySpecException
+ ("Inappropriate key specification");
+ }
+ } catch (InvalidKeyException e) {
+ throw new InvalidKeySpecException
+ ("Inappropriate key specification: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Returns a specification (key material) of the given key object
+ * in the requested format.
+ *
+ * @param key the key
+ *
+ * @param keySpec the requested format in which the key material shall be
+ * returned
+ *
+ * @return the underlying key specification (key material) in the
+ * requested format
+ *
+ * @exception InvalidKeySpecException if the requested key specification is
+ * inappropriate for the given key, or the given key cannot be processed
+ * (e.g., the given key has an unrecognized algorithm or format).
+ */
+ protected KeySpec engineGetKeySpec(Key key, Class keySpec)
+ throws InvalidKeySpecException {
+
+ DSAParams params;
+
+ try {
+
+ if (key instanceof java.security.interfaces.DSAPublicKey) {
+
+ // Determine valid key specs
+ Class dsaPubKeySpec = Class.forName
+ ("java.security.spec.DSAPublicKeySpec");
+ Class x509KeySpec = Class.forName
+ ("java.security.spec.X509EncodedKeySpec");
+
+ if (dsaPubKeySpec.isAssignableFrom(keySpec)) {
+ java.security.interfaces.DSAPublicKey dsaPubKey
+ = (java.security.interfaces.DSAPublicKey)key;
+ params = dsaPubKey.getParams();
+ return new DSAPublicKeySpec(dsaPubKey.getY(),
+ params.getP(),
+ params.getQ(),
+ params.getG());
+
+ } else if (x509KeySpec.isAssignableFrom(keySpec)) {
+ return new X509EncodedKeySpec(key.getEncoded());
+
+ } else {
+ throw new InvalidKeySpecException
+ ("Inappropriate key specification");
+ }
+
+ } else if (key instanceof java.security.interfaces.DSAPrivateKey) {
+
+ // Determine valid key specs
+ Class dsaPrivKeySpec = Class.forName
+ ("java.security.spec.DSAPrivateKeySpec");
+ Class pkcs8KeySpec = Class.forName
+ ("java.security.spec.PKCS8EncodedKeySpec");
+
+ if (dsaPrivKeySpec.isAssignableFrom(keySpec)) {
+ java.security.interfaces.DSAPrivateKey dsaPrivKey
+ = (java.security.interfaces.DSAPrivateKey)key;
+ params = dsaPrivKey.getParams();
+ return new DSAPrivateKeySpec(dsaPrivKey.getX(),
+ params.getP(),
+ params.getQ(),
+ params.getG());
+
+ } else if (pkcs8KeySpec.isAssignableFrom(keySpec)) {
+ return new PKCS8EncodedKeySpec(key.getEncoded());
+
+ } else {
+ throw new InvalidKeySpecException
+ ("Inappropriate key specification");
+ }
+
+ } else {
+ throw new InvalidKeySpecException("Inappropriate key type");
+ }
+
+ } catch (ClassNotFoundException e) {
+ throw new InvalidKeySpecException
+ ("Unsupported key specification: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Translates a key object, whose provider may be unknown or potentially
+ * untrusted, into a corresponding key object of this key factory.
+ *
+ * @param key the key whose provider is unknown or untrusted
+ *
+ * @return the translated key
+ *
+ * @exception InvalidKeyException if the given key cannot be processed by
+ * this key factory.
+ */
+ protected Key engineTranslateKey(Key key) throws InvalidKeyException {
+
+ try {
+
+ if (key instanceof java.security.interfaces.DSAPublicKey) {
+ // Check if key originates from this factory
+ if (key instanceof netscape.security.provider.DSAPublicKey) {
+ return key;
+ }
+ // Convert key to spec
+ DSAPublicKeySpec dsaPubKeySpec
+ = (DSAPublicKeySpec)engineGetKeySpec
+ (key, DSAPublicKeySpec.class);
+ // Create key from spec, and return it
+ return engineGeneratePublic(dsaPubKeySpec);
+
+ } else if (key instanceof java.security.interfaces.DSAPrivateKey) {
+ // Check if key originates from this factory
+ if (key instanceof netscape.security.provider.DSAPrivateKey) {
+ return key;
+ }
+ // Convert key to spec
+ DSAPrivateKeySpec dsaPrivKeySpec
+ = (DSAPrivateKeySpec)engineGetKeySpec
+ (key, DSAPrivateKeySpec.class);
+ // Create key from spec, and return it
+ return engineGeneratePrivate(dsaPrivKeySpec);
+
+ } else {
+ throw new InvalidKeyException("Wrong algorithm type");
+ }
+
+ } catch (InvalidKeySpecException e) {
+ throw new InvalidKeyException("Cannot translate key: "
+ + e.getMessage());
+ }
+ }
+}
diff --git a/pki/base/util/src/netscape/security/provider/DSAKeyPairGenerator.java b/pki/base/util/src/netscape/security/provider/DSAKeyPairGenerator.java
new file mode 100644
index 000000000..be5b44286
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/DSAKeyPairGenerator.java
@@ -0,0 +1,405 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.util.Hashtable;
+import java.math.BigInteger;
+import java.security.AlgorithmParameters;
+import java.security.AlgorithmParameterGenerator;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.InvalidParameterException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.ProviderException;
+import java.security.SecureRandom;
+import java.security.interfaces.DSAParams;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
+import java.security.spec.DSAParameterSpec;
+
+import netscape.security.x509.AlgIdDSA;
+
+/**
+ * This class generates DSA key parameters and public/private key
+ * pairs according to the DSS standard NIST FIPS 186. It uses the
+ * updated version of SHA, SHA-1 as described in FIPS 180-1.
+ *
+ * @author Benjamin Renaud
+ *
+ * @version 1.23, 97/12/10
+ */
+
+public class DSAKeyPairGenerator extends KeyPairGenerator
+implements java.security.interfaces.DSAKeyPairGenerator {
+
+ private static Hashtable precomputedParams;
+
+ static {
+
+ /* We support precomputed parameter for 512, 768 and 1024 bit
+ moduli. In this file we provide both the seed and counter
+ value of the generation process for each of these seeds,
+ for validation purposes. We also include the test vectors
+ from the DSA specification, FIPS 186, and the FIPS 186
+ Change No 1, which updates the test vector using SHA-1
+ instead of SHA (for both the G function and the message
+ hash.
+ */
+
+ precomputedParams = new Hashtable();
+
+ /*
+ * L = 512
+ * SEED = b869c82b35d70e1b1ff91b28e37a62ecdc34409b
+ * counter = 123
+ */
+ BigInteger p512 =
+ new BigInteger("fca682ce8e12caba26efccf7110e526db078b05edecb" +
+ "cd1eb4a208f3ae1617ae01f35b91a47e6df63413c5e1" +
+ "2ed0899bcd132acd50d99151bdc43ee737592e17", 16);
+
+ BigInteger q512 =
+ new BigInteger("962eddcc369cba8ebb260ee6b6a126d9346e38c5", 16);
+
+ BigInteger g512 =
+ new BigInteger("678471b27a9cf44ee91a49c5147db1a9aaf244f05a43" +
+ "4d6486931d2d14271b9e35030b71fd73da179069b32e" +
+ "2935630e1c2062354d0da20a6c416e50be794ca4", 16);
+
+ /*
+ * L = 768
+ * SEED = 77d0f8c4dad15eb8c4f2f8d6726cefd96d5bb399
+ * counter = 263
+ */
+ BigInteger p768 =
+ new BigInteger("e9e642599d355f37c97ffd3567120b8e25c9cd43e" +
+ "927b3a9670fbec5d890141922d2c3b3ad24800937" +
+ "99869d1e846aab49fab0ad26d2ce6a22219d470bc" +
+ "e7d777d4a21fbe9c270b57f607002f3cef8393694" +
+ "cf45ee3688c11a8c56ab127a3daf", 16);
+
+ BigInteger q768 =
+ new BigInteger("9cdbd84c9f1ac2f38d0f80f42ab952e7338bf511",
+ 16);
+
+ BigInteger g768 =
+ new BigInteger("30470ad5a005fb14ce2d9dcd87e38bc7d1b1c5fac" +
+ "baecbe95f190aa7a31d23c4dbbcbe06174544401a" +
+ "5b2c020965d8c2bd2171d3668445771f74ba084d2" +
+ "029d83c1c158547f3a9f1a2715be23d51ae4d3e5a" +
+ "1f6a7064f316933a346d3f529252", 16);
+
+
+ /*
+ * L = 1024
+ * SEED = 8d5155894229d5e689ee01e6018a237e2cae64cd
+ * counter = 92
+ */
+ BigInteger p1024 =
+ new BigInteger("fd7f53811d75122952df4a9c2eece4e7f611b7523c" +
+ "ef4400c31e3f80b6512669455d402251fb593d8d58" +
+ "fabfc5f5ba30f6cb9b556cd7813b801d346ff26660" +
+ "b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c6" +
+ "1bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554" +
+ "135a169132f675f3ae2b61d72aeff22203199dd148" +
+ "01c7", 16);
+
+ BigInteger q1024 =
+ new BigInteger("9760508f15230bccb292b982a2eb840bf0581cf5",
+ 16);
+
+ BigInteger g1024 =
+ new BigInteger("f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa" +
+ "3aea82f9574c0b3d0782675159578ebad4594fe671" +
+ "07108180b449167123e84c281613b7cf09328cc8a6" +
+ "e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f" +
+ "0bfa213562f1fb627a01243bcca4f1bea8519089a8" +
+ "83dfe15ae59f06928b665e807b552564014c3bfecf" +
+ "492a", 16);
+
+ try {
+ AlgIdDSA alg512 = new AlgIdDSA(p512, q512, g512);
+ AlgIdDSA alg768 = new AlgIdDSA(p768, q768, g768);
+ AlgIdDSA alg1024 = new AlgIdDSA(p1024, q1024, g1024);
+
+ precomputedParams.put(Integer.valueOf(512), alg512);
+ precomputedParams.put(Integer.valueOf(768), alg768);
+ precomputedParams.put(Integer.valueOf(1024), alg1024);
+
+ } catch (Exception e) {
+ throw new InternalError("initializing precomputed " +
+ "algorithm parameters for Sun DSA");
+ }
+ }
+
+
+ /* The modulus length */
+ private int modlen = 1024;
+
+ /* Generate new parameters, even if we have precomputed ones. */
+ boolean generateNewParameters = false;
+
+ /* preset algorithm parameters. */
+ private BigInteger presetP, presetQ, presetG;
+
+ /* The source of random bits to use */
+ SecureRandom random;
+
+ public DSAKeyPairGenerator() {
+ super("DSA");
+ }
+
+ public void initialize(int strength, SecureRandom random) {
+ if ((strength < 512) || (strength > 1024) || (strength % 64 != 0)) {
+ throw new InvalidParameterException
+ ("Modulus size must range from 512 to 1024 "
+ + "and be a multiple of 64");
+ }
+
+ /* Set the random */
+ this.random = random;
+ if (this.random == null) {
+ this.random = new SecureRandom();
+ }
+
+ this.modlen = strength;
+ DSAParams params = null;
+
+ /* Find the precomputed parameters, if any */
+ if (!generateNewParameters) {
+ Integer mod = Integer.valueOf(this.modlen);
+ params = (DSAParams)precomputedParams.get(mod);
+ }
+ if (params != null) {
+ setParams(params);
+ }
+ }
+
+ /**
+ * Initializes the DSA key pair generator. If <code>genParams</code>
+ * is false, a set of pre-computed parameters is used. In this case,
+ * <code>modelen</code> must be 512, 768, or 1024.
+ */
+ public void initialize(int modlen, boolean genParams, SecureRandom random)
+ throws InvalidParameterException {
+ if (genParams == false && modlen != 512 && modlen != 768
+ && modlen != 1024) {
+ throw new InvalidParameterException
+ ("No precomputed parameters for requested modulus size "
+ + "available");
+ }
+ this.generateNewParameters = genParams;
+ initialize(modlen, random);
+ }
+
+ /**
+ * Initializes the DSA object using a DSA parameter object.
+ *
+ * @param params a fully initialized DSA parameter object.
+ */
+ public void initialize(DSAParams params, SecureRandom random)
+ throws InvalidParameterException {
+ initialize(params.getP().bitLength(), random);
+ setParams(params);
+ }
+
+ /**
+ * Initializes the DSA object using a parameter object.
+ *
+ * @param params the parameter set to be used to generate
+ * the keys.
+ * @param random the source of randomness for this generator.
+ *
+ * @exception InvalidAlgorithmParameterException if the given parameters
+ * are inappropriate for this key pair generator
+ */
+ public void initialize(AlgorithmParameterSpec params, SecureRandom random)
+ throws InvalidAlgorithmParameterException {
+ if (!(params instanceof DSAParameterSpec)) {
+ throw new InvalidAlgorithmParameterException
+ ("Inappropriate parameter");
+ }
+ initialize(((DSAParameterSpec)params).getP().bitLength(),
+ random);
+ setParams((DSAParameterSpec)params);
+ }
+
+ /**
+ * Generates a pair of keys usable by any JavaSecurity compliant
+ * DSA implementation.
+ *
+ * @param rnd the source of random bits from which the random key
+ * generation parameters are drawn. In particular, this includes
+ * the XSEED parameter.
+ *
+ * @exception InvalidParameterException if the modulus is not
+ * between 512 and 1024.
+ */
+ public KeyPair generateKeyPair() {
+
+ // set random if initialize() method has been skipped
+ if (this.random == null) {
+ this.random = new SecureRandom();
+ }
+
+ if (presetP == null || presetQ == null || presetG == null ||
+ generateNewParameters) {
+
+ AlgorithmParameterGenerator dsaParamGen;
+
+ try {
+ dsaParamGen = AlgorithmParameterGenerator.getInstance("DSA",
+ "SUN");
+ } catch (NoSuchAlgorithmException e) {
+ // this should never happen, because we provide it
+ throw new RuntimeException(e.getMessage());
+ } catch (NoSuchProviderException e) {
+ // this should never happen, because we provide it
+ throw new RuntimeException(e.getMessage());
+ }
+
+ dsaParamGen.init(modlen, random);
+
+ DSAParameterSpec dsaParamSpec;
+ try {
+ dsaParamSpec = (DSAParameterSpec)
+ dsaParamGen.generateParameters().getParameterSpec
+ (DSAParameterSpec.class);
+ } catch (InvalidParameterSpecException e) {
+ // this should never happen
+ throw new RuntimeException(e.getMessage());
+ }
+ presetP = dsaParamSpec.getP();
+ presetQ = dsaParamSpec.getQ();
+ presetG = dsaParamSpec.getG();
+ }
+
+ return generateKeyPair(presetP, presetQ, presetG, random);
+ }
+
+ public KeyPair generateKeyPair(BigInteger p, BigInteger q, BigInteger g,
+ SecureRandom random) {
+
+ BigInteger x = generateX(random, q);
+ BigInteger y = generateY(x, p, g);
+
+ try {
+ DSAPublicKey pub = new DSAPublicKey(y, p, q, g);
+ DSAPrivateKey priv = new DSAPrivateKey(x, p, q, g);
+
+ KeyPair pair = new KeyPair(pub, priv);
+ return pair;
+
+ } catch (InvalidKeyException e) {
+ throw new ProviderException(e.getMessage());
+ }
+ }
+
+ /* Test vectors from the DSA specs. */
+
+ private static int[] testXSeed = { 0xbd029bbe, 0x7f51960b, 0xcf9edb2b,
+ 0x61f06f0f, 0xeb5a38b6 };
+
+ private int[] x_t = { 0x67452301,0xefcdab89,0x98badcfe,
+ 0x10325476,0xc3d2e1f0 };
+
+ /**
+ * Generate the private key component of the key pair using the
+ * provided source of random bits. This method uses the random but
+ * source passed to generate a seed and then calls the seed-based
+ * generateX method.
+ */
+ private BigInteger generateX(SecureRandom random, BigInteger q) {
+ BigInteger x = null;
+ while (true) {
+ int[] seed = new int[5];
+ for (int i = 0; i < 5; i++) {
+ seed[i] = random.nextInt();
+ }
+ x = generateX(seed, q);
+ if (x.signum() > 0 && (x.compareTo(q) < 0)) {
+ break;
+ }
+ }
+ return x;
+ }
+
+ /**
+ * Given a seed, generate the private key component of the key
+ * pair. In the terminology used in the DSA specification
+ * (FIPS-186) seed is the XSEED quantity.
+ *
+ * @param seed the seed to use to generate the private key.
+ */
+ BigInteger generateX(int[] seed, BigInteger q) {
+
+ /* Test vector
+ int[] tseed = { 0xbd029bbe, 0x7f51960b, 0xcf9edb2b,
+ 0x61f06f0f, 0xeb5a38b6 };
+ seed = tseed;
+ */
+ // check out t in the spec.
+ int[] t = { 0x67452301, 0xEFCDAB89, 0x98BADCFE,
+ 0x10325476, 0xC3D2E1F0 };
+ //
+
+ int[] tmp = DSA.SHA_7(seed, t);
+ byte[] tmpBytes = new byte[tmp.length * 4];
+ for (int i = 0; i < tmp.length; i++) {
+ int k = tmp[i];
+ for (int j = 0; j < 4; j++) {
+ tmpBytes[(i * 4) + j] = (byte) (k >>> (24 - (j * 8)));
+ }
+ }
+ BigInteger x = new BigInteger(1, tmpBytes).mod(q);
+ return x;
+ }
+
+ /**
+ * Generate the public key component y of the key pair.
+ *
+ * @param x the private key component.
+ *
+ * @param p the base parameter.
+ */
+ BigInteger generateY(BigInteger x, BigInteger p, BigInteger g) {
+ BigInteger y = g.modPow(x, p);
+ return y;
+ }
+
+ /**
+ * Set the parameters.
+ */
+ private void setParams(DSAParams params) {
+ presetP = params.getP();
+ presetQ = params.getQ();
+ presetG = params.getG();
+ }
+
+ /**
+ * Set the parameters.
+ */
+ private void setParams(DSAParameterSpec params) {
+ presetP = params.getP();
+ presetQ = params.getQ();
+ presetG = params.getG();
+ }
+}
diff --git a/pki/base/util/src/netscape/security/provider/DSAParameterGenerator.java b/pki/base/util/src/netscape/security/provider/DSAParameterGenerator.java
new file mode 100755
index 000000000..949e9ea62
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/DSAParameterGenerator.java
@@ -0,0 +1,300 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.math.BigInteger;
+import java.security.AlgorithmParameterGeneratorSpi;
+import java.security.AlgorithmParameters;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.InvalidParameterException;
+import java.security.SecureRandom;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
+import java.security.spec.DSAParameterSpec;
+
+/*
+ * This class generates parameters for the DSA algorithm. It uses a default
+ * prime modulus size of 1024 bits, which can be overwritten during
+ * initialization.
+ *
+ * @author Jan Luehe
+ *
+ * @version 1.4, 97/12/10
+ *
+ * @see java.security.AlgorithmParameters
+ * @see java.security.spec.AlgorithmParameterSpec
+ * @see DSAParameters
+ *
+ * @since JDK1.2
+ */
+
+public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
+
+ // the modulus length
+ private int modLen = 1024; // default
+
+ // the source of randomness
+ private SecureRandom random;
+
+ // useful constants
+ private static final BigInteger ZERO = BigInteger.valueOf(0);
+ private static final BigInteger ONE = BigInteger.valueOf(1);
+ private static final BigInteger TWO = BigInteger.valueOf(2);
+
+ // Make a SHA-1 hash function
+ private SHA sha;
+
+ public DSAParameterGenerator() {
+ this.sha = new SHA();
+ }
+
+ /**
+ * Initializes this parameter generator for a certain strength
+ * and source of randomness.
+ *
+ * @param strength the strength (size of prime) in bits
+ * @param random the source of randomness
+ */
+ protected void engineInit(int strength, SecureRandom random) {
+ /*
+ * Bruce Schneier, "Applied Cryptography", 2nd Edition,
+ * Description of DSA:
+ * [...] The algorithm uses the following parameter:
+ * p=a prime number L bits long, when L ranges from 512 to 1024 and is
+ * a multiple of 64. [...]
+ */
+ if ((strength < 512) || (strength > 1024) || (strength % 64 != 0)) {
+ throw new InvalidParameterException
+ ("Prime size must range from 512 to 1024 "
+ + "and be a multiple of 64");
+ }
+ this.modLen = strength;
+ this.random = random;
+ }
+
+ /**
+ * Initializes this parameter generator with a set of
+ * algorithm-specific parameter generation values.
+ *
+ * @param params the set of algorithm-specific parameter generation values
+ * @param random the source of randomness
+ *
+ * @exception InvalidAlgorithmParameterException if the given parameter
+ * generation values are inappropriate for this parameter generator
+ */
+ protected void engineInit(AlgorithmParameterSpec genParamSpec,
+ SecureRandom random)
+ throws InvalidAlgorithmParameterException {
+ throw new InvalidAlgorithmParameterException("Invalid parameter");
+ }
+
+ /**
+ * Generates the parameters.
+ *
+ * @return the new AlgorithmParameters object
+ */
+ protected AlgorithmParameters engineGenerateParameters() {
+ AlgorithmParameters algParams = null;
+ try {
+ if (this.random == null) {
+ this.random = new SecureRandom();
+ }
+
+ BigInteger[] pAndQ = generatePandQ(this.random, this.modLen);
+ BigInteger paramP = pAndQ[0];
+ BigInteger paramQ = pAndQ[1];
+ BigInteger paramG = generateG(paramP, paramQ);
+
+ DSAParameterSpec dsaParamSpec = new DSAParameterSpec(paramP,
+ paramQ,
+ paramG);
+ algParams = AlgorithmParameters.getInstance("DSA", "SUN");
+ algParams.init(dsaParamSpec);
+ } catch (InvalidParameterSpecException e) {
+ // this should never happen
+ throw new RuntimeException(e.getMessage());
+ } catch (NoSuchAlgorithmException e) {
+ // this should never happen, because we provide it
+ throw new RuntimeException(e.getMessage());
+ } catch (NoSuchProviderException e) {
+ // this should never happen, because we provide it
+ throw new RuntimeException(e.getMessage());
+ }
+
+ return algParams;
+ }
+
+ /*
+ * Generates the prime and subprime parameters for DSA,
+ * using the provided source of randomness.
+ * This method will generate new seeds until a suitable
+ * seed has been found.
+ *
+ * @param random the source of randomness to generate the
+ * seed
+ * @param L the size of <code>p</code>, in bits.
+ *
+ * @return an array of BigInteger, with <code>p</code> at index 0 and
+ * <code>q</code> at index 1.
+ */
+ BigInteger[] generatePandQ(SecureRandom random, int L) {
+ BigInteger[] result = null;
+ byte[] seed = new byte[20];
+
+ while(result == null) {
+ for (int i = 0; i < 20; i++) {
+ seed[i] = (byte)random.nextInt();
+ }
+ result = generatePandQ(seed, L);
+ }
+ return result;
+ }
+
+ /*
+ * Generates the prime and subprime parameters for DSA.
+ *
+ * <p>The seed parameter corresponds to the <code>SEED</code> parameter
+ * referenced in the FIPS specification of the DSA algorithm,
+ * and L is the size of <code>p</code>, in bits.
+ *
+ * @param seed the seed to generate the parameters
+ * @param L the size of <code>p</code>, in bits.
+ *
+ * @return an array of BigInteger, with <code>p</code> at index 0,
+ * <code>q</code> at index 1, the seed at index 2, and the counter value
+ * at index 3, or null if the seed does not yield suitable numbers.
+ */
+ BigInteger[] generatePandQ(byte[] seed, int L) {
+
+ /* Useful variables */
+ int g = seed.length * 8;
+ int n = (L - 1) / 160;
+ int b = (L - 1) % 160;
+
+ BigInteger SEED = new BigInteger(1, seed);
+ BigInteger TWOG = TWO.pow(2 * g);
+
+ /* Step 2 (Step 1 is getting seed). */
+ byte[] U1 = SHA(seed);
+ byte[] U2 = SHA(toByteArray((SEED.add(ONE)).mod(TWOG)));
+
+ xor(U1, U2);
+ byte[] U = U1;
+
+ /* Step 3: For q by setting the msb and lsb to 1 */
+ U[0] |= 0x80;
+ U[19] |= 1;
+ BigInteger q = new BigInteger(1, U);
+
+ /* Step 5 */
+ if (!q.isProbablePrime(40)) {
+ return null;
+
+ } else {
+ BigInteger V[] = new BigInteger[n + 1];
+ BigInteger offset = TWO;
+
+ /* Step 6 */
+ for (int counter = 0; counter < 4096; counter++) {
+
+ /* Step 7 */
+ for (int k = 0; k <= n; k++) {
+ BigInteger K = BigInteger.valueOf(k);
+ BigInteger tmp = (SEED.add(offset).add(K)).mod(TWOG);
+ V[k] = new BigInteger(1, SHA(toByteArray(tmp)));
+ }
+
+ /* Step 8 */
+ BigInteger W = V[0];
+ for (int i = 1; i < n; i++) {
+ W = W.add(V[i].multiply(TWO.pow(i * 160)));
+ }
+ W = W.add((V[n].mod(TWO.pow(b))).multiply(TWO.pow(n * 160)));
+
+ BigInteger TWOLm1 = TWO.pow(L - 1);
+ BigInteger X = W.add(TWOLm1);
+
+ /* Step 9 */
+ BigInteger c = X.mod(q.multiply(TWO));
+ BigInteger p = X.subtract(c.subtract(ONE));
+
+ /* Step 10 - 13 */
+ if (p.compareTo(TWOLm1) > -1 && p.isProbablePrime(15)) {
+ BigInteger[] result = {p, q, SEED,
+ BigInteger.valueOf(counter)};
+ return result;
+ }
+ offset = offset.add(BigInteger.valueOf(n)).add(ONE);
+ }
+ return null;
+ }
+ }
+
+ /*
+ * Generates the <code>g</code> parameter for DSA.
+ *
+ * @param p the prime, <code>p</code>.
+ * @param q the subprime, <code>q</code>.
+ *
+ * @param the <code>g</code>
+ */
+ BigInteger generateG(BigInteger p, BigInteger q) {
+ BigInteger h = ONE;
+ BigInteger pMinusOneOverQ = (p.subtract(ONE)).divide(q);
+ BigInteger g = ONE;
+ while (g.compareTo(TWO) < 0) {
+ g = h.modPow(pMinusOneOverQ, p);
+ h = h.add(ONE);
+ }
+ return g;
+ }
+
+ /*
+ * Returns the SHA-1 digest of some data
+ */
+ private byte[] SHA(byte[] array) {
+ sha.engineReset();
+ sha.engineUpdate(array, 0, array.length);
+ return sha.engineDigest();
+ }
+
+ /*
+ * Converts the result of a BigInteger.toByteArray call to an exact
+ * signed magnitude representation for any positive number.
+ */
+ private byte[] toByteArray(BigInteger bigInt) {
+ byte[] result = bigInt.toByteArray();
+ if (result[0] == 0) {
+ byte[] tmp = new byte[result.length - 1];
+ System.arraycopy(result, 1, tmp, 0, tmp.length);
+ result = tmp;
+ }
+ return result;
+ }
+
+ /*
+ * XORs U2 into U1
+ */
+ private void xor(byte[] U1, byte[] U2) {
+ for (int i = 0; i < U1.length; i++) {
+ U1[i] ^= U2[i];
+ }
+ }
+}
diff --git a/pki/base/util/src/netscape/security/provider/DSAParameters.java b/pki/base/util/src/netscape/security/provider/DSAParameters.java
new file mode 100755
index 000000000..4edf88490
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/DSAParameters.java
@@ -0,0 +1,133 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.util.*;
+import java.io.*;
+import java.math.BigInteger;
+import java.security.AlgorithmParametersSpi;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.DSAParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
+
+import netscape.security.util.DerValue;
+import netscape.security.util.DerOutputStream;
+import netscape.security.util.BigInt;
+
+/**
+ * This class implements the parameter set used by the
+ * Digital Signature Algorithm as specified in the FIPS 186
+ * standard.
+ *
+ * @author Jan Luehe
+ *
+ * @version 1.8, 97/12/10
+ *
+ * @since JDK1.2
+ */
+
+public class DSAParameters extends AlgorithmParametersSpi {
+
+ // the prime (p)
+ protected BigInteger p;
+
+ // the sub-prime (q)
+ protected BigInteger q;
+
+ // the base (g)
+ protected BigInteger g;
+
+ protected void engineInit(AlgorithmParameterSpec paramSpec)
+ throws InvalidParameterSpecException {
+ if (!(paramSpec instanceof DSAParameterSpec)) {
+ throw new InvalidParameterSpecException
+ ("Inappropriate parameter specification");
+ }
+ this.p = ((DSAParameterSpec)paramSpec).getP();
+ this.q = ((DSAParameterSpec)paramSpec).getQ();
+ this.g = ((DSAParameterSpec)paramSpec).getG();
+ }
+
+ protected void engineInit(byte[] params) throws IOException {
+ DerValue encodedParams = new DerValue(params);
+
+ if (encodedParams.tag != DerValue.tag_Sequence) {
+ throw new IOException("DSA params parsing error");
+ }
+
+ encodedParams.data.reset();
+
+ this.p = encodedParams.data.getInteger().toBigInteger();
+ this.q = encodedParams.data.getInteger().toBigInteger();
+ this.g = encodedParams.data.getInteger().toBigInteger();
+
+ if (encodedParams.data.available() != 0) {
+ throw new IOException("encoded params have " +
+ encodedParams.data.available() +
+ " extra bytes");
+ }
+ }
+
+ protected void engineInit(byte[] params, String decodingMethod)
+ throws IOException {
+ engineInit(params);
+ }
+
+ protected AlgorithmParameterSpec engineGetParameterSpec(Class paramSpec)
+ throws InvalidParameterSpecException {
+ try {
+ Class dsaParamSpec = Class.forName
+ ("java.security.spec.DSAParameterSpec");
+ if (dsaParamSpec.isAssignableFrom(paramSpec)) {
+ return new DSAParameterSpec(this.p, this.q, this.g);
+ } else {
+ throw new InvalidParameterSpecException
+ ("Inappropriate parameter Specification");
+ }
+ } catch (ClassNotFoundException e) {
+ throw new InvalidParameterSpecException
+ ("Unsupported parameter specification: " + e.getMessage());
+ }
+ }
+
+ protected byte[] engineGetEncoded() throws IOException {
+ DerOutputStream out = new DerOutputStream();
+ DerOutputStream bytes = new DerOutputStream();
+
+ bytes.putInteger(new BigInt(p.toByteArray()));
+ bytes.putInteger(new BigInt(q.toByteArray()));
+ bytes.putInteger(new BigInt(g.toByteArray()));
+ out.write(DerValue.tag_Sequence, bytes);
+ return out.toByteArray();
+ }
+
+ protected byte[] engineGetEncoded(String encodingMethod)
+ throws IOException {
+ return engineGetEncoded();
+ }
+
+ /*
+ * Returns a formatted string describing the parameters.
+ */
+ protected String engineToString() {
+ return "\n\tp: " + new BigInt(p).toString()
+ + "\n\tq: " + new BigInt(q).toString()
+ + "\n\tg: " + new BigInt(g).toString()
+ + "\n";
+ }
+}
diff --git a/pki/base/util/src/netscape/security/provider/DSAPrivateKey.java b/pki/base/util/src/netscape/security/provider/DSAPrivateKey.java
new file mode 100644
index 000000000..ab60554e6
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/DSAPrivateKey.java
@@ -0,0 +1,150 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.util.*;
+import java.io.*;
+import java.math.BigInteger;
+import java.security.InvalidKeyException;
+import java.security.ProviderException;
+import java.security.AlgorithmParameters;
+import java.security.spec.DSAParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
+import java.security.interfaces.DSAParams;
+
+import netscape.security.x509.AlgIdDSA;
+import netscape.security.pkcs.PKCS8Key;
+import netscape.security.util.BigInt;
+import netscape.security.util.DerValue;
+import netscape.security.util.DerInputStream;
+import netscape.security.util.DerOutputStream;
+
+/**
+ * A PKCS#8 private key for the Digital Signature Algorithm.
+ *
+ * @author Benjamin Renaud
+ *
+ * @version 1.47, 97/12/10
+ *
+ * @see DSAPublicKey
+ * @see AlgIdDSA
+ * @see DSA
+ */
+
+public final class DSAPrivateKey extends PKCS8Key
+implements java.security.interfaces.DSAPrivateKey, Serializable {
+
+ /** use serialVersionUID from JDK 1.1. for interoperability */
+ private static final long serialVersionUID = -3244453684193605938L;
+
+ /* the private key */
+ private BigInteger x;
+
+ /*
+ * Keep this constructor for backwards compatibility with JDK1.1.
+ */
+ public DSAPrivateKey() {
+ }
+
+ /**
+ * Make a DSA private key out of a private key and three parameters.
+ */
+ public DSAPrivateKey(BigInteger x, BigInteger p,
+ BigInteger q, BigInteger g)
+ throws InvalidKeyException {
+ this.x = x;
+ algid = new AlgIdDSA(p, q, g);
+
+ try {
+ key = new DerValue(DerValue.tag_Integer,
+ x.toByteArray()).toByteArray();
+ encode();
+ } catch (IOException e) {
+ throw new InvalidKeyException("could not DER encode x: " +
+ e.getMessage());
+ }
+ }
+
+ /**
+ * Make a DSA private key from its DER encoding (PKCS #8).
+ */
+ public DSAPrivateKey(byte[] encoded) throws InvalidKeyException {
+ clearOldKey();
+ decode(encoded);
+ }
+
+ /**
+ * Returns the DSA parameters associated with this key, or null if the
+ * parameters could not be parsed.
+ */
+ public DSAParams getParams() {
+ try {
+ if (algid instanceof DSAParams) {
+ return (DSAParams)algid;
+ } else {
+ DSAParameterSpec paramSpec;
+ AlgorithmParameters algParams = algid.getParameters();
+ if (algParams == null) {
+ return null;
+ }
+ paramSpec = (DSAParameterSpec)algParams.getParameterSpec
+ (DSAParameterSpec.class);
+ return (DSAParams)paramSpec;
+ }
+ } catch (InvalidParameterSpecException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Get the raw private key, x, without the parameters.
+ *
+ */
+ public BigInteger getX() {
+ return x;
+ }
+
+ private void clearOldKey() {
+ int i;
+ if (this.encodedKey != null) {
+ for (i = 0; i < this.encodedKey.length; i++) {
+ this.encodedKey[i] = (byte)0x00;
+ }
+ }
+ if (this.key != null) {
+ for (i = 0; i < this.key.length; i++) {
+ this.key[i] = (byte)0x00;
+ }
+ }
+ }
+
+ public String toString() {
+ return "Sun DSA Private Key \nparameters:" + algid + "\nx: " +
+ x.toString(16) + "\n";
+ }
+
+ protected void parseKeyBits() throws InvalidKeyException {
+ DerInputStream in = new DerInputStream(key);
+
+ try {
+ x = in.getInteger().toBigInteger();
+ } catch (IOException e) {
+ throw new InvalidKeyException(e.getMessage());
+ }
+ }
+}
diff --git a/pki/base/util/src/netscape/security/provider/DSAPublicKey.java b/pki/base/util/src/netscape/security/provider/DSAPublicKey.java
new file mode 100644
index 000000000..9ebdc0dc0
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/DSAPublicKey.java
@@ -0,0 +1,135 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.util.*;
+import java.io.*;
+import java.math.BigInteger;
+import java.security.InvalidKeyException;
+import java.security.ProviderException;
+import java.security.AlgorithmParameters;
+import java.security.spec.DSAParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
+import java.security.interfaces.DSAParams;
+
+import netscape.security.x509.X509Key;
+import netscape.security.x509.AlgIdDSA;
+import netscape.security.util.BigInt;
+import netscape.security.util.DerValue;
+import netscape.security.util.DerInputStream;
+import netscape.security.util.DerOutputStream;
+
+/**
+ * An X.509 public key for the Digital Signature Algorithm.
+ *
+ * @author Benjamin Renaud
+ *
+ * @version 1.52, 97/12/10
+ *
+ * @see DSAPrivateKey
+ * @see AlgIdDSA
+ * @see DSA
+ */
+
+public final class DSAPublicKey extends X509Key
+implements java.security.interfaces.DSAPublicKey, Serializable {
+
+ /** use serialVersionUID from JDK 1.1. for interoperability */
+ private static final long serialVersionUID = -2994193307391104133L;
+
+ /* the public key */
+ private BigInteger y;
+
+ /*
+ * Keep this constructor for backwards compatibility with JDK1.1.
+ */
+ public DSAPublicKey() {
+ }
+
+ /**
+ * Make a DSA public key out of a public key and three parameters.
+ */
+ public DSAPublicKey(BigInteger y, BigInteger p, BigInteger q,
+ BigInteger g)
+ throws InvalidKeyException {
+ this.y = y;
+ algid = new AlgIdDSA(p, q, g);
+
+ try {
+ key = new DerValue(DerValue.tag_Integer,
+ y.toByteArray()).toByteArray();
+ encode();
+ } catch (IOException e) {
+ throw new InvalidKeyException("could not DER encode y: " +
+ e.getMessage());
+ }
+ }
+
+ /**
+ * Make a DSA public key from its DER encoding (X.509).
+ */
+ public DSAPublicKey(byte[] encoded) throws InvalidKeyException {
+ decode(encoded);
+ }
+
+ /**
+ * Returns the DSA parameters associated with this key, or null if the
+ * parameters could not be parsed.
+ */
+ public DSAParams getParams() {
+ try {
+ if (algid instanceof DSAParams) {
+ return (DSAParams)algid;
+ } else {
+ DSAParameterSpec paramSpec;
+ AlgorithmParameters algParams = algid.getParameters();
+ if (algParams == null) {
+ return null;
+ }
+ paramSpec = (DSAParameterSpec)algParams.getParameterSpec
+ (DSAParameterSpec.class);
+ return (DSAParams)paramSpec;
+ }
+ } catch (InvalidParameterSpecException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Get the raw public value, y, without the parameters.
+ *
+ */
+ public BigInteger getY() {
+ return y;
+ }
+
+ public String toString() {
+ return "Sun DSA Public Key\n Parameters:" + algid
+ + "\n y:\n" + (new BigInt(y)).toString() + "\n";
+ }
+
+ protected void parseKeyBits() throws InvalidKeyException {
+ try {
+ DerInputStream in = new DerInputStream(key);
+ y = in.getInteger().toBigInteger();
+ } catch (IOException e) {
+ throw new InvalidKeyException("Invalid key: y value\n" +
+ e.getMessage());
+ }
+ }
+}
diff --git a/pki/base/util/src/netscape/security/provider/MD5.java b/pki/base/util/src/netscape/security/provider/MD5.java
new file mode 100644
index 000000000..97bbac204
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/MD5.java
@@ -0,0 +1,390 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.util.*;
+import java.lang.*;
+import java.security.*;
+
+/**
+ * The MD5 class is used to compute an MD5 message digest over a given
+ * buffer of bytes. It is an implementation of the RSA Data Security Inc
+ * MD5 algorithim as described in internet RFC 1321.
+ *
+ * @version 1.24 97/12/10
+ * @author Chuck McManis
+ * @author Benjamin Renaud
+ */
+
+public final class MD5 extends MessageDigestSpi implements Cloneable {
+
+ /** contains the computed message digest */
+ private byte[] digestBits;
+
+ private String algorithm;
+
+ private int state[];
+ private long count; // bit count AND buffer[] index aid
+ private byte buffer[];
+ private int transformBuffer[];
+
+ private static final int S11 = 7;
+ private static final int S12 = 12;
+ private static final int S13 = 17;
+ private static final int S14 = 22;
+ private static final int S21 = 5;
+ private static final int S22 = 9;
+ private static final int S23 = 14;
+ private static final int S24 = 20;
+ private static final int S31 = 4;
+ private static final int S32 = 11;
+ private static final int S33 = 16;
+ private static final int S34 = 23;
+ private static final int S41 = 6;
+ private static final int S42 = 10;
+ private static final int S43 = 15;
+ private static final int S44 = 21;
+
+ private static final int MD5_LENGTH = 16;
+
+ /**
+ * Standard constructor, creates a new MD5 instance, allocates its
+ * buffers from the heap.
+ */
+ public MD5() {
+ init();
+ }
+
+ private MD5(MD5 md5) {
+ this();
+ this.state = (int[])md5.state.clone();
+ this.transformBuffer = (int[])md5.transformBuffer.clone();
+ this.buffer = (byte[])md5.buffer.clone();
+ this.digestBits = (byte[])md5.digestBits.clone();
+ this.count = md5.count;
+ }
+
+ /* **********************************************************
+ * The MD5 Functions. These are copied verbatim from
+ * the RFC to insure accuracy. The results of this
+ * implementation were checked against the RSADSI version.
+ * **********************************************************
+ */
+
+ private int F(int x, int y, int z) {
+ return ((x & y) | ((~x) & z));
+ }
+
+ private int G(int x, int y, int z) {
+ return ((x & z) | (y & (~z)));
+ }
+
+ private int H(int x, int y, int z) {
+ return ((x ^ y) ^ z);
+ }
+
+ private int I(int x, int y, int z) {
+ return (y ^ (x | (~z)));
+ }
+
+ private int rotateLeft(int a, int n) {
+ return ((a << n) | (a >>> (32 - n)));
+ }
+
+ private int FF(int a, int b, int c, int d, int x, int s, int ac) {
+ a += F(b, c, d) + x + ac;
+ a = rotateLeft(a, s);
+ a += b;
+ return a;
+ }
+
+ private int GG(int a, int b, int c, int d, int x, int s, int ac) {
+ a += G(b, c, d) + x + ac;
+ a = rotateLeft(a, s);
+ a += b;
+ return a;
+ }
+
+ private int HH(int a, int b, int c, int d, int x, int s, int ac) {
+ a += H(b, c, d) + x + ac;
+ a = rotateLeft(a, s);
+ a += b;
+ return a;
+ }
+
+ private int II(int a, int b, int c, int d, int x, int s, int ac) {
+ a += I(b, c, d) + x + ac;
+ a = rotateLeft(a, s);
+ a += b;
+ return a;
+ }
+
+ /**
+ * This is where the functions come together as the generic MD5
+ * transformation operation, it is called by update() which is
+ * synchronized (to protect transformBuffer). It consumes sixteen
+ * bytes from the buffer, beginning at the specified offset.
+ */
+ void transform(byte buf[], int offset) {
+ int a, b, c, d;
+ int x[] = transformBuffer;
+
+ a = state[0];
+ b = state[1];
+ c = state[2];
+ d = state[3];
+
+ for (int i = 0; i < 16; i++) {
+ x[i] = (int)buf[i*4+offset] & 0xff;
+ for (int j = 1; j < 4; j++) {
+ x[i] += ((int)buf[i*4+j+offset] & 0xff) << (j * 8);
+ }
+ }
+
+ /* Round 1 */
+ a = FF ( a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
+ d = FF ( d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
+ c = FF ( c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
+ b = FF ( b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
+ a = FF ( a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
+ d = FF ( d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
+ c = FF ( c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
+ b = FF ( b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
+ a = FF ( a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
+ d = FF ( d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
+ c = FF ( c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
+ b = FF ( b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
+ a = FF ( a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
+ d = FF ( d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
+ c = FF ( c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
+ b = FF ( b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
+
+ /* Round 2 */
+ a = GG ( a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
+ d = GG ( d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
+ c = GG ( c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
+ b = GG ( b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
+ a = GG ( a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
+ d = GG ( d, a, b, c, x[10], S22, 0x2441453); /* 22 */
+ c = GG ( c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
+ b = GG ( b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
+ a = GG ( a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
+ d = GG ( d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
+ c = GG ( c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
+ b = GG ( b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
+ a = GG ( a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
+ d = GG ( d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
+ c = GG ( c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
+ b = GG ( b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
+
+ /* Round 3 */
+ a = HH ( a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
+ d = HH ( d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
+ c = HH ( c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
+ b = HH ( b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
+ a = HH ( a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
+ d = HH ( d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
+ c = HH ( c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
+ b = HH ( b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
+ a = HH ( a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
+ d = HH ( d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
+ c = HH ( c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
+ b = HH ( b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
+ a = HH ( a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
+ d = HH ( d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
+ c = HH ( c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
+ b = HH ( b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
+
+ /* Round 4 */
+ a = II ( a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
+ d = II ( d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
+ c = II ( c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
+ b = II ( b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
+ a = II ( a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
+ d = II ( d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
+ c = II ( c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
+ b = II ( b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
+ a = II ( a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
+ d = II ( d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
+ c = II ( c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
+ b = II ( b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
+ a = II ( a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
+ d = II ( d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
+ c = II ( c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
+ b = II ( b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
+
+ state[0] += a;
+ state[1] += b;
+ state[2] += c;
+ state[3] += d;
+ }
+
+ /**
+ * Initialize the MD5 state information and reset the bit count
+ * to 0. Given this implementation you are constrained to counting
+ * 2^64 bits.
+ */
+ public void init() {
+ state = new int[4];
+ transformBuffer = new int[16];
+ buffer = new byte[64];
+ digestBits = new byte[16];
+ count = 0;
+ // Load magic initialization constants.
+ state[0] = 0x67452301;
+ state[1] = 0xefcdab89;
+ state[2] = 0x98badcfe;
+ state[3] = 0x10325476;
+ for (int i = 0; i < digestBits.length; i++)
+ digestBits[i] = 0;
+ }
+
+ protected void engineReset() {
+ init();
+ }
+
+ /**
+ * Return the digest length in bytes
+ */
+ protected int engineGetDigestLength() {
+ return (MD5_LENGTH);
+ }
+
+ /**
+ * Update adds the passed byte to the digested data.
+ */
+ protected synchronized void engineUpdate(byte b) {
+ int index;
+
+ index = (int) ((count >>> 3) & 0x3f);
+ count += 8;
+ buffer[index] = b;
+ if (index >= 63) {
+ transform(buffer, 0);
+ }
+ }
+
+ /**
+ * Update adds the selected part of an array of bytes to the digest.
+ * This version is more efficient than the byte-at-a-time version;
+ * it avoids data copies and reduces per-byte call overhead.
+ */
+ protected synchronized void engineUpdate(byte input[], int offset,
+ int len) {
+ int i;
+
+ for (i = offset; len > 0; ) {
+ int index = (int) ((count >>> 3) & 0x3f);
+
+ if (index == 0 && len > 64) {
+ count += (64 * 8);
+ transform (input, i);
+ len -= 64;
+ i += 64;
+ } else {
+ count += 8;
+ buffer[index] = input [i];
+ if (index >= 63)
+ transform (buffer, 0);
+ i++;
+ len--;
+ }
+ }
+ }
+
+ /**
+ * Perform the final computations, any buffered bytes are added
+ * to the digest, the count is added to the digest, and the resulting
+ * digest is stored. After calling final you will need to call
+ * init() again to do another digest.
+ */
+ private void finish() {
+ byte bits[] = new byte[8];
+ byte padding[];
+ int i, index, padLen;
+
+ for (i = 0; i < 8; i++) {
+ bits[i] = (byte)((count >>> (i * 8)) & 0xff);
+ }
+
+ index = (int)(count >> 3) & 0x3f;
+ padLen = (index < 56) ? (56 - index) : (120 - index);
+ padding = new byte[padLen];
+ padding[0] = (byte) 0x80;
+ engineUpdate(padding, 0, padding.length);
+ engineUpdate(bits, 0, bits.length);
+
+ for (i = 0; i < 4; i++) {
+ for (int j = 0; j < 4; j++) {
+ digestBits[i*4+j] = (byte)((state[i] >>> (j * 8)) & 0xff);
+ }
+ }
+ }
+
+ /**
+ */
+ protected byte[] engineDigest() {
+ finish();
+
+ byte[] result = new byte[MD5_LENGTH];
+ System.arraycopy(digestBits, 0, result, 0, MD5_LENGTH);
+
+ init();
+
+ return result;
+ }
+
+ /**
+ */
+ protected int engineDigest(byte[] buf, int offset, int len)
+ throws DigestException {
+ finish();
+
+ if (len < MD5_LENGTH)
+ throw new DigestException("partial digests not returned");
+ if (buf.length - offset < MD5_LENGTH)
+ throw new DigestException("insufficient space in the output " +
+ "buffer to store the digest");
+
+ System.arraycopy(digestBits, 0, buf, offset, MD5_LENGTH);
+
+ init();
+
+ return MD5_LENGTH;
+ }
+
+ /*
+ * Clones this object.
+ */
+ public Object clone() {
+ MD5 that = null;
+ try {
+ that = (MD5)super.clone();
+ that.state = (int[])this.state.clone();
+ that.transformBuffer = (int[])this.transformBuffer.clone();
+ that.buffer = (byte[])this.buffer.clone();
+ that.digestBits = (byte[])this.digestBits.clone();
+ that.count = this.count;
+ return that;
+ } catch (CloneNotSupportedException e) {
+ }
+ return that;
+ }
+}
+
+
diff --git a/pki/base/util/src/netscape/security/provider/RSAPublicKey.java b/pki/base/util/src/netscape/security/provider/RSAPublicKey.java
new file mode 100644
index 000000000..83dbc7f3d
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/RSAPublicKey.java
@@ -0,0 +1,148 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.util.*;
+import java.io.*;
+import java.security.InvalidKeyException;
+import java.security.ProviderException;
+import netscape.security.x509.AlgorithmId;
+import netscape.security.util.BigInt;
+
+import netscape.security.x509.X509Key;
+import netscape.security.util.ObjectIdentifier;
+import netscape.security.util.DerValue;
+import netscape.security.util.DerInputStream;
+import netscape.security.util.DerOutputStream;
+
+/**
+ * An X.509 public key for the RSA Algorithm.
+ *
+ * @author galperin
+ *
+ * @version $Revision$, $Date$
+ *
+ */
+
+public final class RSAPublicKey extends X509Key implements Serializable {
+
+ /* XXX This currently understands only PKCS#1 RSA Encryption OID
+ and parameter format
+ Later we may consider adding X509v3 OID for RSA keys. Besides
+ different OID it also has a parameter equal to modulus size
+ in bits (redundant!)
+ */
+
+ private static final ObjectIdentifier ALGORITHM_OID =
+ AlgorithmId.RSAEncryption_oid;
+
+ private BigInt modulus;
+ private BigInt publicExponent;
+
+ /*
+ * Keep this constructor for backwards compatibility with JDK1.1.
+ */
+ public RSAPublicKey() {
+ }
+
+ /**
+ * Make a RSA public key out of a public exponent and modulus
+ */
+ public RSAPublicKey(BigInt modulus, BigInt publicExponent)
+ throws InvalidKeyException {
+ this.modulus = modulus;
+ this.publicExponent = publicExponent;
+ this.algid = new AlgorithmId(ALGORITHM_OID);
+
+ try {
+ DerOutputStream out = new DerOutputStream ();
+
+ out.putInteger (modulus);
+ out.putInteger (publicExponent);
+ key = (new DerValue(DerValue.tag_Sequence,
+ out.toByteArray())).toByteArray();
+ encode();
+ } catch (IOException ex) {
+ throw new InvalidKeyException("could not DER encode : " +
+ ex.getMessage());
+ }
+ }
+
+ /**
+ * Make a RSA public key from its DER encoding (X.509).
+ */
+ public RSAPublicKey(byte[] encoded) throws InvalidKeyException {
+ decode(encoded);
+ }
+
+ /**
+ * Get key size as number of bits in modulus
+ * (Always rounded up to a multiple of 8)
+ *
+ */
+ public int getKeySize() {
+ return this.modulus.byteLength() * 8;
+ }
+
+ /**
+ * Get the raw public exponent
+ *
+ */
+ public BigInt getPublicExponent() {
+ return this.publicExponent;
+ }
+
+ /**
+ * Get the raw modulus
+ *
+ */
+ public BigInt getModulus() {
+ return this.modulus;
+ }
+
+ public String toString() {
+ return "RSA Public Key\n Algorithm: " + algid
+ + "\n modulus:\n" + this.modulus.toString() + "\n"
+ + "\n publicExponent:\n" + this.publicExponent.toString()
+ + "\n";
+ }
+
+ protected void parseKeyBits() throws InvalidKeyException {
+ if (!this.algid.getOID().equals(ALGORITHM_OID) &&
+ !this.algid.getOID().equals(AlgorithmId.RSA_oid)) {
+ throw new InvalidKeyException("Key algorithm OID is not RSA");
+ }
+
+ try {
+ DerValue val = new DerValue (key);
+ if (val.tag != DerValue.tag_Sequence) {
+ throw new InvalidKeyException("Invalid RSA public key format:" +
+ " must be a SEQUENCE");
+ }
+
+ DerInputStream in = val.data;
+
+ this.modulus = in.getInteger();
+ this.publicExponent = in.getInteger();
+ } catch (IOException e) {
+ throw new InvalidKeyException("Invalid RSA public key: " +
+ e.getMessage());
+ }
+ }
+
+}
diff --git a/pki/base/util/src/netscape/security/provider/SHA.java b/pki/base/util/src/netscape/security/provider/SHA.java
new file mode 100644
index 000000000..09fdf2dfa
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/SHA.java
@@ -0,0 +1,362 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.security.*;
+
+/**
+ * This class implements the Secure Hash Algorithm (SHA) developed by
+ * the National Institute of Standards and Technology along with the
+ * National Security Agency. This is the updated version of SHA
+ * fip-180 as superseded by fip-180-1.
+ *
+ * <p>It implement JavaSecurity MessageDigest, and can be used by in
+ * the Java Security framework, as a pluggable implementation, as a
+ * filter for the digest stream classes.
+ *
+ * @version 1.30 97/12/10
+ * @author Roger Riggs
+ * @author Benjamin Renaud
+ */
+
+public class SHA extends MessageDigestSpi implements Cloneable {
+
+ /* This private hookm controlled by the appropriate constructor,
+ causes this class to implement the first version of SHA,
+ as defined in FIPS 180, as opposed to FIPS 180-1. This was
+ useful for DSA testing. */
+ private int version = 1;
+
+ private static final int SHA_LENGTH = 20;
+
+ // Buffer of int's and count of characters accumulated
+ // 64 bytes are included in each hash block so the low order
+ // bits of count are used to know how to pack the bytes into ints
+ // and to know when to compute the block and start the next one.
+ private int W[] = new int[80];
+ private long count = 0;
+ private final int countmax = 64;
+ private final int countmask = (countmax-1);
+
+ private int AA, BB, CC, DD, EE;
+
+ /**
+ * Creates a SHA object.with state (for cloning) */
+ private SHA(SHA sha) {
+ this();
+ this.version = sha.version;
+ System.arraycopy(sha.W, 0, this.W, 0, W.length);
+ this.count = sha.count;
+ this.AA = sha.AA;
+ this.BB = sha.BB;
+ this.CC = sha.CC;
+ this.DD = sha.DD;
+ this.EE = sha.EE;
+ }
+
+ SHA(int version) {
+ this();
+ this.version = version;
+ }
+
+ /**
+ * Creates a new SHA object.
+ */
+ public SHA() {
+ init();
+ }
+
+ /**
+ * Return the length of the digest in bytes
+ */
+ protected int engineGetDigestLength() {
+ return (SHA_LENGTH);
+ }
+
+ public void engineUpdate(byte b) {
+ engineUpdate((int)b);
+ }
+
+ /**
+ * Update a byte.
+ *
+ * @param b the byte
+ */
+ private void engineUpdate(int b) {
+ int word;
+ int offset;
+
+ /* compute word offset and bit offset within word the low bits
+ of count are inverted to make put the bytes in the write
+ order */
+ word = ((int)count & countmask) >>> 2;
+ offset = (~(int)count & 3) << 3;
+
+ W[word] = (W[word] & ~(0xff << offset)) | ((b & 0xff) << offset);
+
+ /* If this is the last byte of a block, compute the partial hash */
+ if (((int)count & countmask) == countmask) {
+ computeBlock();
+ }
+ count++;
+ }
+
+ /**
+ * Update a buffer.
+ *
+ * @param b the data to be updated.
+ * @param off the start offset in the data
+ * @param len the number of bytes to be updated.
+ */
+ public void engineUpdate(byte b[], int off, int len) {
+ int word;
+ int offset;
+
+ if ((off < 0) || (len < 0) || (off + len > b.length))
+ throw new ArrayIndexOutOfBoundsException();
+
+ // Use single writes until integer aligned
+ while ((len > 0) &&
+ ((int)count & 3) != 0) {
+ engineUpdate(b[off]);
+ off++;
+ len--;
+ }
+
+ /* Assemble groups of 4 bytes to be inserted in integer array */
+ for (;len >= 4; len -= 4, off += 4) {
+
+ word = ((int)count & countmask) >> 2;
+
+ W[word] = ((b[off] & 0xff) << 24) |
+ ((b[off+1] & 0xff) << 16) |
+ ((b[off+2] & 0xff) << 8) |
+ ((b[off+3] & 0xff) );
+
+ count += 4;
+ if (((int)count & countmask) == 0) {
+ computeBlock();
+ }
+ }
+
+ /* Use single writes for last few bytes */
+ for (; len > 0; len--, off++) {
+ engineUpdate(b[off]);
+ }
+ }
+
+ /**
+ * Resets the buffers and hash value to start a new hash.
+ */
+ public void init() {
+ AA = 0x67452301;
+ BB = 0xefcdab89;
+ CC = 0x98badcfe;
+ DD = 0x10325476;
+ EE = 0xc3d2e1f0;
+
+ for (int i = 0; i < 80; i++)
+ W[i] = 0;
+ count = 0;
+ }
+
+ /**
+ * Resets the buffers and hash value to start a new hash.
+ */
+ public void engineReset() {
+ init();
+ }
+
+ /**
+ * Computes the final hash and returns the final value as a
+ * byte[20] array. The object is reset to be ready for further
+ * use, as specified in the JavaSecurity MessageDigest
+ * specification. */
+ public byte[] engineDigest() {
+ byte hashvalue[] = new byte[SHA_LENGTH];
+
+ try {
+ int outLen = engineDigest(hashvalue, 0, hashvalue.length);
+ } catch (DigestException e) {
+ throw new InternalError("");
+ }
+ return hashvalue;
+ }
+
+ /**
+ * Computes the final hash and returns the final value as a
+ * byte[20] array. The object is reset to be ready for further
+ * use, as specified in the JavaSecurity MessageDigest
+ * specification. */
+ public int engineDigest(byte[] hashvalue, int offset, int len)
+ throws DigestException {
+
+ if (len < SHA_LENGTH)
+ throw new DigestException("partial digests not returned");
+ if (hashvalue.length - offset < SHA_LENGTH)
+ throw new DigestException("insufficient space in the output " +
+ "buffer to store the digest");
+
+ /* The number of bits before padding occurs */
+ long bits = count << 3;
+
+ engineUpdate(0x80);
+
+ /* Pad with zeros until length is a multiple of 448 (the last two
+ 32 ints are used a holder for bits (see above). */
+ while ((int)(count & countmask) != 56) {
+ engineUpdate(0);
+ }
+
+ W[14] = (int)(bits >>> 32);
+ W[15] = (int)(bits & 0xffffffff);
+
+ count += 8;
+ computeBlock();
+
+ // Copy out the result
+ hashvalue[offset + 0] = (byte)(AA >>> 24);
+ hashvalue[offset + 1] = (byte)(AA >>> 16);
+ hashvalue[offset + 2] = (byte)(AA >>> 8);
+ hashvalue[offset + 3] = (byte)(AA >>> 0);
+
+ hashvalue[offset + 4] = (byte)(BB >>> 24);
+ hashvalue[offset + 5] = (byte)(BB >>> 16);
+ hashvalue[offset + 6] = (byte)(BB >>> 8);
+ hashvalue[offset + 7] = (byte)(BB >>> 0);
+
+ hashvalue[offset + 8] = (byte)(CC >>> 24);
+ hashvalue[offset + 9] = (byte)(CC >>> 16);
+ hashvalue[offset + 10] = (byte)(CC >>> 8);
+ hashvalue[offset + 11] = (byte)(CC >>> 0);
+
+ hashvalue[offset + 12] = (byte)(DD >>> 24);
+ hashvalue[offset + 13] = (byte)(DD >>> 16);
+ hashvalue[offset + 14] = (byte)(DD >>> 8);
+ hashvalue[offset + 15] = (byte)(DD >>> 0);
+
+ hashvalue[offset + 16] = (byte)(EE >>> 24);
+ hashvalue[offset + 17] = (byte)(EE >>> 16);
+ hashvalue[offset + 18] = (byte)(EE >>> 8);
+ hashvalue[offset + 19] = (byte)(EE >>> 0);
+
+ engineReset(); // remove the evidence
+
+ return SHA_LENGTH;
+ }
+
+ // Constants for each round
+ private final int round1_kt = 0x5a827999;
+ private final int round2_kt = 0x6ed9eba1;
+ private final int round3_kt = 0x8f1bbcdc;
+ private final int round4_kt = 0xca62c1d6;
+
+ /**
+ * Compute a the hash for the current block.
+ *
+ * This is in the same vein as Peter Gutmann's algorithm listed in
+ * the back of Applied Cryptography, Compact implementation of
+ * "old" NIST Secure Hash Algorithm.
+ *
+ */
+ private void computeBlock() {
+ int temp, a, b, c, d, e;
+
+ // The first 16 ints have the byte stream, compute the rest of
+ // the buffer
+ for (int t = 16; t <= 79; t++) {
+ if (version == 0) {
+ W[t] = W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16];
+ } else {
+ temp = W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16];
+ W[t] = ((temp << 1) | (temp >>>(32 - 1)));
+ }
+ }
+
+ a = AA;
+ b = BB;
+ c = CC;
+ d = DD;
+ e = EE;
+
+ // Round 1
+ for (int i = 0; i < 20; i++) {
+ temp = ((a<<5) | (a>>>(32-5))) +
+ ((b&c)|((~b)&d))+ e + W[i] + round1_kt;
+ e = d;
+ d = c;
+ c = ((b<<30) | (b>>>(32-30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 2
+ for (int i = 20; i < 40; i++) {
+ temp = ((a<<5) | (a>>>(32-5))) +
+ (b ^ c ^ d) + e + W[i] + round2_kt;
+ e = d;
+ d = c;
+ c = ((b<<30) | (b>>>(32-30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 3
+ for (int i = 40; i < 60; i++) {
+ temp = ((a<<5) | (a>>>(32-5))) +
+ ((b&c)|(b&d)|(c&d)) + e + W[i] + round3_kt;
+ e = d;
+ d = c;
+ c = ((b<<30) | (b>>>(32-30)));
+ b = a;
+ a = temp;
+ }
+
+ // Round 4
+ for (int i = 60; i < 80; i++) {
+ temp = ((a<<5) | (a>>>(32-5))) +
+ (b ^ c ^ d) + e + W[i] + round4_kt;
+ e = d;
+ d = c;
+ c = ((b<<30) | (b>>>(32-30)));
+ b = a;
+ a = temp;
+ }
+ AA += a;
+ BB += b;
+ CC += c;
+ DD += d;
+ EE += e;
+ }
+
+ /*
+ * Clones this object.
+ */
+ public Object clone() {
+ SHA that = null;
+ try {
+ that = (SHA)super.clone();
+ that.W = new int[80];
+ System.arraycopy(this.W, 0, that.W, 0, W.length);
+ return that;
+ } catch (CloneNotSupportedException e) {
+ }
+ return that;
+ }
+}
+
diff --git a/pki/base/util/src/netscape/security/provider/Sun.java b/pki/base/util/src/netscape/security/provider/Sun.java
new file mode 100644
index 000000000..20e295caa
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/Sun.java
@@ -0,0 +1,133 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.io.*;
+import java.util.*;
+import java.security.*;
+
+/**
+ * The SUN Security Provider.
+ *
+ * @author Benjamin Renaud
+ *
+ * @version 1.24, 97/12/10
+ */
+
+/**
+ * Defines the SUN provider.
+ *
+ * Algorithm supported, and their names:
+ *
+ * - SHA-1 is the message digest scheme decribed FIPS 180-1.
+ * Aliases for SHA-1 are SHA.
+ *
+ * - DSA is the signature scheme described in FIPS 186. (SHA used in
+ * DSA is SHA-1: FIPS 186 with Change No 1.) Aliases for DSA are
+ * SHA/DSA, SHA-1/DSA, SHA1/DSA, DSS and the object identifier
+ * strings "OID.1.3.14.3.2.13", "OID.1.3.14.3.2.27" and
+ * "OID.1.2.840.10040.4.3".
+ *
+ * - DSA is the key generation scheme as described in FIPS 186.
+ * Aliases for DSA include the OID strings "OID.1.3.14.3.2.12"
+ * and "OID.1.2.840.10040.4.1".
+ *
+ * - MD5 is the message digest scheme described in RFC 1321.
+ * There are no aliases for MD5.
+ *
+ * Notes: The name of algorithm described in FIPS-180 is SHA-0, and is
+ * not supported by the SUN provider.)
+ */
+public final class Sun extends Provider {
+
+ private static String info = "SUN Security Provider v1.0, " +
+ "DSA signing and key generation, SHA-1 and MD5 message digests.";
+
+ public Sun() {
+ /* We are the SUN provider */
+ super("SUN", 1.0, info);
+
+ try {
+
+// AccessController.beginPrivileged();
+
+ /*
+ * Signature engines
+ */
+ put("Signature.DSA", "netscape.security.provider.DSA");
+
+ put("Alg.Alias.Signature.SHA/DSA", "DSA");
+ put("Alg.Alias.Signature.SHA1/DSA", "DSA");
+ put("Alg.Alias.Signature.SHA-1/DSA", "DSA");
+ put("Alg.Alias.Signature.DSS", "DSA");
+ put("Alg.Alias.Signature.OID.1.3.14.3.2.13", "DSA");
+ put("Alg.Alias.Signature.OID.1.3.14.3.2.27", "DSA");
+ put("Alg.Alias.Signature.OID.1.2.840.10040.4.3", "DSA");
+ // the following are not according to our formal spec but
+ // are still supported
+ put("Alg.Alias.Signature.1.3.14.3.2.13", "DSA");
+ put("Alg.Alias.Signature.1.3.14.3.2.27", "DSA");
+ put("Alg.Alias.Signature.1.2.840.10040.4.3", "DSA");
+ put("Alg.Alias.Signature.SHAwithDSA", "DSA");
+ put("Alg.Alias.Signature.SHA1withDSA", "DSA");
+
+ /*
+ * Key Pair Generator engines
+ */
+ put("KeyPairGenerator.DSA",
+ "netscape.security.provider.DSAKeyPairGenerator");
+
+ put("Alg.Alias.KeyPairGenerator.OID.1.3.14.3.2.12", "DSA");
+ put("Alg.Alias.KeyPairGenerator.OID.1.2.840.10040.4.1", "DSA");
+ // the following are not according to our formal spec but
+ // are still supported
+ put("Alg.Alias.KeyPairGenerator.1.3.14.3.2.12", "DSA");
+ put("Alg.Alias.KeyPairGenerator.1.2.840.10040.4.1", "DSA");
+
+ /*
+ * Digest engines
+ */
+ put("MessageDigest.MD5", "netscape.security.provider.MD5");
+ put("MessageDigest.SHA-1", "netscape.security.provider.SHA");
+
+ put("Alg.Alias.MessageDigest.SHA", "SHA-1");
+ put("Alg.Alias.MessageDigest.SHA1", "SHA-1");
+
+ /*
+ * Algorithm Parameter Generator engines
+ */
+ put("AlgorithmParameterGenerator.DSA",
+ "netscape.security.provider.DSAParameterGenerator");
+
+ /*
+ * Algorithm Parameter engines
+ */
+ put("AlgorithmParameters.DSA",
+ "netscape.security.provider.DSAParameters");
+ put("Alg.Alias.AlgorithmParameters.1.3.14.3.2.12", "DSA");
+ put("Alg.Alias.AlgorithmParameters.1.2.840.10040.4.1", "DSA");
+ /*
+ * Key factories
+ */
+ put("KeyFactory.DSA", "netscape.security.provider.DSAKeyFactory");
+
+ } finally {
+// AccessController.endPrivileged();
+ }
+ }
+}
diff --git a/pki/base/util/src/netscape/security/provider/SystemIdentity.java b/pki/base/util/src/netscape/security/provider/SystemIdentity.java
new file mode 100644
index 000000000..ec06810ff
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/SystemIdentity.java
@@ -0,0 +1,76 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.io.Serializable;
+import java.util.Enumeration;
+import java.security.*;
+
+/**
+ * An identity.
+ *
+ * @version 1.19, 09/12/97
+ * @author Benjamin Renaud
+ */
+
+public class SystemIdentity extends Identity implements Serializable {
+
+ /** use serialVersionUID from JDK 1.1. for interoperability */
+ private static final long serialVersionUID = 9060648952088498478L;
+
+ /* Free form additional information about this identity. */
+ private String info;
+
+ /* This exists only for serialization bc and don't use it! */
+ private boolean trusted = false;
+
+ public SystemIdentity(String name, IdentityScope scope)
+ throws InvalidParameterException, KeyManagementException {
+ super(name, scope);
+ }
+
+ void setIdentityInfo(String info) {
+ super.setInfo(info);
+ }
+
+ String getIndentityInfo() {
+ return super.getInfo();
+ }
+
+ /**
+ * Call back method into a protected method for package friends.
+ */
+ void setIdentityPublicKey(PublicKey key) throws KeyManagementException {
+ setPublicKey(key);
+ }
+
+ /**
+ * Call back method into a protected method for package friends.
+ */
+ void addIdentityCertificate(Certificate cert)
+ throws KeyManagementException {
+ addCertificate(cert);
+ }
+
+ void clearCertificates() throws KeyManagementException {
+ Certificate[] certs = certificates();
+ for (int i = 0; i < certs.length; i++) {
+ removeCertificate(certs[i]);
+ }
+ }
+}
diff --git a/pki/base/util/src/netscape/security/provider/SystemSigner.java b/pki/base/util/src/netscape/security/provider/SystemSigner.java
new file mode 100644
index 000000000..ffce24019
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/SystemSigner.java
@@ -0,0 +1,84 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.util.*;
+import java.security.*;
+
+/**
+ * SunSecurity signer.
+ *
+ * @version 1.24, 09/12/97
+ * @author Benjamin Renaud */
+public class SystemSigner extends Signer {
+
+ /** use serialVersionUID from JDK 1.1. for interoperability */
+ private static final long serialVersionUID = -2127743304301557711L;
+
+ /* This exists only for serialization bc and don't use it! */
+ private boolean trusted = false;
+
+ /**
+ * Construct a signer with a given name.
+ */
+ public SystemSigner(String name) {
+ super(name);
+ }
+
+ /**
+ * Construct a signer with a name and a scope.
+ *
+ * @param name the signer's name.
+ *
+ * @param scope the scope for this signer.
+ */
+ public SystemSigner(String name, IdentityScope scope)
+ throws KeyManagementException {
+
+ super(name, scope);
+ }
+
+ /* friendly callback for set keys */
+ void setSignerKeyPair(KeyPair pair)
+ throws InvalidParameterException, KeyException {
+ setKeyPair(pair);
+ }
+
+ /* friendly callback for getting private keys */
+ PrivateKey getSignerPrivateKey() {
+ return getPrivateKey();
+ }
+
+ void setSignerInfo(String s) {
+ setInfo(s);
+ }
+
+ /**
+ * Call back method into a protected method for package friends.
+ */
+ void addSignerCertificate(Certificate cert) throws KeyManagementException {
+ addCertificate(cert);
+ }
+
+ void clearCertificates() throws KeyManagementException {
+ Certificate[] certs = certificates();
+ for (int i = 0; i < certs.length; i++) {
+ removeCertificate(certs[i]);
+ }
+ }
+}
diff --git a/pki/base/util/src/netscape/security/provider/X509CertificateFactory.java b/pki/base/util/src/netscape/security/provider/X509CertificateFactory.java
new file mode 100644
index 000000000..6fa19fa5b
--- /dev/null
+++ b/pki/base/util/src/netscape/security/provider/X509CertificateFactory.java
@@ -0,0 +1,59 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package netscape.security.provider;
+
+import java.security.cert.*;
+import java.io.InputStream;
+import java.util.Collection;
+import java.security.Provider;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import netscape.security.x509.X509CertImpl;
+import netscape.security.x509.X509CRLImpl;
+import netscape.security.x509.X509ExtensionException;
+
+public class X509CertificateFactory extends CertificateFactorySpi {
+
+ public Certificate engineGenerateCertificate(InputStream inStream)
+ throws CertificateException {
+ return new X509CertImpl(inStream);
+ }
+ public Collection engineGenerateCertificates(InputStream inStream)
+ throws CertificateException {
+ return null;
+ }
+
+ public CRL engineGenerateCRL(InputStream inStream)
+ throws CRLException {
+ X509CRLImpl crl = null;
+ try {
+ crl = new X509CRLImpl(inStream);
+ }
+ catch (X509ExtensionException e) {
+ ;
+ }
+
+ return crl;
+ }
+
+ public Collection engineGenerateCRLs(InputStream inStream)
+ throws CRLException {
+ return null;
+ }
+
+}