diff options
author | Peter Dettman <peter.dettman@bouncycastle.org> | 2014-06-30 18:10:23 +0400 |
---|---|---|
committer | Peter Dettman <peter.dettman@bouncycastle.org> | 2014-06-30 18:10:23 +0400 |
commit | ebe240ce7fbe01542216ea7d3bcddb5555cfb29c (patch) | |
tree | a87581671c3ddf13ce849cef0e9a4ebf70623811 | |
parent | d68a9ab9534d1d732058986acc2bbba8b8a6bfae (diff) | |
parent | 86d074dbcf9b6bab29985eee7b7187f3b85b0f43 (diff) |
Merge branch 'master' of git.bouncycastle.org:bc-java
33 files changed, 2589 insertions, 7811 deletions
diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/CramerShoupCiphertext.java b/core/src/main/java/org/bouncycastle/crypto/engines/CramerShoupCiphertext.java index 1e43eb2a..0d8ba19d 100644 --- a/core/src/main/java/org/bouncycastle/crypto/engines/CramerShoupCiphertext.java +++ b/core/src/main/java/org/bouncycastle/crypto/engines/CramerShoupCiphertext.java @@ -3,160 +3,177 @@ package org.bouncycastle.crypto.engines; import java.math.BigInteger; /** - * * Class, holding Cramer Shoup ciphertexts (u1, u2, e, v) - * */ -public class CramerShoupCiphertext { - - BigInteger u1, u2, e, v; - - public CramerShoupCiphertext() { - - } - - public CramerShoupCiphertext(BigInteger u1, BigInteger u2, BigInteger e, BigInteger v){ - this.u1 = u1; - this.u2 = u2; - this.e = e; - this.v = v; - } - - public CramerShoupCiphertext(byte[] c){ - int off = 0, s; - byte[] size = new byte[4]; - byte[] tmp; - - System.arraycopy(c, off, size, 0, 4); - s = byteArrayToInt(size); - tmp = new byte[s]; - off += 4; - System.arraycopy(c, off, tmp, 0, s); - off += s; - u1 = new BigInteger(tmp); - - System.arraycopy(c, off, size, 0, 4); - s = byteArrayToInt(size); - tmp = new byte[s]; - off += 4; - System.arraycopy(c, off, tmp, 0, s); - off += s; - u2 = new BigInteger(tmp); - - System.arraycopy(c, off, size, 0, 4); - s = byteArrayToInt(size); - tmp = new byte[s]; - off += 4; - System.arraycopy(c, off, tmp, 0, s); - off += s; - e = new BigInteger(tmp); - - System.arraycopy(c, off, size, 0, 4); - s = byteArrayToInt(size); - tmp = new byte[s]; - off += 4; - System.arraycopy(c, off, tmp, 0, s); - off += s; - v = new BigInteger(tmp); - } - - public BigInteger getU1() { - return u1; - } - - public void setU1(BigInteger u1) { - this.u1 = u1; - } - - public BigInteger getU2() { - return u2; - } - - public void setU2(BigInteger u2) { - this.u2 = u2; - } - - public BigInteger getE() { - return e; - } - - public void setE(BigInteger e) { - this.e = e; - } - - public BigInteger getV() { - return v; - } - - public void setV(BigInteger v) { - this.v = v; - } - - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - - result.append("u1: "+u1.toString()); - result.append("\nu2: "+u2.toString()); - result.append("\ne: "+e.toString()); - result.append("\nv: "+v.toString()); - - return result.toString(); - } - - /** - * convert the cipher-text in a byte array, - * prepending them with 4 Bytes for their length - * - * @return - */ - public byte[] toByteArray(){ - - byte[] u1Bytes = u1.toByteArray(); - int u1Length = u1Bytes.length; - byte[] u2Bytes = u2.toByteArray(); - int u2Length = u2Bytes.length; - byte[] eBytes = e.toByteArray(); - int eLength = eBytes.length; - byte[] vBytes = v.toByteArray(); - int vLength = vBytes.length; - - int off = 0; - byte[] result = new byte[u1Length+u2Length+eLength+vLength+4*4]; - System.arraycopy(intToByteArray(u1Length), 0, result, 0, 4); - off += 4; - System.arraycopy(u1Bytes, 0, result, off, u1Length); - off += u1Length; - System.arraycopy(intToByteArray(u2Length), 0, result, off, 4); - off += 4; - System.arraycopy(u2Bytes, 0, result, off , u2Length); - off += u2Length; - System.arraycopy(intToByteArray(eLength), 0, result, off, 4); - off += 4; - System.arraycopy(eBytes, 0, result, off, eLength); - off += eLength; - System.arraycopy(intToByteArray(vLength), 0, result, off, 4); - off += 4; - System.arraycopy(vBytes, 0, result, off, vLength); - - return result; - } - - private byte[] intToByteArray(int in){ - byte[] bytes = new byte[4]; - for (int i = 0; i < 4; i++) { - bytes[3-i] = (byte)(in >>> (i * 8)); - } - return bytes; - } - - private int byteArrayToInt(byte[] in){ - if (in.length != 4) - return -1; - int r = 0; - for (int i = 3; i >= 0; i--) { - r += (int)in[i] << ((3-i) * 8); - } - return r; - } +public class CramerShoupCiphertext +{ + + BigInteger u1, u2, e, v; + + public CramerShoupCiphertext() + { + + } + + public CramerShoupCiphertext(BigInteger u1, BigInteger u2, BigInteger e, BigInteger v) + { + this.u1 = u1; + this.u2 = u2; + this.e = e; + this.v = v; + } + + public CramerShoupCiphertext(byte[] c) + { + int off = 0, s; + byte[] size = new byte[4]; + byte[] tmp; + + System.arraycopy(c, off, size, 0, 4); + s = byteArrayToInt(size); + tmp = new byte[s]; + off += 4; + System.arraycopy(c, off, tmp, 0, s); + off += s; + u1 = new BigInteger(tmp); + + System.arraycopy(c, off, size, 0, 4); + s = byteArrayToInt(size); + tmp = new byte[s]; + off += 4; + System.arraycopy(c, off, tmp, 0, s); + off += s; + u2 = new BigInteger(tmp); + + System.arraycopy(c, off, size, 0, 4); + s = byteArrayToInt(size); + tmp = new byte[s]; + off += 4; + System.arraycopy(c, off, tmp, 0, s); + off += s; + e = new BigInteger(tmp); + + System.arraycopy(c, off, size, 0, 4); + s = byteArrayToInt(size); + tmp = new byte[s]; + off += 4; + System.arraycopy(c, off, tmp, 0, s); + off += s; + v = new BigInteger(tmp); + } + + public BigInteger getU1() + { + return u1; + } + + public void setU1(BigInteger u1) + { + this.u1 = u1; + } + + public BigInteger getU2() + { + return u2; + } + + public void setU2(BigInteger u2) + { + this.u2 = u2; + } + + public BigInteger getE() + { + return e; + } + + public void setE(BigInteger e) + { + this.e = e; + } + + public BigInteger getV() + { + return v; + } + + public void setV(BigInteger v) + { + this.v = v; + } + + public String toString() + { + StringBuffer result = new StringBuffer(); + + result.append("u1: " + u1.toString()); + result.append("\nu2: " + u2.toString()); + result.append("\ne: " + e.toString()); + result.append("\nv: " + v.toString()); + + return result.toString(); + } + + /** + * convert the cipher-text in a byte array, + * prepending them with 4 Bytes for their length + * + * @return + */ + public byte[] toByteArray() + { + + byte[] u1Bytes = u1.toByteArray(); + int u1Length = u1Bytes.length; + byte[] u2Bytes = u2.toByteArray(); + int u2Length = u2Bytes.length; + byte[] eBytes = e.toByteArray(); + int eLength = eBytes.length; + byte[] vBytes = v.toByteArray(); + int vLength = vBytes.length; + + int off = 0; + byte[] result = new byte[u1Length + u2Length + eLength + vLength + 4 * 4]; + System.arraycopy(intToByteArray(u1Length), 0, result, 0, 4); + off += 4; + System.arraycopy(u1Bytes, 0, result, off, u1Length); + off += u1Length; + System.arraycopy(intToByteArray(u2Length), 0, result, off, 4); + off += 4; + System.arraycopy(u2Bytes, 0, result, off, u2Length); + off += u2Length; + System.arraycopy(intToByteArray(eLength), 0, result, off, 4); + off += 4; + System.arraycopy(eBytes, 0, result, off, eLength); + off += eLength; + System.arraycopy(intToByteArray(vLength), 0, result, off, 4); + off += 4; + System.arraycopy(vBytes, 0, result, off, vLength); + + return result; + } + + private byte[] intToByteArray(int in) + { + byte[] bytes = new byte[4]; + for (int i = 0; i < 4; i++) + { + bytes[3 - i] = (byte)(in >>> (i * 8)); + } + return bytes; + } + + private int byteArrayToInt(byte[] in) + { + if (in.length != 4) + { + return -1; + } + int r = 0; + for (int i = 3; i >= 0; i--) + { + r += (int)in[i] << ((3 - i) * 8); + } + return r; + } }
\ No newline at end of file diff --git a/core/src/main/java/org/bouncycastle/crypto/engines/CramerShoupCoreEngine.java b/core/src/main/java/org/bouncycastle/crypto/engines/CramerShoupCoreEngine.java index cc6d96be..5fcfff9b 100644 --- a/core/src/main/java/org/bouncycastle/crypto/engines/CramerShoupCoreEngine.java +++ b/core/src/main/java/org/bouncycastle/crypto/engines/CramerShoupCoreEngine.java @@ -13,263 +13,302 @@ import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.util.BigIntegers; /** - * * Essentially the Cramer-Shoup encryption / decryption algorithms according to * "A practical public key cryptosystem provably secure against adaptive chosen ciphertext attack." (Crypto 1998) - * */ -public class CramerShoupCoreEngine { +public class CramerShoupCoreEngine +{ - private static final BigInteger ONE = BigInteger.ONE; - - private CramerShoupKeyParameters key; + private static final BigInteger ONE = BigInteger.valueOf(1); + + private CramerShoupKeyParameters key; private SecureRandom random; - private boolean forEncryption; - private String label = null; - - /** - * initialise the CramerShoup engine. - * - * @param forEncryption - * whether this engine should encrypt or decrypt - * @param param - * the necessary CramerShoup key parameters. - * @param label - * the label for labelled CS as {@link String} - */ - public void init(boolean forEncryption, CipherParameters param, String label) { - init(forEncryption, param); - - this.label = label; - } - - /** - * initialise the CramerShoup engine. - * - * @param forEncryption - * whether this engine should encrypt or decrypt - * @param param - * the necessary CramerShoup key parameters. - */ - public void init(boolean forEncryption, CipherParameters param) { + private boolean forEncryption; + private String label = null; + + /** + * initialise the CramerShoup engine. + * + * @param forEncryption whether this engine should encrypt or decrypt + * @param param the necessary CramerShoup key parameters. + * @param label the label for labelled CS as {@link String} + */ + public void init(boolean forEncryption, CipherParameters param, String label) + { + init(forEncryption, param); + + this.label = label; + } + + /** + * initialise the CramerShoup engine. + * + * @param forEncryption whether this engine should encrypt or decrypt + * @param param the necessary CramerShoup key parameters. + */ + public void init(boolean forEncryption, CipherParameters param) + { SecureRandom providedRandom = null; - if (param instanceof ParametersWithRandom) { - ParametersWithRandom rParam = (ParametersWithRandom) param; + if (param instanceof ParametersWithRandom) + { + ParametersWithRandom rParam = (ParametersWithRandom)param; - key = (CramerShoupKeyParameters) rParam.getParameters(); + key = (CramerShoupKeyParameters)rParam.getParameters(); providedRandom = rParam.getRandom(); - } else { - key = (CramerShoupKeyParameters) param; - } + } + else + { + key = (CramerShoupKeyParameters)param; + } this.random = initSecureRandom(forEncryption, providedRandom); - this.forEncryption = forEncryption; - } - - /** - * Return the maximum size for an input block to this engine. For Cramer - * Shoup this is always one byte less than the key size on encryption, and - * the same length as the key size on decryption. - * - * @return maximum size for an input block. - * - * TODO: correct? - */ - public int getInputBlockSize() { - int bitSize = key.getParameters().getP().bitLength(); - - if (forEncryption) { - return (bitSize + 7) / 8 - 1; - } else { - return (bitSize + 7) / 8; - } - } - - /** - * Return the maximum size for an output block to this engine. For Cramer - * Shoup this is always one byte less than the key size on decryption, and - * the same length as the key size on encryption. - * - * @return maximum size for an output block. - * - * TODO: correct? - */ - public int getOutputBlockSize() { - int bitSize = key.getParameters().getP().bitLength(); - - if (forEncryption) { - return (bitSize + 7) / 8; - } else { - return (bitSize + 7) / 8 - 1; - } - } - - public BigInteger convertInput(byte[] in, int inOff, int inLen) { - if (inLen > (getInputBlockSize() + 1)) { - throw new DataLengthException("input too large for Cramer Shoup cipher."); - } else if (inLen == (getInputBlockSize() + 1) && forEncryption) { - throw new DataLengthException("input too large for Cramer Shoup cipher."); - } - - byte[] block; - - if (inOff != 0 || inLen != in.length) { - block = new byte[inLen]; - - System.arraycopy(in, inOff, block, 0, inLen); - } else { - block = in; - } - - BigInteger res = new BigInteger(1, block); - if (res.compareTo(key.getParameters().getP()) >= 0) { - throw new DataLengthException("input too large for Cramer Shoup cipher."); - } - - return res; - } - - public byte[] convertOutput(BigInteger result) { - byte[] output = result.toByteArray(); - - if (!forEncryption) { - if (output[0] == 0 && output.length > getOutputBlockSize()) { // have ended up with an extra zero byte, copy down. - byte[] tmp = new byte[output.length - 1]; - - System.arraycopy(output, 1, tmp, 0, tmp.length); - - return tmp; - } - - if (output.length < getOutputBlockSize()) {// have ended up with less bytes than normal, lengthen - byte[] tmp = new byte[getOutputBlockSize()]; - - System.arraycopy(output, 0, tmp, tmp.length - output.length, output.length); - - return tmp; - } - } else { - if (output[0] == 0) { // have ended up with an extra zero byte, copy down. - byte[] tmp = new byte[output.length - 1]; - - System.arraycopy(output, 1, tmp, 0, tmp.length); - - return tmp; - } - } - - return output; - } - - public CramerShoupCiphertext encryptBlock(BigInteger input) { - - CramerShoupCiphertext result = null; - - if (!key.isPrivate() && this.forEncryption && key instanceof CramerShoupPublicKeyParameters) { - CramerShoupPublicKeyParameters pk = (CramerShoupPublicKeyParameters)key; - BigInteger p = pk.getParameters().getP(); - BigInteger g1 = pk.getParameters().getG1(); - BigInteger g2 = pk.getParameters().getG2(); - - BigInteger h = pk.getH(); - - if (!isValidMessage(input, p)) - return result; - - BigInteger r = generateRandomElement(p, random); - - BigInteger u1, u2, v, e, a; - - u1 = g1.modPow(r, p); - u2 = g2.modPow(r, p); - e = h.modPow(r, p).multiply(input).mod(p); - - Digest digest = pk.getParameters().getH(); - byte[] u1Bytes = u1.toByteArray(); - digest.update(u1Bytes, 0, u1Bytes.length); - byte[] u2Bytes = u2.toByteArray(); - digest.update(u2Bytes, 0, u2Bytes.length); - byte[] eBytes = e.toByteArray(); - digest.update(eBytes, 0, eBytes.length); - if (this.label != null){ - byte[] lBytes = this.label.getBytes(); - digest.update(lBytes, 0, lBytes.length); - } - byte[] out = new byte[digest.getDigestSize()]; - digest.doFinal(out , 0); - a = new BigInteger(1, out); - - v = pk.getC().modPow(r, p).multiply(pk.getD().modPow(r.multiply(a), p)).mod(p); - - result = new CramerShoupCiphertext(u1, u2, e, v); - } - return result; - } - - public BigInteger decryptBlock(CramerShoupCiphertext input) throws CramerShoupCiphertextException { - - BigInteger result = null; - - if (key.isPrivate() && !this.forEncryption && key instanceof CramerShoupPrivateKeyParameters) { - CramerShoupPrivateKeyParameters sk = (CramerShoupPrivateKeyParameters)key; - - BigInteger p = sk.getParameters().getP(); - - Digest digest = sk.getParameters().getH(); - byte[] u1Bytes = input.getU1().toByteArray(); - digest.update(u1Bytes, 0, u1Bytes.length); - byte[] u2Bytes = input.getU2().toByteArray(); - digest.update(u2Bytes, 0, u2Bytes.length); - byte[] eBytes = input.getE().toByteArray(); - digest.update(eBytes, 0, eBytes.length); - if (this.label != null){ - byte[] lBytes = this.label.getBytes(); - digest.update(lBytes, 0, lBytes.length); - } - byte[] out = new byte[digest.getDigestSize()]; - digest.doFinal(out , 0); - - BigInteger a = new BigInteger(1, out); - BigInteger v = input.u1.modPow(sk.getX1().add(sk.getY1().multiply(a)), p). - multiply(input.u2.modPow(sk.getX2().add(sk.getY2().multiply(a)), p)).mod(p); - - // check correctness of ciphertext - if (input.v.equals(v)){ - result = input.e.multiply(input.u1.modPow(sk.getZ(), p).modInverse(p)).mod(p); - } else { - throw new CramerShoupCiphertextException("Sorry, that ciphertext is not correct"); - } - } - return result; - } - - private BigInteger generateRandomElement(BigInteger p, SecureRandom random) { - return BigIntegers.createRandomInRange(ONE, p.subtract(ONE), random); - } - - /** - * just checking whether the message m is actually less than the group order p - */ - private boolean isValidMessage(BigInteger m, BigInteger p){ - return m.compareTo(p) < 0; - } + this.forEncryption = forEncryption; + } + + /** + * Return the maximum size for an input block to this engine. For Cramer + * Shoup this is always one byte less than the key size on encryption, and + * the same length as the key size on decryption. + * + * @return maximum size for an input block. + * <p/> + * TODO: correct? + */ + public int getInputBlockSize() + { + int bitSize = key.getParameters().getP().bitLength(); + + if (forEncryption) + { + return (bitSize + 7) / 8 - 1; + } + else + { + return (bitSize + 7) / 8; + } + } + + /** + * Return the maximum size for an output block to this engine. For Cramer + * Shoup this is always one byte less than the key size on decryption, and + * the same length as the key size on encryption. + * + * @return maximum size for an output block. + * <p/> + * TODO: correct? + */ + public int getOutputBlockSize() + { + int bitSize = key.getParameters().getP().bitLength(); + + if (forEncryption) + { + return (bitSize + 7) / 8; + } + else + { + return (bitSize + 7) / 8 - 1; + } + } + + public BigInteger convertInput(byte[] in, int inOff, int inLen) + { + if (inLen > (getInputBlockSize() + 1)) + { + throw new DataLengthException("input too large for Cramer Shoup cipher."); + } + else if (inLen == (getInputBlockSize() + 1) && forEncryption) + { + throw new DataLengthException("input too large for Cramer Shoup cipher."); + } + + byte[] block; + + if (inOff != 0 || inLen != in.length) + { + block = new byte[inLen]; + + System.arraycopy(in, inOff, block, 0, inLen); + } + else + { + block = in; + } + + BigInteger res = new BigInteger(1, block); + if (res.compareTo(key.getParameters().getP()) >= 0) + { + throw new DataLengthException("input too large for Cramer Shoup cipher."); + } + + return res; + } + + public byte[] convertOutput(BigInteger result) + { + byte[] output = result.toByteArray(); + + if (!forEncryption) + { + if (output[0] == 0 && output.length > getOutputBlockSize()) + { // have ended up with an extra zero byte, copy down. + byte[] tmp = new byte[output.length - 1]; + + System.arraycopy(output, 1, tmp, 0, tmp.length); + + return tmp; + } + + if (output.length < getOutputBlockSize()) + {// have ended up with less bytes than normal, lengthen + byte[] tmp = new byte[getOutputBlockSize()]; + + System.arraycopy(output, 0, tmp, tmp.length - output.length, output.length); + + return tmp; + } + } + else + { + if (output[0] == 0) + { // have ended up with an extra zero byte, copy down. + byte[] tmp = new byte[output.length - 1]; + + System.arraycopy(output, 1, tmp, 0, tmp.length); + + return tmp; + } + } + + return output; + } + + public CramerShoupCiphertext encryptBlock(BigInteger input) + { + + CramerShoupCiphertext result = null; + + if (!key.isPrivate() && this.forEncryption && key instanceof CramerShoupPublicKeyParameters) + { + CramerShoupPublicKeyParameters pk = (CramerShoupPublicKeyParameters)key; + BigInteger p = pk.getParameters().getP(); + BigInteger g1 = pk.getParameters().getG1(); + BigInteger g2 = pk.getParameters().getG2(); + + BigInteger h = pk.getH(); + + if (!isValidMessage(input, p)) + { + return result; + } + + BigInteger r = generateRandomElement(p, random); + + BigInteger u1, u2, v, e, a; + + u1 = g1.modPow(r, p); + u2 = g2.modPow(r, p); + e = h.modPow(r, p).multiply(input).mod(p); + + Digest digest = pk.getParameters().getH(); + byte[] u1Bytes = u1.toByteArray(); + digest.update(u1Bytes, 0, u1Bytes.length); + byte[] u2Bytes = u2.toByteArray(); + digest.update(u2Bytes, 0, u2Bytes.length); + byte[] eBytes = e.toByteArray(); + digest.update(eBytes, 0, eBytes.length); + if (this.label != null) + { + byte[] lBytes = this.label.getBytes(); + digest.update(lBytes, 0, lBytes.length); + } + byte[] out = new byte[digest.getDigestSize()]; + digest.doFinal(out, 0); + a = new BigInteger(1, out); + + v = pk.getC().modPow(r, p).multiply(pk.getD().modPow(r.multiply(a), p)).mod(p); + + result = new CramerShoupCiphertext(u1, u2, e, v); + } + return result; + } + + public BigInteger decryptBlock(CramerShoupCiphertext input) + throws CramerShoupCiphertextException + { + + BigInteger result = null; + + if (key.isPrivate() && !this.forEncryption && key instanceof CramerShoupPrivateKeyParameters) + { + CramerShoupPrivateKeyParameters sk = (CramerShoupPrivateKeyParameters)key; + + BigInteger p = sk.getParameters().getP(); + + Digest digest = sk.getParameters().getH(); + byte[] u1Bytes = input.getU1().toByteArray(); + digest.update(u1Bytes, 0, u1Bytes.length); + byte[] u2Bytes = input.getU2().toByteArray(); + digest.update(u2Bytes, 0, u2Bytes.length); + byte[] eBytes = input.getE().toByteArray(); + digest.update(eBytes, 0, eBytes.length); + if (this.label != null) + { + byte[] lBytes = this.label.getBytes(); + digest.update(lBytes, 0, lBytes.length); + } + byte[] out = new byte[digest.getDigestSize()]; + digest.doFinal(out, 0); + + BigInteger a = new BigInteger(1, out); + BigInteger v = input.u1.modPow(sk.getX1().add(sk.getY1().multiply(a)), p). + multiply(input.u2.modPow(sk.getX2().add(sk.getY2().multiply(a)), p)).mod(p); + + // check correctness of ciphertext + if (input.v.equals(v)) + { + result = input.e.multiply(input.u1.modPow(sk.getZ(), p).modInverse(p)).mod(p); + } + else + { + throw new CramerShoupCiphertextException("Sorry, that ciphertext is not correct"); + } + } + return result; + } + + private BigInteger generateRandomElement(BigInteger p, SecureRandom random) + { + return BigIntegers.createRandomInRange(ONE, p.subtract(ONE), random); + } + + /** + * just checking whether the message m is actually less than the group order p + */ + private boolean isValidMessage(BigInteger m, BigInteger p) + { + return m.compareTo(p) < 0; + } protected SecureRandom initSecureRandom(boolean needed, SecureRandom provided) { return !needed ? null : (provided != null) ? provided : new SecureRandom(); } - /** - * CS exception for wrong cipher-texts - */ - public class CramerShoupCiphertextException extends Exception { - - private static final long serialVersionUID = -6360977166495345076L; - - public CramerShoupCiphertextException(String msg) { - super(msg); - } - - } + /** + * CS exception for wrong cipher-texts + */ + public class CramerShoupCiphertextException + extends Exception + { + + private static final long serialVersionUID = -6360977166495345076L; + + public CramerShoupCiphertextException(String msg) + { + super(msg); + } + + } } diff --git a/core/src/test/java/org/bouncycastle/crypto/test/CramerShoupTest.java b/core/src/test/java/org/bouncycastle/crypto/test/CramerShoupTest.java index 2eb90152..e9633572 100644 --- a/core/src/test/java/org/bouncycastle/crypto/test/CramerShoupTest.java +++ b/core/src/test/java/org/bouncycastle/crypto/test/CramerShoupTest.java @@ -15,106 +15,133 @@ import org.bouncycastle.crypto.params.CramerShoupParameters; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.test.SimpleTest; -public class CramerShoupTest extends SimpleTest { +public class CramerShoupTest + extends SimpleTest +{ + private static final BigInteger ONE = BigInteger.valueOf(1); private static final SecureRandom RND = new SecureRandom(); - private AsymmetricCipherKeyPair keyPair; - - public static void main(String[] args) { - runTest(new CramerShoupTest()); - } - - @Override - public String getName() { - return "CramerShoup"; - } - - @Override - public void performTest() throws Exception { - BigInteger pSubOne = DHStandardGroups.rfc3526_2048.getP().subtract(BigInteger.ONE); - for (int i = 0; i < 10; ++i) { - BigInteger message = BigIntegers.createRandomInRange(BigInteger.ONE, pSubOne, RND); - - BigInteger m1 = encDecTest(message); - BigInteger m2 = labelledEncDecTest(message, "myRandomLabel"); - BigInteger m3 = encDecEncodingTest(message); - BigInteger m4 = labelledEncDecEncodingTest(message, "myOtherCoolLabel"); - - if (!message.equals(m1) || !message.equals(m2) || !message.equals(m3) || !message.equals(m4)){ - fail("decrypted message != original message"); - } - } - } - - private BigInteger encDecEncodingTest(BigInteger m){ - CramerShoupCiphertext ciphertext = encrypt(m); - byte[] c = ciphertext.toByteArray(); - CramerShoupCiphertext decC = new CramerShoupCiphertext(c); - return decrypt(decC); - } - - private BigInteger labelledEncDecEncodingTest(BigInteger m, String l){ - byte[] c = encrypt(m, l).toByteArray(); - return decrypt(new CramerShoupCiphertext(c), l); - } - - private BigInteger encDecTest(BigInteger m){ - CramerShoupCiphertext c = encrypt(m); - return decrypt(c); - } - - private BigInteger labelledEncDecTest(BigInteger m, String l){ - CramerShoupCiphertext c = encrypt(m, l); - return decrypt(c, l); - } - - - private BigInteger decrypt(CramerShoupCiphertext ciphertext) { - return decrypt(ciphertext, null); - } - - private BigInteger decrypt(CramerShoupCiphertext ciphertext, String label) { - - CramerShoupCoreEngine engine = new CramerShoupCoreEngine(); - if (label != null) - engine.init(false, keyPair.getPrivate(), label); - else - engine.init(false, keyPair.getPrivate()); - try { - BigInteger m = engine.decryptBlock(ciphertext); - - return m; - } catch (CramerShoupCiphertextException e) { - e.printStackTrace(); - } - - return null; - } - - private CramerShoupCiphertext encrypt(BigInteger message) { - return encrypt(message, null); - } - - private CramerShoupCiphertext encrypt(BigInteger message, String label) { - CramerShoupKeyPairGenerator kpGen = new CramerShoupKeyPairGenerator(); - CramerShoupParametersGenerator pGen = new CramerShoupParametersGenerator(); - - pGen.init(2048, 1, RND); - CramerShoupParameters params = pGen.generateParameters(DHStandardGroups.rfc3526_2048); - CramerShoupKeyGenerationParameters param = new CramerShoupKeyGenerationParameters(RND, params); - - kpGen.init(param); - keyPair = kpGen.generateKeyPair(); - - CramerShoupCoreEngine engine = new CramerShoupCoreEngine(); - if (label != null) - engine.init(true, keyPair.getPublic(), label); - else - engine.init(true, keyPair.getPublic()); - - CramerShoupCiphertext ciphertext = engine.encryptBlock(message); - - return ciphertext; - } + private AsymmetricCipherKeyPair keyPair; + + public static void main(String[] args) + { + runTest(new CramerShoupTest()); + } + + public String getName() + { + return "CramerShoup"; + } + + + public void performTest() + throws Exception + { + BigInteger pSubOne = DHStandardGroups.rfc3526_2048.getP().subtract(ONE); + for (int i = 0; i < 10; ++i) + { + BigInteger message = BigIntegers.createRandomInRange(ONE, pSubOne, RND); + + BigInteger m1 = encDecTest(message); + BigInteger m2 = labelledEncDecTest(message, "myRandomLabel"); + BigInteger m3 = encDecEncodingTest(message); + BigInteger m4 = labelledEncDecEncodingTest(message, "myOtherCoolLabel"); + + if (!message.equals(m1) || !message.equals(m2) || !message.equals(m3) || !message.equals(m4)) + { + fail("decrypted message != original message"); + } + } + } + + private BigInteger encDecEncodingTest(BigInteger m) + { + CramerShoupCiphertext ciphertext = encrypt(m); + byte[] c = ciphertext.toByteArray(); + CramerShoupCiphertext decC = new CramerShoupCiphertext(c); + return decrypt(decC); + } + + private BigInteger labelledEncDecEncodingTest(BigInteger m, String l) + { + byte[] c = encrypt(m, l).toByteArray(); + return decrypt(new CramerShoupCiphertext(c), l); + } + + private BigInteger encDecTest(BigInteger m) + { + CramerShoupCiphertext c = encrypt(m); + return decrypt(c); + } + + private BigInteger labelledEncDecTest(BigInteger m, String l) + { + CramerShoupCiphertext c = encrypt(m, l); + return decrypt(c, l); + } + + + private BigInteger decrypt(CramerShoupCiphertext ciphertext) + { + return decrypt(ciphertext, null); + } + + private BigInteger decrypt(CramerShoupCiphertext ciphertext, String label) + { + + CramerShoupCoreEngine engine = new CramerShoupCoreEngine(); + if (label != null) + { + engine.init(false, keyPair.getPrivate(), label); + } + else + { + engine.init(false, keyPair.getPrivate()); + } + try + { + BigInteger m = engine.decryptBlock(ciphertext); + + return m; + } + catch (CramerShoupCiphertextException e) + { + e.printStackTrace(); + } + + return null; + } + + private CramerShoupCiphertext encrypt(BigInteger message) + { + return encrypt(message, null); + } + + private CramerShoupCiphertext encrypt(BigInteger message, String label) + { + CramerShoupKeyPairGenerator kpGen = new CramerShoupKeyPairGenerator(); + CramerShoupParametersGenerator pGen = new CramerShoupParametersGenerator(); + + pGen.init(2048, 1, RND); + CramerShoupParameters params = pGen.generateParameters(DHStandardGroups.rfc3526_2048); + CramerShoupKeyGenerationParameters param = new CramerShoupKeyGenerationParameters(RND, params); + + kpGen.init(param); + keyPair = kpGen.generateKeyPair(); + + CramerShoupCoreEngine engine = new CramerShoupCoreEngine(); + if (label != null) + { + engine.init(true, keyPair.getPublic(), label); + } + else + { + engine.init(true, keyPair.getPublic()); + } + + CramerShoupCiphertext ciphertext = engine.encryptBlock(message); + + return ciphertext; + } } diff --git a/core/src/test/java/org/bouncycastle/math/ec/test/ECPointPerformanceTest.java b/core/src/test/java/org/bouncycastle/math/ec/test/ECPointPerformanceTest.java index a5e45dab..6db88a00 100644 --- a/core/src/test/java/org/bouncycastle/math/ec/test/ECPointPerformanceTest.java +++ b/core/src/test/java/org/bouncycastle/math/ec/test/ECPointPerformanceTest.java @@ -2,15 +2,16 @@ package org.bouncycastle.math.ec.test; import java.math.BigInteger; import java.security.SecureRandom; -import java.util.Collections; +import java.util.ArrayList; +import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import junit.framework.TestCase; - import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.x9.ECNamedCurveTable; import org.bouncycastle.asn1.x9.X9ECParameters; @@ -173,8 +174,8 @@ public class ECPointPerformanceTest extends TestCase public void testMultiply() throws Exception { - SortedSet names = new TreeSet(Collections.list(ECNamedCurveTable.getNames())); - names.addAll(Collections.list(CustomNamedCurves.getNames())); + SortedSet names = new TreeSet(enumToList(ECNamedCurveTable.getNames())); + names.addAll(enumToList(CustomNamedCurves.getNames())); Set oids = new HashSet(); @@ -195,4 +196,16 @@ public class ECPointPerformanceTest extends TestCase randMult(name); } } + + private List enumToList(Enumeration en) + { + List rv = new ArrayList(); + + while (en.hasMoreElements()) + { + rv.add(en.nextElement()); + } + + return rv; + } } diff --git a/core/src/test/java/org/bouncycastle/math/ec/test/ECPointTest.java b/core/src/test/java/org/bouncycastle/math/ec/test/ECPointTest.java index 4db9f4bd..1ad4d760 100644 --- a/core/src/test/java/org/bouncycastle/math/ec/test/ECPointTest.java +++ b/core/src/test/java/org/bouncycastle/math/ec/test/ECPointTest.java @@ -2,15 +2,16 @@ package org.bouncycastle.math.ec.test; import java.math.BigInteger; import java.security.SecureRandom; -import java.util.Collections; +import java.util.ArrayList; +import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Set; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; - import org.bouncycastle.asn1.x9.ECNamedCurveTable; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.crypto.ec.CustomNamedCurves; @@ -503,8 +504,8 @@ public class ECPointTest extends TestCase */ public void testAddSubtractMultiplyTwiceEncoding() { - Set names = new HashSet(Collections.list(ECNamedCurveTable.getNames())); - names.addAll(Collections.list(CustomNamedCurves.getNames())); + Set names = new HashSet(enumToList(ECNamedCurveTable.getNames())); + names.addAll(enumToList(CustomNamedCurves.getNames())); Iterator it = names.iterator(); while (it.hasNext()) @@ -525,6 +526,18 @@ public class ECPointTest extends TestCase } } + private List enumToList(Enumeration en) + { + List rv = new ArrayList(); + + while (en.hasMoreElements()) + { + rv.add(en.nextElement()); + } + + return rv; + } + private void assertPointsEqual(String message, ECPoint a, ECPoint b) { assertEquals(message, a, b); diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPSignatureTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPSignatureTest.java index 69ace7d4..dce348bf 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/PGPSignatureTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/PGPSignatureTest.java @@ -696,11 +696,10 @@ public class PGPSignatureTest { PGPUserAttributeSubpacketVector attr = (PGPUserAttributeSubpacketVector)attrit.next(); - Iterator<PGPSignature> sigit = - masterPk.getSignaturesForUserAttribute(attr); + Iterator sigit = masterPk.getSignaturesForUserAttribute(attr); while (sigit.hasNext()) { - PGPSignature sig = sigit.next(); + PGPSignature sig = (PGPSignature)sigit.next(); sig.init(new BcPGPContentVerifierBuilderProvider(), masterPk); if (!sig.verifyCertification(attr, masterPk)) @@ -765,7 +764,7 @@ public class PGPSignatureTest sVec = sGen.generate(); - nd = sVec.getNotationDataOccurences(); + nd = sVec.getNotationDataOccurrences(); if (nd.length != 3 || !nd[0].isHumanReadable() || nd[1].isHumanReadable() || nd[2].isHumanReadable()) { diff --git a/pkix/src/main/jdk1.3/org/bouncycastle/cert/jcajce/JcaX509ExtensionUtils.java b/pkix/src/main/jdk1.3/org/bouncycastle/cert/jcajce/JcaX509ExtensionUtils.java new file mode 100644 index 00000000..2878f44f --- /dev/null +++ b/pkix/src/main/jdk1.3/org/bouncycastle/cert/jcajce/JcaX509ExtensionUtils.java @@ -0,0 +1,138 @@ +package org.bouncycastle.cert.jcajce; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; + +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.cert.X509ExtensionUtils; +import org.bouncycastle.operator.DigestCalculator; + +public class JcaX509ExtensionUtils + extends X509ExtensionUtils +{ + /** + * Create a utility class pre-configured with a SHA-1 digest calculator based on the + * default implementation. + * + * @throws java.security.NoSuchAlgorithmException + */ + public JcaX509ExtensionUtils() + throws NoSuchAlgorithmException + { + super(new SHA1DigestCalculator(MessageDigest.getInstance("SHA1"))); + } + + public JcaX509ExtensionUtils(DigestCalculator calculator) + { + super(calculator); + } + + public AuthorityKeyIdentifier createAuthorityKeyIdentifier( + X509Certificate cert) + throws CertificateEncodingException + { + return super.createAuthorityKeyIdentifier(new JcaX509CertificateHolder(cert)); + } + + public AuthorityKeyIdentifier createAuthorityKeyIdentifier( + PublicKey pubKey) + { + return super.createAuthorityKeyIdentifier(SubjectPublicKeyInfo.getInstance(pubKey.getEncoded())); + } + + public AuthorityKeyIdentifier createAuthorityKeyIdentifier(PublicKey pubKey, GeneralNames generalNames, BigInteger serial) + { + return super.createAuthorityKeyIdentifier(SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()), generalNames, serial); + } + + /** + * Return a RFC 3280 type 1 key identifier. As in: + * <pre> + * (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the + * value of the BIT STRING subjectPublicKey (excluding the tag, + * length, and number of unused bits). + * </pre> + * @param publicKey the key object containing the key identifier is to be based on. + * @return the key identifier. + */ + public SubjectKeyIdentifier createSubjectKeyIdentifier( + PublicKey publicKey) + { + return super.createSubjectKeyIdentifier(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); + } + + /** + * Return a RFC 3280 type 2 key identifier. As in: + * <pre> + * (2) The keyIdentifier is composed of a four bit type field with + * the value 0100 followed by the least significant 60 bits of the + * SHA-1 hash of the value of the BIT STRING subjectPublicKey. + * </pre> + * @param publicKey the key object of interest. + * @return the key identifier. + */ + public SubjectKeyIdentifier createTruncatedSubjectKeyIdentifier(PublicKey publicKey) + { + return super.createSubjectKeyIdentifier(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); + } + + /** + * Return the ASN.1 object contained in a byte[] returned by a getExtensionValue() call. + * + * @param encExtValue DER encoded OCTET STRING containing the DER encoded extension object. + * @return an ASN.1 object + * @throws java.io.IOException on a parsing error. + */ + public static ASN1Primitive parseExtensionValue(byte[] encExtValue) + throws IOException + { + return ASN1Primitive.fromByteArray(ASN1OctetString.getInstance(encExtValue).getOctets()); + } + + private static class SHA1DigestCalculator + implements DigestCalculator + { + private ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + private MessageDigest digest; + + public SHA1DigestCalculator(MessageDigest digest) + { + this.digest = digest; + } + + public AlgorithmIdentifier getAlgorithmIdentifier() + { + return new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1); + } + + public OutputStream getOutputStream() + { + return bOut; + } + + public byte[] getDigest() + { + byte[] bytes = digest.digest(bOut.toByteArray()); + + bOut.reset(); + + return bytes; + } + } +} diff --git a/pkix/src/test/java/org/bouncycastle/cert/test/BcCertTest.java b/pkix/src/test/java/org/bouncycastle/cert/test/BcCertTest.java index a0eb89c7..fd551381 100644 --- a/pkix/src/test/java/org/bouncycastle/cert/test/BcCertTest.java +++ b/pkix/src/test/java/org/bouncycastle/cert/test/BcCertTest.java @@ -62,7 +62,6 @@ import org.bouncycastle.crypto.params.RSAKeyGenerationParameters; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory; -import org.bouncycastle.cert.test.PEMData; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.ContentVerifierProvider; import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; diff --git a/pkix/src/test/jdk1.3/org/bouncycastle/cert/path/test/CertPathTest.java b/pkix/src/test/jdk1.3/org/bouncycastle/cert/path/test/CertPathTest.java new file mode 100644 index 00000000..d487afb0 --- /dev/null +++ b/pkix/src/test/jdk1.3/org/bouncycastle/cert/path/test/CertPathTest.java @@ -0,0 +1,370 @@ +package org.bouncycastle.cert.path.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectOutputStream; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PublicKey; +import java.security.Security; +import java.security.SignatureException; +import org.bouncycastle.jce.cert.CertPath; +import org.bouncycastle.jce.cert.CertPathBuilder; +import org.bouncycastle.jce.cert.CertPathBuilderException; +import org.bouncycastle.jce.cert.CertPathBuilderResult; +import org.bouncycastle.jce.cert.CertStore; +import java.security.cert.Certificate; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateException; +import org.bouncycastle.jce.cert.CertificateFactory; +import org.bouncycastle.jce.cert.CollectionCertStoreParameters; +import org.bouncycastle.jce.cert.PKIXBuilderParameters; +import org.bouncycastle.jce.cert.TrustAnchor; +import org.bouncycastle.jce.cert.X509CertSelector; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.Vector; + +import org.bouncycastle.jce.X509Principal; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.encoders.Base64; +import org.bouncycastle.util.test.SimpleTest; + +public class CertPathTest + extends SimpleTest +{ + public static byte[] rootCertBin = Base64.decode( + "MIIBqzCCARQCAQEwDQYJKoZIhvcNAQEFBQAwHjEcMBoGA1UEAxMTVGVzdCBDQSBDZXJ0aWZpY2F0ZTAeFw0wODA5MDQwNDQ1MDhaFw0wODA5MTEwNDQ1MDhaMB4xHDAaBgNVBAMTE1Rlc3QgQ0EgQ2VydGlmaWNhdGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMRLUjhPe4YUdLo6EcjKcWUOG7CydFTH53Pr1lWjOkbmszYDpkhCTT9LOsI+disk18nkBxSl8DAHTqV+VxtuTPt64iyi10YxyDeep+DwZG/f8cVQv97U3hA9cLurZ2CofkMLGr6JpSGCMZ9FcstcTdHB4lbErIJ54YqfF4pNOs4/AgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAgyrTEFY7ALpeY59jL6xFOLpuPqoBOWrUWv6O+zy5BCU0qiX71r3BpigtxRj+DYcfLIM9FNERDoHu3TthD3nwYWUBtFX8N0QUJIdJabxqAMhLjSC744koiFpCYse5Ye3ZvEdFwDzgAQsJTp5eFGgTZPkPzcdhkFJ2p9+OWs+cb24="); + + + static byte[] interCertBin = Base64.decode( + "MIICSzCCAbSgAwIBAgIBATANBgkqhkiG9w0BAQUFADAeMRwwGgYDVQQDExNUZXN0IENBIENlcnRpZmljYXRlMB4XDTA4MDkwNDA0NDUwOFoXDTA4MDkxMTA0NDUwOFowKDEmMCQGA1UEAxMdVGVzdCBJbnRlcm1lZGlhdGUgQ2VydGlmaWNhdGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0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TFoSKkIDAeMRwwGgYDVQQDExNUZXN0IENBIENlcnRpZmljYXRlggEBMB0GA1UdDgQWBBSVkw+VpqBf3zsLc/9GdkK9TzHPwDAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIFoDANBgkqhkiG9w0BAQUFAAOBgQBLv/0bVDjzTs/y1vN3FUiZNknEbzupIZduTuXJjqv/vBX+LDPjUfu/+iOCXOSKoRn6nlOWhwB1z6taG2usQkFG8InMkRcPREi2uVgFdhJ/1C3dAWhsdlubjdL926bftXvxnx/koDzyrePW5U96RlOQM2qLvbaky2Giz6hrc3Wl+w=="); + public static byte[] rootCrlBin = Base64.decode( + "MIIBYjCBzAIBATANBgkqhkiG9w0BAQsFADAeMRwwGgYDVQQDExNUZXN0IENBIENlcnRpZmljYXRlFw0wODA5MDQwNDQ1MDhaFw0wODA5MDQwNzMxNDhaMCIwIAIBAhcNMDgwOTA0MDQ0NTA4WjAMMAoGA1UdFQQDCgEJoFYwVDBGBgNVHSMEPzA9gBSG/wE5PbsQH0loJxwkPhgBI8/ldaEipCAwHjEcMBoGA1UEAxMTVGVzdCBDQSBDZXJ0aWZpY2F0ZYIBATAKBgNVHRQEAwIBATANBgkqhkiG9w0BAQsFAAOBgQCAbaFCo0BNG4AktVf6jjBLeawP1u0ELYkOCEGvYZE0mBpQ+OvFg7subZ6r3lRIj030nUli28sPFtu5ZQMBNcpE4nS1ziF44RfT3Lp5UgHx9x17Krz781iEyV+7zU8YxYMY9wULD+DCuK294kGKIssVNbmTYXZatBNoXQN5CLIocA=="); + static byte[] interCrlBin = Base64.decode( + "MIIBbDCB1gIBATANBgkqhkiG9w0BAQsFADAoMSYwJAYDVQQDEx1UZXN0IEludGVybWVkaWF0ZSBDZXJ0aWZpY2F0ZRcNMDgwOTA0MDQ0NTA4WhcNMDgwOTA0MDczMTQ4WjAiMCACAQIXDTA4MDkwNDA0NDUwOFowDDAKBgNVHRUEAwoBCaBWMFQwRgYDVR0jBD8wPYAUv8jAAY6QfNpDI9l6DLv0LAzmhMWhIqQgMB4xHDAaBgNVBAMTE1Rlc3QgQ0EgQ2VydGlmaWNhdGWCAQEwCgYDVR0UBAMCAQEwDQYJKoZIhvcNAQELBQADgYEAEVCr5TKs5yguGgLH+dBzmSPoeSIWJFLsgWwJEit/iUDJH3dgYmaczOcGxIDtbYYHLWIHM+P2YRyQz3MEkCXEgm/cx4y7leAmux5l+xQWgmxFPz+197vaphPeCZo+B7V1CWtm518gcq4mrs9ovfgNqgyFj7KGjcBpWdJE32KMt50="); + + /* + * certpath with a circular reference + */ + static byte[] certA = Base64.decode( + "MIIC6jCCAlOgAwIBAgIBBTANBgkqhkiG9w0BAQUFADCBjTEPMA0GA1UEAxMGSW50" + + "ZXIzMQswCQYDVQQGEwJDSDEPMA0GA1UEBxMGWnVyaWNoMQswCQYDVQQIEwJaSDEX" + + "MBUGA1UEChMOUHJpdmFzcGhlcmUgQUcxEDAOBgNVBAsTB1Rlc3RpbmcxJDAiBgkq" + + "hkiG9w0BCQEWFWFybWluQHByaXZhc3BoZXJlLmNvbTAeFw0wNzA0MDIwODQ2NTda" + + "Fw0xNzAzMzAwODQ0MDBaMIGlMScwJQYDVQQDHh4AQQByAG0AaQBuACAASADkAGIA" + + "ZQByAGwAaQBuAGcxCzAJBgNVBAYTAkNIMQ8wDQYDVQQHEwZadXJpY2gxCzAJBgNV" + + "BAgTAlpIMRcwFQYDVQQKEw5Qcml2YXNwaGVyZSBBRzEQMA4GA1UECxMHVGVzdGlu" + + "ZzEkMCIGCSqGSIb3DQEJARYVYXJtaW5AcHJpdmFzcGhlcmUuY29tMIGfMA0GCSqG" + + "SIb3DQEBAQUAA4GNADCBiQKBgQCfHfyVs5dbxG35H/Thd29qR4NZU88taCu/OWA1" + + "GdACI02lXWYpmLWiDgnU0ULP+GG8OnVp1IES9fz2zcrXKQ19xZzsen/To3h5sNte" + + "cJpS00XMM24q/jDwy5NvkBP9YIfFKQ1E/0hFHXcqwlw+b/y/v6YGsZCU2h6QDz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3o8H4e7Z0PZwIDAQABoyMwITAPBgNVHRMBAf8E" + + "BTADAQH/MA4GA1UdDwEB/wQEAwIB9jANBgkqhkiG9w0BAQQFAAOBgQCtWdirSsmt" + + "+CBBCNn6ZnbU3QqQfiiQIomjenNEHESJgaS/+PvPE5i3xWFXsunTHLW321/Km16I" + + "7+ZvT8Su1cqHg79NAT8QB0yke1saKSy2C0Pic4HwrNqVBWFNSxMU0hQzpx/ZXDbZ" + + "DqIXAp5EfyRYBy2ul+jm6Rot6aFgzuopKg=="); + + static byte[] certC = Base64.decode( + "MIICtTCCAh6gAwIBAgIBAjANBgkqhkiG9w0BAQQFADCBjTEPMA0GA1UEAxMGSW50" + + "ZXIxMQswCQYDVQQGEwJDSDEPMA0GA1UEBxMGWnVyaWNoMQswCQYDVQQIEwJaSDEX" + + "MBUGA1UEChMOUHJpdmFzcGhlcmUgQUcxEDAOBgNVBAsTB1Rlc3RpbmcxJDAiBgkq" + + "hkiG9w0BCQEWFWFybWluQHByaXZhc3BoZXJlLmNvbTAeFw0wNzA0MDIwODQ0Mzla" + + "Fw0xNzAzMzAwODQ0MDBaMIGNMQ8wDQYDVQQDEwZJbnRlcjIxCzAJBgNVBAYTAkNI" + + "MQ8wDQYDVQQHEwZadXJpY2gxCzAJBgNVBAgTAlpIMRcwFQYDVQQKEw5Qcml2YXNw" + + "aGVyZSBBRzEQMA4GA1UECxMHVGVzdGluZzEkMCIGCSqGSIb3DQEJARYVYXJtaW5A" + + "cHJpdmFzcGhlcmUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD0rLr6" + + "f2/ONeJzTb0q9M/NNX+MnAFMSqiQGVBkT76u5nOH4KLkpHXkzI82JI7GuQMzoT3a" + + "+RP1hO6FneO92ms2soC6xiOFb4EC69Dfhh87Nww5O35JxVF0bzmbmIAWd6P/7zGh" + + "nd2S4tKkaZcubps+C0j9Fgi0hipVicAOUVVoDQIDAQABoyMwITAPBgNVHRMBAf8E" + + "BTADAQH/M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gQCgr9kUdWUT" + + "Lt9UcztSzR3pnHRsyvS0E/z850OKQKS5/VxLEalpFvhj+3EcZ7Y6mFxaaS2B7vXg" + + "2YWyqV1PRb6iF7/u9EXkpSTKGrJahwANirCa3V/HTUuPdCE2GITlnWI8h3eVA+xQ" + + "D4LF0PXHOkXbwmhXRSb10lW1bSGkUxE9jg=="); + + private void testExceptions() + throws Exception + { + byte[] enc = { (byte)0, (byte)2, (byte)3, (byte)4, (byte)5 }; + MyCertPath mc = new MyCertPath(enc); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + ByteArrayInputStream is; + byte[] arr; + + ObjectOutputStream oOut = new ObjectOutputStream(os); + oOut.writeObject(mc); + oOut.flush(); + oOut.close(); + + try + { + CertificateFactory cFac = CertificateFactory.getInstance("X.509", + "BC"); + arr = os.toByteArray(); + is = new ByteArrayInputStream(arr); + cFac.generateCertPath(is); + } + catch (CertificateException e) + { + // ignore okay + } + + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + List certCol = new ArrayList(); + + certCol.add(cf.generateCertificate(new ByteArrayInputStream(certA))); + certCol.add(cf.generateCertificate(new ByteArrayInputStream(certB))); + certCol.add(cf.generateCertificate(new ByteArrayInputStream(certC))); + certCol.add(cf.generateCertificate(new ByteArrayInputStream(certD))); + + CertPathBuilder pathBuilder = CertPathBuilder.getInstance("PKIX", "BC"); + X509CertSelector select = new X509CertSelector(); + select.setSubject(((X509Principal)((X509Certificate)certCol.get(0)).getSubjectDN()).getEncoded()); + + Set trustanchors = new HashSet(); + trustanchors.add(new TrustAnchor((X509Certificate)cf.generateCertificate(new ByteArrayInputStream(rootCertBin)), null)); + + CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certCol)); + + PKIXBuilderParameters params = new PKIXBuilderParameters(trustanchors, select); + params.addCertStore(certStore); + + try + { + CertPathBuilderResult result = pathBuilder.build(params); + CertPath path = result.getCertPath(); + fail("found cert path in circular set"); + } + catch (CertPathBuilderException e) + { + // expected + } + } + + public void performTest() + throws Exception + { + CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); + + X509Certificate rootCert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(rootCertBin)); + X509Certificate interCert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(interCertBin)); + X509Certificate finalCert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(finalCertBin)); + + //Testing CertPath generation from List + List list = new ArrayList(); + list.add(interCert); + CertPath certPath1 = cf.generateCertPath(list); + + //Testing CertPath encoding as PkiPath + byte[] encoded = certPath1.getEncoded("PkiPath"); + + //Testing CertPath generation from InputStream + ByteArrayInputStream inStream = new ByteArrayInputStream(encoded); + CertPath certPath2 = cf.generateCertPath(inStream, "PkiPath"); + + //Comparing both CertPathes + if (!certPath2.equals(certPath1)) + { + fail("CertPath differ after encoding and decoding."); + } + + encoded = certPath1.getEncoded("PKCS7"); + + //Testing CertPath generation from InputStream + inStream = new ByteArrayInputStream(encoded); + certPath2 = cf.generateCertPath(inStream, "PKCS7"); + + //Comparing both CertPathes + if (!certPath2.equals(certPath1)) + { + fail("CertPath differ after encoding and decoding."); + } + + encoded = certPath1.getEncoded("PEM"); + + //Testing CertPath generation from InputStream + inStream = new ByteArrayInputStream(encoded); + certPath2 = cf.generateCertPath(inStream, "PEM"); + + //Comparing both CertPathes + if (!certPath2.equals(certPath1)) + { + fail("CertPath differ after encoding and decoding."); + } + + // + // empty list test + // + list = new ArrayList(); + + CertPath certPath = CertificateFactory.getInstance("X.509","BC").generateCertPath(list); + if (certPath.getCertificates().size() != 0) + { + fail("list wrong size."); + } + + // + // exception tests + // + testExceptions(); + } + + public String getName() + { + return "CertPath"; + } + + public static void main( + String[] args) + { + Security.addProvider(new BouncyCastleProvider()); + + runTest(new CertPathTest()); + } + + private static class MyCertificate extends Certificate + { + private final byte[] encoding; + + public MyCertificate(String type, byte[] encoding) + { + super(type); + // don't copy to allow null parameter in test + this.encoding = encoding; + } + + public byte[] getEncoded() throws CertificateEncodingException + { + // do copy to force NPE in test + return (byte[])encoding.clone(); + } + + public void verify(PublicKey key) throws CertificateException, + NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException + { + } + + public void verify(PublicKey key, String sigProvider) + throws CertificateException, NoSuchAlgorithmException, + InvalidKeyException, NoSuchProviderException, + SignatureException + { + } + + public String toString() + { + return "[My test Certificate, type: " + getType() + "]"; + } + + public PublicKey getPublicKey() + { + return new PublicKey() + { + public String getAlgorithm() + { + return "TEST"; + } + + public byte[] getEncoded() + { + return new byte[] { (byte)1, (byte)2, (byte)3 }; + } + + public String getFormat() + { + return "TEST_FORMAT"; + } + }; + } + } + + private static class MyCertPath extends CertPath + { + private final Vector certificates; + + private final Vector encodingNames; + + private final byte[] encoding; + + public MyCertPath(byte[] encoding) + { + super("MyEncoding"); + this.encoding = encoding; + certificates = new Vector(); + certificates.add(new MyCertificate("MyEncoding", encoding)); + encodingNames = new Vector(); + encodingNames.add("MyEncoding"); + } + + public List getCertificates() + { + return Collections.unmodifiableList(certificates); + } + + public byte[] getEncoded() throws CertificateEncodingException + { + return (byte[])encoding.clone(); + } + + public byte[] getEncoded(String encoding) + throws CertificateEncodingException + { + if (getType().equals(encoding)) + { + return (byte[])this.encoding.clone(); + } + throw new CertificateEncodingException("Encoding not supported: " + + encoding); + } + + public Iterator getEncodings() + { + return Collections.unmodifiableCollection(encodingNames).iterator(); + } + } +} + diff --git a/pkix/src/test/jdk1.3/org/bouncycastle/cert/test/BcCertTest.java b/pkix/src/test/jdk1.3/org/bouncycastle/cert/test/BcCertTest.java new file mode 100644 index 00000000..e414c856 --- /dev/null +++ b/pkix/src/test/jdk1.3/org/bouncycastle/cert/test/BcCertTest.java @@ -0,0 +1,1418 @@ +package org.bouncycastle.cert.test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.math.BigInteger; +import java.security.SecureRandom; +import java.security.cert.CRL; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509CRL; +import java.security.cert.X509Certificate; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import junit.framework.TestCase; +import org.bouncycastle.asn1.ASN1EncodableVector; +import org.bouncycastle.asn1.ASN1Enumerated; +import org.bouncycastle.asn1.ASN1Object; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.DERBitString; +import org.bouncycastle.asn1.DERSequence; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x500.X500NameBuilder; +import org.bouncycastle.asn1.x500.style.RFC4519Style; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; +import org.bouncycastle.asn1.x509.CRLReason; +import org.bouncycastle.asn1.x509.Certificate; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.Extensions; +import org.bouncycastle.asn1.x509.ExtensionsGenerator; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.cert.CertException; +import org.bouncycastle.cert.X509CRLEntryHolder; +import org.bouncycastle.cert.X509CRLHolder; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.X509v1CertificateBuilder; +import org.bouncycastle.cert.X509v2CRLBuilder; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.bc.BcX509ExtensionUtils; +import org.bouncycastle.cert.bc.BcX509v1CertificateBuilder; +import org.bouncycastle.cert.bc.BcX509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; +import org.bouncycastle.crypto.generators.DSAKeyPairGenerator; +import org.bouncycastle.crypto.generators.DSAParametersGenerator; +import org.bouncycastle.crypto.generators.RSAKeyPairGenerator; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.crypto.params.DSAKeyGenerationParameters; +import org.bouncycastle.crypto.params.DSAParameters; +import org.bouncycastle.crypto.params.RSAKeyGenerationParameters; +import org.bouncycastle.crypto.params.RSAKeyParameters; +import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; +import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory; +import org.bouncycastle.cert.test.PEMData; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.ContentVerifierProvider; +import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; +import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.bc.BcDSAContentSignerBuilder; +import org.bouncycastle.operator.bc.BcDSAContentVerifierProviderBuilder; +import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder; +import org.bouncycastle.operator.bc.BcRSAContentVerifierProviderBuilder; +import org.bouncycastle.util.encoders.Base64; + +public class BcCertTest + extends TestCase +{ + DefaultSignatureAlgorithmIdentifierFinder sigAlgFinder = new DefaultSignatureAlgorithmIdentifierFinder(); + DefaultDigestAlgorithmIdentifierFinder digAlgFinder = new DefaultDigestAlgorithmIdentifierFinder(); + + // + // server.crt + // + byte[] cert1 = Base64.decode( + "MIIDXjCCAsegAwIBAgIBBzANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx" + + "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY" + + "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB" + + "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCS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2861iXZfWqGQjrGAaA0ZpXNk9oo110yxoqEoSJSzniZa7Xtz" + + "soTwNUpE0SLHvWf/SlKdFWlzXA+vOZbzEv4UmjeelekTm7lc01EEa5QRVzOxHFtQ" + + "DhkaJ8VqOMajkQFma2r9iA=="); + + // + // testx509.pem + // + byte[] cert3 = Base64.decode( + "MIIBWzCCAQYCARgwDQYJKoZIhvcNAQEEBQAwODELMAkGA1UEBhMCQVUxDDAKBgNV" + + "BAgTA1FMRDEbMBkGA1UEAxMSU1NMZWF5L3JzYSB0ZXN0IENBMB4XDTk1MDYxOTIz" + + "MzMxMloXDTk1MDcxNzIzMzMxMlowOjELMAkGA1UEBhMCQVUxDDAKBgNVBAgTA1FM" + + "RDEdMBsGA1UEAxMUU1NMZWF5L3JzYSB0ZXN0IGNlcnQwXDANBgkqhkiG9w0BAQEF" + + "AANLADBIAkEAqtt6qS5GTxVxGZYWa0/4u+IwHf7p2LNZbcPBp9/OfIcYAXBQn8hO" + + "/Re1uwLKXdCjIoaGs4DLdG88rkzfyK5dPQIDAQABMAwGCCqGSIb3DQIFBQADQQAE" + + "Wc7EcF8po2/ZO6kNCwK/ICH6DobgLekA5lSLr5EvuioZniZp5lFzAw4+YzPQ7XKJ" + + "zl9HYIMxATFyqSiD9jsx"); + + // + // v3-cert1.pem + // + byte[] cert4 = Base64.decode( + "MIICjTCCAfigAwIBAgIEMaYgRzALBgkqhkiG9w0BAQQwRTELMAkGA1UEBhMCVVMx" + + "NjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFuZCBTcGFjZSBBZG1pbmlz" + + "dHJhdGlvbjAmFxE5NjA1MjgxMzQ5MDUrMDgwMBcROTgwNTI4MTM0OTA1KzA4MDAw" + + "ZzELMAkGA1UEBhMCVVMxNjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFu" + + "ZCBTcGFjZSBBZG1pbmlzdHJhdGlvbjEgMAkGA1UEBRMCMTYwEwYDVQQDEwxTdGV2" + + "ZSBTY2hvY2gwWDALBgkqhkiG9w0BAQEDSQAwRgJBALrAwyYdgxmzNP/ts0Uyf6Bp" + + "miJYktU/w4NG67ULaN4B5CnEz7k57s9o3YY3LecETgQ5iQHmkwlYDTL2fTgVfw0C" + + "AQOjgaswgagwZAYDVR0ZAQH/BFowWDBWMFQxCzAJBgNVBAYTAlVTMTYwNAYDVQQK" + + "Ey1OYXRpb25hbCBBZXJvbmF1dGljcyBhbmQgU3BhY2UgQWRtaW5pc3RyYXRpb24x" + + "DTALBgNVBAMTBENSTDEwFwYDVR0BAQH/BA0wC4AJODMyOTcwODEwMBgGA1UdAgQR" + + "MA8ECTgzMjk3MDgyM4ACBSAwDQYDVR0KBAYwBAMCBkAwCwYJKoZIhvcNAQEEA4GB" + + "AH2y1VCEw/A4zaXzSYZJTTUi3uawbbFiS2yxHvgf28+8Js0OHXk1H1w2d6qOHH21" + + "X82tZXd/0JtG0g1T9usFFBDvYK8O0ebgz/P5ELJnBL2+atObEuJy1ZZ0pBDWINR3" + + "WkDNLCGiTkCKp0F5EWIrVDwh54NNevkCQRZita+z4IBO"); + + // + // v3-cert2.pem + // + byte[] cert5 = Base64.decode( + "MIICiTCCAfKgAwIBAgIEMeZfHzANBgkqhkiG9w0BAQQFADB9MQswCQYDVQQGEwJD" + + "YTEPMA0GA1UEBxMGTmVwZWFuMR4wHAYDVQQLExVObyBMaWFiaWxpdHkgQWNjZXB0" + + "ZWQxHzAdBgNVBAoTFkZvciBEZW1vIFB1cnBvc2VzIE9ubHkxHDAaBgNVBAMTE0Vu" + + "dHJ1c3QgRGVtbyBXZWIgQ0EwHhcNOTYwNzEyMTQyMDE1WhcNOTYxMDEyMTQyMDE1" + + "WjB0MSQwIgYJKoZIhvcNAQkBExVjb29rZUBpc3NsLmF0bC5ocC5jb20xCzAJBgNV" + + "BAYTAlVTMScwJQYDVQQLEx5IZXdsZXR0IFBhY2thcmQgQ29tcGFueSAoSVNTTCkx" + + "FjAUBgNVBAMTDVBhdWwgQS4gQ29va2UwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA" + + "6ceSq9a9AU6g+zBwaL/yVmW1/9EE8s5you1mgjHnj0wAILuoB3L6rm6jmFRy7QZT" + + "G43IhVZdDua4e+5/n1ZslwIDAQABo2MwYTARBglghkgBhvhCAQEEBAMCB4AwTAYJ" + + "YIZIAYb4QgENBD8WPVRoaXMgY2VydGlmaWNhdGUgaXMgb25seSBpbnRlbmRlZCBm" + + "b3IgZGVtb25zdHJhdGlvbiBwdXJwb3Nlcy4wDQYJKoZIhvcNAQEEBQADgYEAi8qc" + + "F3zfFqy1sV8NhjwLVwOKuSfhR/Z8mbIEUeSTlnH3QbYt3HWZQ+vXI8mvtZoBc2Fz" + + "lexKeIkAZXCesqGbs6z6nCt16P6tmdfbZF3I3AWzLquPcOXjPf4HgstkyvVBn0Ap" + + "jAFN418KF/Cx4qyHB4cjdvLrRjjQLnb2+ibo7QU="); + + // + // pem encoded pkcs7 + // + byte[] cert6 = Base64.decode( + "MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIJbzCCAj0w" + + "ggGmAhEAzbp/VvDf5LxU/iKss3KqVTANBgkqhkiG9w0BAQIFADBfMQswCQYDVQQGEwJVUzEXMBUG" + + "A1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGljIFByaW1hcnkgQ2Vy" + + "dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTYwMTI5MDAwMDAwWhcNMjgwODAxMjM1OTU5WjBfMQsw" + + "CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVi" + + "bGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwgZ8wDQYJKoZIhvcNAQEBBQADgY0A" + + "MIGJAoGBAOUZv22jVmEtmUhx9mfeuY3rt56GgAqRDvo4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FN1YnNjcmliZXItUGVyc29uYSBOb3Qg" + + "VmFsaWRhdGVkAhAW25/9Rtc6aQ+irD9NW8MsMAkGBSsOAwIaBQCggbowGAYJKoZIhvcNAQkDMQsG" + + "CSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMDAxMDAyMTczNTE4WjAjBgkqhkiG9w0BCQQxFgQU" + + "gZjSaBEY2oxGvlQUIMnxSXhivK8wWwYJKoZIhvcNAQkPMU4wTDAKBggqhkiG9w0DBzAOBggqhkiG" + + "9w0DAgICAIAwDQYIKoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwBwYFKw4DAh0w" + + "DQYJKoZIhvcNAQEBBQAEgYAzk+PU91/ZFfoiuKOECjxEh9fDYE2jfDCheBIgh5gdcCo+sS1WQs8O" + + "HreQ9Nop/JdJv1DQMBK6weNBBDoP0EEkRm1XCC144XhXZC82jBZohYmi2WvDbbC//YN58kRMYMyy" + + "srrfn4Z9I+6kTriGXkrpGk9Q0LSGjmG2BIsqiF0dvwAAAAAAAA=="); + + // + // dsaWithSHA1 cert + // + byte[] cert7 = Base64.decode( + "MIIEXAYJKoZIhvcNAQcCoIIETTCCBEkCAQExCzAJBgUrDgMCGgUAMAsGCSqG" + + "SIb3DQEHAaCCAsMwggK/MIIB4AIBADCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7" + + "d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULjw3GobwaJX13kquPh" + + "fVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABj" + + "TUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/z" + + "m8Q12PFp/PjOhh+nMA4xDDAKBgNVBAMTA0lEMzAeFw05NzEwMDEwMDAwMDBa" + + "Fw0zODAxMDEwMDAwMDBaMA4xDDAKBgNVBAMTA0lEMzCB8DCBpwYFKw4DAhsw" + + "gZ0CQQ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p/PjOhh+nBC8wLQIVALID" + + "dt+MHwawrDrwsO1Z6sXBaaJsAhRaKssrpevmLkbygKPV07XiAKBG02Zvb2Jh" + + "cg=="); + + // + // testcrl.pem + // + byte[] crl1 = Base64.decode( + "MIICjTCCAfowDQYJKoZIhvcNAQECBQAwXzELMAkGA1UEBhMCVVMxIDAeBgNVBAoT" + + "F1JTQSBEYXRhIFNlY3VyaXR5LCBJbmMuMS4wLAYDVQQLEyVTZWN1cmUgU2VydmVy" + + "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5Fw05NTA1MDIwMjEyMjZaFw05NTA2MDEw" + + "MDAxNDlaMIIBaDAWAgUCQQAABBcNOTUwMjAxMTcyNDI2WjAWAgUCQQAACRcNOTUw" + + "MjEwMDIxNjM5WjAWAgUCQQAADxcNOTUwMjI0MDAxMjQ5WjAWAgUCQQAADBcNOTUw" + + "MjI1MDA0NjQ0WjAWAgUCQQAAGxcNOTUwMzEzMTg0MDQ5WjAWAgUCQQAAFhcNOTUw" + + "MzE1MTkxNjU0WjAWAgUCQQAAGhcNOTUwMzE1MTk0MDQxWjAWAgUCQQAAHxcNOTUw" + + "MzI0MTk0NDMzWjAWAgUCcgAABRcNOTUwMzI5MjAwNzExWjAWAgUCcgAAERcNOTUw" + + "MzMwMDIzNDI2WjAWAgUCQQAAIBcNOTUwNDA3MDExMzIxWjAWAgUCcgAAHhcNOTUw" + + "NDA4MDAwMjU5WjAWAgUCcgAAQRcNOTUwNDI4MTcxNzI0WjAWAgUCcgAAOBcNOTUw" + + "NDI4MTcyNzIxWjAWAgUCcgAATBcNOTUwNTAyMDIxMjI2WjANBgkqhkiG9w0BAQIF" + + "AAN+AHqOEJXSDejYy0UwxxrH/9+N2z5xu/if0J6qQmK92W0hW158wpJg+ovV3+wQ" + + "wvIEPRL2rocL0tKfAsVq1IawSJzSNgxG0lrcla3MrJBnZ4GaZDu4FutZh72MR3Gt" + + "JaAL3iTJHJD55kK2D/VoyY1djlsPuNh6AEgdVwFAyp0v"); + + // + // ecdsa cert with extra octet string. + // + byte[] oldEcdsa = Base64.decode( + "MIICljCCAkCgAwIBAgIBATALBgcqhkjOPQQBBQAwgY8xCzAJBgNVBAYTAkFVMSgwJ" + + "gYDVQQKEx9UaGUgTGVnaW9uIG9mIHRoZSBCb3VuY3kgQ2FzdGxlMRIwEAYDVQQHEw" + + "lNZWxib3VybmUxETAPBgNVBAgTCFZpY3RvcmlhMS8wLQYJKoZIhvcNAQkBFiBmZWV" + + "kYmFjay1jcnlwdG9AYm91bmN5Y2FzdGxlLm9yZzAeFw0wMTEyMDcwMTAwMDRaFw0w" + + "MTEyMDcwMTAxNDRaMIGPMQswCQYDVQQGEwJBVTEoMCYGA1UEChMfVGhlIExlZ2lvb" + + "iBvZiB0aGUgQm91bmN5IENhc3RsZTESMBAGA1UEBxMJTWVsYm91cm5lMREwDwYDVQ" + + "QIEwhWaWN0b3JpYTEvMC0GCSqGSIb3DQEJARYgZmVlZGJhY2stY3J5cHRvQGJvdW5" + + "jeWNhc3RsZS5vcmcwgeQwgb0GByqGSM49AgEwgbECAQEwKQYHKoZIzj0BAQIef///" + + "////////////f///////gAAAAAAAf///////MEAEHn///////////////3///////" + + "4AAAAAAAH///////AQeawFsO9zxiUHQ1lSSFHXKcanbL7J9HTd5YYXClCwKBB8CD/" + + "qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqvAh5///////////////9///+eXpq" + + "fXZBx+9FSJoiQnQsDIgAEHwJbbcU7xholSP+w9nFHLebJUhqdLSU05lq/y9X+DHAw" + + "CwYHKoZIzj0EAQUAA0MAMEACHnz6t4UNoVROp74ma4XNDjjGcjaqiIWPZLK8Bdw3G" + + "QIeLZ4j3a6ividZl344UH+UPUE7xJxlYGuy7ejTsqRR"); + + byte[] keyUsage = Base64.decode( + "MIIE7TCCBFagAwIBAgIEOAOR7jANBgkqhkiG9w0BAQQFADCByTELMAkGA1UE" + + "BhMCVVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MUgwRgY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iVi4DjbxX46TdcTbTaK8/qr6AIf+l"); + + byte[] probSelfSignedCert = Base64.decode( + "MIICxTCCAi6gAwIBAgIQAQAAAAAAAAAAAAAAAAAAATANBgkqhkiG9w0BAQUFADBF" + + "MScwJQYDVQQKEx4gRElSRUNUSU9OIEdFTkVSQUxFIERFUyBJTVBPVFMxGjAYBgNV" + + "BAMTESBBQyBNSU5FRkkgQiBURVNUMB4XDTA0MDUwNzEyMDAwMFoXDTE0MDUwNzEy" + + "MDAwMFowRTEnMCUGA1UEChMeIERJUkVDVElPTiBHRU5FUkFMRSBERVMgSU1QT1RT" + + "MRowGAYDVQQDExEgQUMgTUlORUZJIEIgVEVTVDCBnzANBgkqhkiG9w0BAQEFAAOB" + + "jQAwgYkCgYEAveoCUOAukZdcFCs2qJk76vSqEX0ZFzHqQ6faBPZWjwkgUNwZ6m6m" + + "qWvvyq1cuxhoDvpfC6NXILETawYc6MNwwxsOtVVIjuXlcF17NMejljJafbPximEt" + + "DQ4LcQeSp4K7FyFlIAMLyt3BQ77emGzU5fjFTvHSUNb3jblx0sV28c0CAwEAAaOB" + + "tTCBsjAfBgNVHSMEGDAWgBSEJ4bLbvEQY8cYMAFKPFD1/fFXlzAdBgNVHQ4EFgQU" + + "hCeGy27xEGPHGDABSjxQ9f3xV5cwDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIB" + + "AQQEAwIBBjA8BgNVHR8ENTAzMDGgL6AthitodHRwOi8vYWRvbmlzLnBrNy5jZXJ0" + + "cGx1cy5uZXQvZGdpLXRlc3QuY3JsMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN" + + "AQEFBQADgYEAmToHJWjd3+4zknfsP09H6uMbolHNGG0zTS2lrLKpzcmkQfjhQpT9" + + "LUTBvfs1jdjo9fGmQLvOG+Sm51Rbjglb8bcikVI5gLbclOlvqLkm77otjl4U4Z2/" + + "Y0vP14Aov3Sn3k+17EfReYUZI4liuB95ncobC4e8ZM++LjQcIM0s+Vs="); + + + byte[] gost34102001base = Base64.decode( + "MIIB1DCCAYECEEjpVKXP6Wn1yVz3VeeDQa8wCgYGKoUDAgIDBQAwbTEfMB0G" + + "A1UEAwwWR29zdFIzNDEwLTIwMDEgZXhhbXBsZTESMBAGA1UECgwJQ3J5cHRv" + + "UHJvMQswCQYDVQQGEwJSVTEpMCcGCSqGSIb3DQEJARYaR29zdFIzNDEwLTIw" + + "MDFAZXhhbXBsZS5jb20wHhcNMDUwMjAzMTUxNjQ2WhcNMTUwMjAzMTUxNjQ2" + + "WjBtMR8wHQYDVQQDDBZHb3N0UjM0MTAtMjAwMSBleGFtcGxlMRIwEAYDVQQK" + + "DAlDcnlwdG9Qcm8xCzAJBgNVBAYTAlJVMSkwJwYJKoZIhvcNAQkBFhpHb3N0" + + "UjM0MTAtMjAwMUBleGFtcGxlLmNvbTBjMBwGBiqFAwICEzASBgcqhQMCAiQA" + + "BgcqhQMCAh4BA0MABECElWh1YAIaQHUIzROMMYks/eUFA3pDXPRtKw/nTzJ+" + + "V4/rzBa5lYgD0Jp8ha4P5I3qprt+VsfLsN8PZrzK6hpgMAoGBiqFAwICAwUA" + + "A0EAHw5dw/aw/OiNvHyOE65kvyo4Hp0sfz3csM6UUkp10VO247ofNJK3tsLb" + + "HOLjUaqzefrlGb11WpHYrvWFg+FcLA=="); + + private final byte[] emptyDNCert = Base64.decode( + "MIICfTCCAeagAwIBAgIBajANBgkqhkiG9w0BAQQFADB8MQswCQYDVQQGEwJVUzEMMAoGA1UEChMD" + + "Q0RXMQkwBwYDVQQLEwAxCTAHBgNVBAcTADEJMAcGA1UECBMAMRowGAYDVQQDExFUZW1wbGFyIFRl" + + "c3QgMTAyNDEiMCAGCSqGSIb3DQEJARYTdGVtcGxhcnRlc3RAY2R3LmNvbTAeFw0wNjA1MjIwNTAw" + + "MDBaFw0xMDA1MjIwNTAwMDBaMHwxCzAJBgNVBAYTAlVTMQwwCgYDVQQKEwNDRFcxCTAHBgNVBAsT" + + "ADEJMAcGA1UEBxMAMQkwBwYDVQQIEwAxGjAYBgNVBAMTEVRlbXBsYXIgVGVzdCAxMDI0MSIwIAYJ" + + "KoZIhvcNAQkBFhN0ZW1wbGFydGVzdEBjZHcuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB" + + "gQDH3aJpJBfM+A3d84j5YcU6zEQaQ76u5xO9NSBmHjZykKS2kCcUqPpvVOPDA5WgV22dtKPh+lYV" + + "iUp7wyCVwAKibq8HIbihHceFqMKzjwC639rMoDJ7bi/yzQWz1Zg+075a4FGPlUKn7Yfu89wKkjdW" + + "wDpRPXc/agqBnrx5pJTXzQIDAQABow8wDTALBgNVHQ8EBAMCALEwDQYJKoZIhvcNAQEEBQADgYEA" + + "RRsRsjse3i2/KClFVd6YLZ+7K1BE0WxFyY2bbytkwQJSxvv3vLSuweFUbhNxutb68wl/yW4GLy4b" + + "1QdyswNxrNDXTuu5ILKhRDDuWeocz83aG2KGtr3JlFyr3biWGEyn5WUOE6tbONoQDJ0oPYgI6CAc" + + "EHdUp0lioOCt6UOw7Cs="); + + private AsymmetricKeyParameter dudPublicKey = new AsymmetricKeyParameter(true) + { + public String getAlgorithm() + { + return null; + } + + public String getFormat() + { + return null; + } + + public byte[] getEncoded() + { + return null; + } + + }; + + public String getName() + { + return "CertTest"; + } + + public void checkCertificate( + int id, + byte[] bytes) + { + try + { + X509CertificateHolder certHldr = new X509CertificateHolder(bytes); + + SubjectPublicKeyInfo k = certHldr.getSubjectPublicKeyInfo(); + // System.out.println(cert); + } + catch (Exception e) + { + fail(e.toString()); + } + } + /* + public void checkNameCertificate( + int id, + byte[] bytes) + { + ByteArrayInputStream bIn; + String dump = ""; + + try + { + bIn = new ByteArrayInputStream(bytes); + + CertificateFactory fact = CertificateFactory.getInstance("X.509", "LKBX-BC"); + + X509Certificate cert = (X509Certificate)fact.generateCertificate(bIn); + + AsymmetricKeyParameter k = cert.getAsymmetricKeyParameter(); + if (!cert.getIssuerDN().toString().equals("C=DE,O=DATEV eG,0.2.262.1.10.7.20=1+CN=CA DATEV D03 1:PN")) + { + fail(id + " failed - name test."); + } + // System.out.println(cert); + } + catch (Exception e) + { + fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); + } + + } + */ + public void checkKeyUsage( + int id, + byte[] bytes) + throws IOException + { + + X509CertificateHolder certHld = new X509CertificateHolder(bytes); + + if ((DERBitString.getInstance(certHld.getExtension(Extension.keyUsage).getParsedValue()).getBytes()[0] & 0x01) != 0) + { + fail("error generating cert - key usage wrong."); + } + + + } + + + public void checkSelfSignedCertificate( + int id, + byte[] bytes) + throws OperatorCreationException, IOException, CertException + { + + X509CertificateHolder certHolder = new X509CertificateHolder(bytes); + + assertTrue(certHolder.isSignatureValid(new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(certHolder))); + + + } + + /** + * we generate a self signed certificate for the sake of testing - RSA + */ + public void checkCreation1() + throws Exception + { + // + // a sample key pair. + // + AsymmetricKeyParameter pubKey = new RSAKeyParameters( + false, + new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), + new BigInteger("11", 16)); + + AsymmetricKeyParameter privKey = new RSAPrivateCrtKeyParameters( + new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), + new BigInteger("11", 16), + new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), + new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), + new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), + new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), + new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), + new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); + + // + // distinguished name table. + // + X500NameBuilder builder = new X500NameBuilder(RFC4519Style.INSTANCE); + + builder.addRDN(RFC4519Style.c, "AU"); + builder.addRDN(RFC4519Style.o, "The Legion of the Bouncy Castle"); + builder.addRDN(RFC4519Style.l, "Melbourne"); + builder.addRDN(RFC4519Style.st, "Victoria"); + builder.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "feedback-crypto@bouncycastle.org"); + + // + // extensions + // + + // + // create the certificate - version 3 - without extensions + // + AlgorithmIdentifier sigAlg = sigAlgFinder.find("SHA256WithRSAEncryption"); + ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlg, digAlgFinder.find(sigAlg)).build(privKey); + X509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000),builder.build(), pubKey); + + X509CertificateHolder certH = certGen.build(sigGen); + + assertTrue(certH.isValidOn(new Date())); + + ContentVerifierProvider contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(new DefaultDigestAlgorithmIdentifierFinder()).build(pubKey); + + assertTrue(certH.isSignatureValid(contentVerifierProvider)); + + X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certH); + Set dummySet = cert.getNonCriticalExtensionOIDs(); + if (dummySet != null) + { + fail("non-critical oid set should be null"); + } + dummySet = cert.getCriticalExtensionOIDs(); + if (dummySet != null) + { + fail("critical oid set should be null"); + } + + // + // create the certificate - version 3 - with extensions + // + sigGen = new BcRSAContentSignerBuilder(sigAlgFinder.find("MD5WithRSA"), digAlgFinder.find(sigAlgFinder.find("MD5withRSA"))).build(privKey); + certGen = new BcX509v3CertificateBuilder(builder.build(), BigInteger.valueOf(1) + , new Date(System.currentTimeMillis() - 50000) + , new Date(System.currentTimeMillis() + 50000) + , builder.build() + , pubKey) + .addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, + new KeyUsage(KeyUsage.encipherOnly)) + .addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true, + new DERSequence(KeyPurposeId.anyExtendedKeyUsage)) + .addExtension(new ASN1ObjectIdentifier("2.5.29.17"), true, + new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); + + X509CertificateHolder certHolder = certGen.build(sigGen); + + assertTrue(certHolder.isValidOn(new Date())); + + contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey); + if (!certHolder.isSignatureValid(contentVerifierProvider)) + { + fail("signature test failed"); + } + + ByteArrayInputStream bIn = new ByteArrayInputStream(certHolder.getEncoded()); + CertificateFactory certFact = CertificateFactory.getInstance("X.509"); + + cert = (X509Certificate)certFact.generateCertificate(bIn); + + if (!cert.getKeyUsage()[7]) + { + fail("error generating cert - key usage wrong."); + } + + // System.out.println(cert); + + // + // create the certificate - version 1 + // + sigGen = new BcRSAContentSignerBuilder(sigAlgFinder.find("MD5WithRSA"), digAlgFinder.find(sigAlgFinder.find("MD5withRSA"))).build(privKey); + X509v1CertificateBuilder certGen1 = new BcX509v1CertificateBuilder(builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey); + + cert = new JcaX509CertificateConverter().getCertificate(certGen1.build(sigGen)); + + assertTrue(certHolder.isValidOn(new Date())); + + contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(new DefaultDigestAlgorithmIdentifierFinder()).build(pubKey); + + assertTrue(certHolder.isSignatureValid(contentVerifierProvider)); + + bIn = new ByteArrayInputStream(cert.getEncoded()); + certFact = CertificateFactory.getInstance("X.509"); + + cert = (X509Certificate)certFact.generateCertificate(bIn); + + // System.out.println(cert); + if (!cert.getIssuerDN().equals(cert.getSubjectDN())) + { + fail("name comparison fails"); + } + +// + // a lightweight key pair. + // + RSAKeyParameters lwPubKey = new RSAKeyParameters( + false, + new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), + new BigInteger("11", 16)); + + RSAPrivateCrtKeyParameters lwPrivKey = new RSAPrivateCrtKeyParameters( + new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), + new BigInteger("11", 16), + new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), + new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), + new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), + new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), + new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), + new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); + + // + // distinguished name table. + // + builder = new X500NameBuilder(RFC4519Style.INSTANCE); + + builder.addRDN(RFC4519Style.c, "AU"); + builder.addRDN(RFC4519Style.o, "The Legion of the Bouncy Castle"); + builder.addRDN(RFC4519Style.l, "Melbourne"); + builder.addRDN(RFC4519Style.st, "Victoria"); + builder.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "feedback-crypto@bouncycastle.org"); + + // + // extensions + // + + // + // create the certificate - version 3 - without extensions + // + AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WithRSAEncryption"); + AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); + + sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(lwPrivKey); + SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(lwPubKey); + certGen = new X509v3CertificateBuilder(builder.build(), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000), builder.build(), pubInfo); + + certHolder = certGen.build(sigGen); + + assertTrue(certHolder.isValidOn(new Date())); + + contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(new DefaultDigestAlgorithmIdentifierFinder()).build(lwPubKey); + + assertTrue(certHolder.isSignatureValid(contentVerifierProvider)); + + if (!certHolder.isSignatureValid(contentVerifierProvider)) + { + fail("lw sig verification failed"); + } + } + + /** + * we generate a self signed certificate for the sake of testing - DSA + */ + public void checkCreation2() + throws Exception + { + // + // set up the keys + // + AsymmetricKeyParameter privKey; + AsymmetricKeyParameter pubKey; + + AsymmetricCipherKeyPairGenerator kpg = new DSAKeyPairGenerator(); + BigInteger r = new BigInteger("68076202252361894315274692543577577550894681403"); + BigInteger s = new BigInteger("1089214853334067536215539335472893651470583479365"); + DSAParametersGenerator pGen = new DSAParametersGenerator(); + + pGen.init(512, 80, new SecureRandom()); + + DSAParameters params = pGen.generateParameters(); + DSAKeyGenerationParameters genParam = new DSAKeyGenerationParameters(new SecureRandom(), params); + + kpg.init(genParam); + + AsymmetricCipherKeyPair pair = kpg.generateKeyPair(); + + privKey = (AsymmetricKeyParameter)pair.getPrivate(); + pubKey = (AsymmetricKeyParameter)pair.getPublic(); + + // + // distinguished name table. + // + X500NameBuilder builder = createStdBuilder(); + + // + // extensions + // + + // + // create the certificate - version 3 + // + AlgorithmIdentifier sigAlgId = sigAlgFinder.find("SHA1withDSA"); + AlgorithmIdentifier digAlgId = digAlgFinder.find(sigAlgId); + + ContentSigner sigGen = new BcDSAContentSignerBuilder(sigAlgId, digAlgId).build(privKey); + X509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(builder.build(),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey); + + + X509CertificateHolder cert = certGen.build(sigGen); + + assertTrue(cert.isValidOn(new Date())); + + assertTrue(cert.isSignatureValid(new BcDSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); + + + // + // create the certificate - version 1 + // + sigAlgId = sigAlgFinder.find("SHA1withDSA"); + digAlgId = digAlgFinder.find(sigAlgId); + + sigGen = new BcDSAContentSignerBuilder(sigAlgId, digAlgId).build(privKey); + X509v1CertificateBuilder certGen1 = new BcX509v1CertificateBuilder(builder.build(),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey); + + cert = certGen1.build(sigGen); + + assertTrue(cert.isValidOn(new Date())); + + assertTrue(cert.isSignatureValid(new BcDSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); + + ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); + CertificateFactory fact = CertificateFactory.getInstance("X.509"); + + X509Certificate x509cert = (X509Certificate)fact.generateCertificate(bIn); + + //System.out.println(cert); + } + + private X500NameBuilder createStdBuilder() + { + X500NameBuilder builder = new X500NameBuilder(RFC4519Style.INSTANCE); + + builder.addRDN(RFC4519Style.c, "AU"); + builder.addRDN(RFC4519Style.o, "The Legion of the Bouncy Castle"); + builder.addRDN(RFC4519Style.l, "Melbourne"); + builder.addRDN(RFC4519Style.st, "Victoria"); + builder.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "feedback-crypto@bouncycastle.org"); + + return builder; + } + + private void checkCRL( + int id, + byte[] bytes) + { + String dump = ""; + + try + { + X509CRLHolder crlHolder = new X509CRLHolder(bytes); + + } + catch (Exception e) + { + fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString()); + } + + } + + public void checkCRLCreation1() + throws Exception + { + AsymmetricCipherKeyPairGenerator kpg = new RSAKeyPairGenerator(); + RSAKeyGenerationParameters genParam = new RSAKeyGenerationParameters( + BigInteger.valueOf(0x1001), new SecureRandom(), 1024, 25); + + kpg.init(genParam); + + AsymmetricCipherKeyPair pair = kpg.generateKeyPair(); + Date now = new Date(); + + X509v2CRLBuilder crlGen = new X509v2CRLBuilder(new X500Name("CN=Test CA"), now); + + BcX509ExtensionUtils extFact = new BcX509ExtensionUtils(new SHA1DigestCalculator()); + + crlGen.setNextUpdate(new Date(now.getTime() + 100000)); + + crlGen.addCRLEntry(BigInteger.ONE, now, CRLReason.privilegeWithdrawn); + + crlGen.addExtension(Extension.authorityKeyIdentifier, false, extFact.createAuthorityKeyIdentifier(pair.getPublic())); + + AlgorithmIdentifier sigAlg = sigAlgFinder.find("SHA256withRSAEncryption"); + AlgorithmIdentifier digAlg = digAlgFinder.find(sigAlg); + + X509CRLHolder crl = crlGen.build(new BcRSAContentSignerBuilder(sigAlg, digAlg).build(pair.getPrivate())); + + if (!crl.getIssuer().equals(new X500Name("CN=Test CA"))) + { + fail("failed CRL issuer test"); + } + + Extension authExt = crl.getExtension(Extension.authorityKeyIdentifier); + + if (authExt == null) + { + fail("failed to find CRL extension"); + } + + AuthorityKeyIdentifier authId = AuthorityKeyIdentifier.getInstance(authExt.getParsedValue()); + + X509CRLEntryHolder entry = crl.getRevokedCertificate(BigInteger.ONE); + + if (entry == null) + { + fail("failed to find CRL entry"); + } + + if (!entry.getSerialNumber().equals(BigInteger.ONE)) + { + fail("CRL cert serial number does not match"); + } + + if (!entry.hasExtensions()) + { + fail("CRL entry extension not found"); + } + + Extension ext = entry.getExtension(Extension.reasonCode); + + if (ext != null) + { + ASN1Enumerated reasonCode = ASN1Enumerated.getInstance(ext.getParsedValue()); + + if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) + { + fail("CRL entry reasonCode wrong"); + } + } + else + { + fail("CRL entry reasonCode not found"); + } + } + + public void checkCRLCreation2() + throws Exception + { + AsymmetricCipherKeyPairGenerator kpg = new RSAKeyPairGenerator(); + RSAKeyGenerationParameters genParam = new RSAKeyGenerationParameters( + BigInteger.valueOf(0x1001), new SecureRandom(), 1024, 25); + + kpg.init(genParam); + + AsymmetricCipherKeyPair pair = kpg.generateKeyPair(); + Date now = new Date(); + + X509v2CRLBuilder crlGen = new X509v2CRLBuilder(new X500Name("CN=Test CA"), now); + + crlGen.setNextUpdate(new Date(now.getTime() + 100000)); + + ExtensionsGenerator extGen = new ExtensionsGenerator(); + + CRLReason crlReason = CRLReason.lookup(CRLReason.privilegeWithdrawn); + + extGen.addExtension(Extension.reasonCode, false, crlReason); + + BcX509ExtensionUtils extFact = new BcX509ExtensionUtils(new SHA1DigestCalculator()); + + crlGen.addCRLEntry(BigInteger.ONE, now, extGen.generate()); + + crlGen.addExtension(Extension.authorityKeyIdentifier, false, extFact.createAuthorityKeyIdentifier((AsymmetricKeyParameter)pair.getPublic())); + + AlgorithmIdentifier sigAlg = sigAlgFinder.find("SHA256withRSAEncryption"); + AlgorithmIdentifier digAlg = digAlgFinder.find(sigAlg); + + X509CRLHolder crlHolder = crlGen.build(new BcRSAContentSignerBuilder(sigAlg, digAlg).build((AsymmetricKeyParameter)pair.getPrivate())); + + if (!crlHolder.getIssuer().equals(new X500Name("CN=Test CA"))) + { + fail("failed CRL issuer test"); + } + + Extension authExt = crlHolder.getExtension(Extension.authorityKeyIdentifier); + + if (authExt == null) + { + fail("failed to find CRL extension"); + } + + AuthorityKeyIdentifier authId = AuthorityKeyIdentifier.getInstance(authExt.getParsedValue()); + + X509CRLEntryHolder entry = crlHolder.getRevokedCertificate(BigInteger.ONE); + + if (entry == null) + { + fail("failed to find CRL entry"); + } + + if (!entry.getSerialNumber().equals(BigInteger.ONE)) + { + fail("CRL cert serial number does not match"); + } + + if (!entry.hasExtensions()) + { + fail("CRL entry extension not found"); + } + + Extension ext = entry.getExtension(Extension.reasonCode); + + if (ext != null) + { + ASN1Enumerated reasonCode = ASN1Enumerated.getInstance(ext.getParsedValue()); + + if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) + { + fail("CRL entry reasonCode wrong"); + } + } + else + { + fail("CRL entry reasonCode not found"); + } + } + + public void checkCRLCreation3() + throws Exception + { + AsymmetricCipherKeyPairGenerator kpg = new RSAKeyPairGenerator(); + RSAKeyGenerationParameters genParam = new RSAKeyGenerationParameters( + BigInteger.valueOf(0x1001), new SecureRandom(), 1024, 25); + + kpg.init(genParam); + + AsymmetricCipherKeyPair pair = kpg.generateKeyPair(); + Date now = new Date(); + X509v2CRLBuilder crlGen = new X509v2CRLBuilder(new X500Name("CN=Test CA"), now); + + crlGen.setNextUpdate(new Date(now.getTime() + 100000)); + + ExtensionsGenerator extGen = new ExtensionsGenerator(); + + CRLReason crlReason = CRLReason.lookup(CRLReason.privilegeWithdrawn); + + extGen.addExtension(Extension.reasonCode, false, crlReason); + + BcX509ExtensionUtils extFact = new BcX509ExtensionUtils(new SHA1DigestCalculator()); + + Extensions entryExtensions = extGen.generate(); + + crlGen.addCRLEntry(BigInteger.ONE, now, entryExtensions); + + crlGen.addExtension(Extension.authorityKeyIdentifier, false, extFact.createAuthorityKeyIdentifier((AsymmetricKeyParameter)pair.getPublic())); + + AlgorithmIdentifier sigAlg = sigAlgFinder.find("SHA256withRSAEncryption"); + AlgorithmIdentifier digAlg = digAlgFinder.find(sigAlg); + + X509CRLHolder crlHolder = crlGen.build(new BcRSAContentSignerBuilder(sigAlg, digAlg).build((AsymmetricKeyParameter)pair.getPrivate())); + + if (!crlHolder.getIssuer().equals(new X500Name("CN=Test CA"))) + { + fail("failed CRL issuer test"); + } + + Extension authExt = crlHolder.getExtension(Extension.authorityKeyIdentifier); + + if (authExt == null) + { + fail("failed to find CRL extension"); + } + + AuthorityKeyIdentifier authId = AuthorityKeyIdentifier.getInstance(authExt.getParsedValue()); + + X509CRLEntryHolder entry = crlHolder.getRevokedCertificate(BigInteger.ONE); + + if (entry == null) + { + fail("failed to find CRL entry"); + } + + if (!entry.getSerialNumber().equals(BigInteger.ONE)) + { + fail("CRL cert serial number does not match"); + } + + if (!entry.hasExtensions()) + { + fail("CRL entry extension not found"); + } + + Extension ext = entry.getExtension(Extension.reasonCode); + + if (ext != null) + { + ASN1Enumerated reasonCode = ASN1Enumerated.getInstance(ext.getParsedValue()); + + if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) + { + fail("CRL entry reasonCode wrong"); + } + } + else + { + fail("CRL entry reasonCode not found"); + } + + // + // check loading of existing CRL + // + now = new Date(); + crlGen = new X509v2CRLBuilder(new X500Name("CN=Test CA"), now); + + crlGen.setNextUpdate(new Date(now.getTime() + 100000)); + + crlGen.addCRL(crlHolder); + + crlGen.addCRLEntry(BigInteger.valueOf(2), now, entryExtensions); + + crlGen.addExtension(Extension.authorityKeyIdentifier, false, extFact.createAuthorityKeyIdentifier(pair.getPublic())); + + crlHolder = crlGen.build(new BcRSAContentSignerBuilder(sigAlg, digAlg).build(pair.getPrivate())); + + int count = 0; + boolean oneFound = false; + boolean twoFound = false; + + Iterator it = crlHolder.getRevokedCertificates().iterator(); + while (it.hasNext()) + { + X509CRLEntryHolder crlEnt = (X509CRLEntryHolder)it.next(); + + if (crlEnt.getSerialNumber().intValue() == 1) + { + oneFound = true; + Extension extn = crlEnt.getExtension(Extension.reasonCode); + + if (extn != null) + { + ASN1Enumerated reasonCode = ASN1Enumerated.getInstance(extn.getParsedValue()); + + if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) + { + fail("CRL entry reasonCode wrong on recheck"); + } + } + else + { + fail("CRL entry reasonCode not found on recheck"); + } + } + else if (crlEnt.getSerialNumber().intValue() == 2) + { + twoFound = true; + } + + count++; + } + + if (count != 2) + { + fail("wrong number of CRLs found, got: " + count); + } + + if (!oneFound || !twoFound) + { + fail("wrong CRLs found in copied list"); + } + + // + // check factory read back + // + CertificateFactory cFact = CertificateFactory.getInstance("X.509"); + + X509CRL readCrl = (X509CRL)cFact.generateCRL(new ByteArrayInputStream(crlHolder.getEncoded())); + + if (readCrl == null) + { + fail("crl not returned!"); + } + + Collection col = cFact.generateCRLs(new ByteArrayInputStream(crlHolder.getEncoded())); + + if (col.size() != 1) + { + fail("wrong number of CRLs found in collection"); + } + } + + public void checkCreation5() + throws Exception + { + // + // a sample key pair. + // + AsymmetricKeyParameter pubKey = new RSAKeyParameters( + false, + new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), + new BigInteger("11", 16)); + + AsymmetricKeyParameter privKey = new RSAPrivateCrtKeyParameters( + new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), + new BigInteger("11", 16), + new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), + new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), + new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), + new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), + new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), + new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); + + // + // set up the keys + // + SecureRandom rand = new SecureRandom(); + + // + // distinguished name table. + // + X500NameBuilder builder = createStdBuilder(); + + // + // create base certificate - version 3 + // + AlgorithmIdentifier sigAlg = sigAlgFinder.find("MD5WithRSA"); + AlgorithmIdentifier digAlg = digAlgFinder.find(sigAlg); + + ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlg, digAlg).build(privKey); + ASN1ObjectIdentifier extOid = new ASN1ObjectIdentifier("2.5.29.37"); + X509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(builder.build(),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey) + .addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, + new KeyUsage(KeyUsage.encipherOnly)) + .addExtension(extOid, true, + new DERSequence(KeyPurposeId.anyExtendedKeyUsage)) + .addExtension(new ASN1ObjectIdentifier("2.5.29.17"), true, + new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); + + X509CertificateHolder baseCert = certGen.build(sigGen); + + // + // copy certificate + // + + certGen = new BcX509v3CertificateBuilder(builder.build(),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey) + .copyAndAddExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, baseCert) + .copyAndAddExtension(extOid, false, baseCert); + + X509CertificateHolder cert = certGen.build(sigGen); + + assertTrue(cert.isValidOn(new Date())); + + assertTrue(cert.isSignatureValid(new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); + + if (!baseCert.getExtension(new ASN1ObjectIdentifier("2.5.29.15")).equals(cert.getExtension(new ASN1ObjectIdentifier("2.5.29.15")))) + { + fail("2.5.29.15 differs"); + } + + assertTrue(baseCert.getExtension(extOid).getExtnId().equals(cert.getExtension(extOid).getExtnId())); + assertFalse(baseCert.getExtension(extOid).isCritical() == cert.getExtension(extOid).isCritical()); + if (!baseCert.getExtension(extOid).getParsedValue().equals(cert.getExtension(extOid).getParsedValue())) + { + fail("2.5.29.37 differs"); + } + + // + // exception test + // + + try + { + certGen.copyAndAddExtension(new ASN1ObjectIdentifier("2.5.99.99"), true, baseCert); + + fail("exception not thrown on dud extension copy"); + } + catch (NullPointerException e) + { + // expected + } + +// try +// { +// certGen.setPublicKey(dudPublicKey); +// +// certGen.generate(privKey, BC); +// +// fail("key without encoding not detected in v3"); +// } +// catch (IllegalArgumentException e) +// { +// // expected +// } + + } + + public void testForgedSignature() + throws Exception + { + String cert = "MIIBsDCCAVoCAQYwDQYJKoZIhvcNAQEFBQAwYzELMAkGA1UEBhMCQVUxEzARBgNV" + + "BAgTClF1ZWVuc2xhbmQxGjAYBgNVBAoTEUNyeXB0U29mdCBQdHkgTHRkMSMwIQYD" + + "VQQDExpTZXJ2ZXIgdGVzdCBjZXJ0ICg1MTIgYml0KTAeFw0wNjA5MTEyMzU4NTVa" + + "Fw0wNjEwMTEyMzU4NTVaMGMxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpRdWVlbnNs" + + "YW5kMRowGAYDVQQKExFDcnlwdFNvZnQgUHR5IEx0ZDEjMCEGA1UEAxMaU2VydmVy" + + "IHRlc3QgY2VydCAoNTEyIGJpdCkwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAn7PD" + + "hCeV/xIxUg8V70YRxK2A5jZbD92A12GN4PxyRQk0/lVmRUNMaJdq/qigpd9feP/u" + + "12S4PwTLb/8q/v657QIDAQABMA0GCSqGSIb3DQEBBQUAA0EAbynCRIlUQgaqyNgU" + + "DF6P14yRKUtX8akOP2TwStaSiVf/akYqfLFm3UGka5XbPj4rifrZ0/sOoZEEBvHQ" + + "e20sRA=="; + + X509CertificateHolder hldr = new X509CertificateHolder(Base64.decode(cert)); + + assertFalse(hldr.isSignatureValid(new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(hldr))); + } + + private void pemTest() + throws Exception + { + CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); + + X509Certificate cert = readPEMCert(cf, PEMData.CERTIFICATE_1); + if (cert == null) + { + fail("PEM cert not read"); + } + cert = readPEMCert(cf, "-----BEGIN CERTIFICATE-----" + PEMData.CERTIFICATE_2); + if (cert == null) + { + fail("PEM cert with extraneous header not read"); + } + CRL crl = cf.generateCRL(new ByteArrayInputStream(PEMData.CRL_1.getBytes("US-ASCII"))); + if (crl == null) + { + fail("PEM crl not read"); + } + Collection col = cf.generateCertificates(new ByteArrayInputStream(PEMData.CERTIFICATE_2.getBytes("US-ASCII"))); + if (col.size() != 1 || !col.contains(cert)) + { + fail("PEM cert collection not right"); + } + col = cf.generateCRLs(new ByteArrayInputStream(PEMData.CRL_2.getBytes("US-ASCII"))); + if (col.size() != 1 || !col.contains(crl)) + { + fail("PEM crl collection not right"); + } + } + + private static X509Certificate readPEMCert(CertificateFactory cf, String pemData) + throws CertificateException, UnsupportedEncodingException + { + return (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(pemData.getBytes("US-ASCII"))); + } + + private void createPSSCert(String algorithm) + throws Exception + { + AsymmetricCipherKeyPair pair = generateLongFixedKeys(); + + AsymmetricKeyParameter privKey = (AsymmetricKeyParameter)pair.getPrivate(); + AsymmetricKeyParameter pubKey = (AsymmetricKeyParameter)pair.getPublic(); + + // + // distinguished name table. + // + + X500NameBuilder builder = createStdBuilder(); + + // + // create base certificate - version 3 + // + BcX509ExtensionUtils extFact = new BcX509ExtensionUtils(new SHA1DigestCalculator()); + + AlgorithmIdentifier sigAlgId = sigAlgFinder.find(algorithm); + AlgorithmIdentifier digAlgId = digAlgFinder.find(sigAlgId); + + ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privKey); + BcX509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(builder.build(),BigInteger.valueOf(1), + new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),builder.build(),pubKey); + + certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, + new KeyUsage(KeyUsage.encipherOnly)); + certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true, + new DERSequence(KeyPurposeId.anyExtendedKeyUsage)); + certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.17"), true, + new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); + + certGen.addExtension(Extension.authorityKeyIdentifier, true, extFact.createAuthorityKeyIdentifier(pubKey)); + + X509CertificateHolder baseCert = certGen.build(sigGen); + + assertTrue(baseCert.isSignatureValid(new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); + } + + private AsymmetricCipherKeyPair generateLongFixedKeys() + { + RSAKeyParameters pubKeySpec = new RSAKeyParameters( + false, + new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), + new BigInteger("010001",16)); + + RSAKeyParameters privKeySpec = new RSAPrivateCrtKeyParameters( + new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), + new BigInteger("010001",16), + new BigInteger("33a5042a90b27d4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b325",16), + new BigInteger("e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e86296b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b3b6dcd3eda8e6443",16), + new BigInteger("b69dca1cf7d4d7ec81e75b90fcca874abcde123fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc723e6963364a1f9425452b269a6799fd",16), + new BigInteger("28fa13938655be1f8a159cbaca5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8dd3ede2448328f385d81b30e8e43b2fffa027861979",16), + new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729",16), + new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d",16)); + + return new AsymmetricCipherKeyPair(pubKeySpec, privKeySpec); + } + + public void testNullDerNullCert() + throws Exception + { + AsymmetricCipherKeyPair pair = generateLongFixedKeys(); + AsymmetricKeyParameter pubKey = (AsymmetricKeyParameter)pair.getPublic(); + AsymmetricKeyParameter privKey = (AsymmetricKeyParameter)pair.getPrivate(); + + DefaultSignatureAlgorithmIdentifierFinder sigAlgFinder = new DefaultSignatureAlgorithmIdentifierFinder(); + DefaultDigestAlgorithmIdentifierFinder digAlgFinder = new DefaultDigestAlgorithmIdentifierFinder(); + + AlgorithmIdentifier sigAlgId = sigAlgFinder.find("MD5withRSA"); + AlgorithmIdentifier digAlgId = digAlgFinder.find(sigAlgId); + + ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privKey); + BcX509v3CertificateBuilder certGen = new BcX509v3CertificateBuilder(new X500Name("CN=Test"),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),new X500Name("CN=Test"),pubKey); + X509CertificateHolder cert = certGen.build(sigGen); + + Certificate struct = Certificate.getInstance(cert.getEncoded()); + + ASN1Object tbsCertificate = struct.getTBSCertificate(); + AlgorithmIdentifier sig = struct.getSignatureAlgorithm(); + + ASN1EncodableVector v = new ASN1EncodableVector(); + + v.add(tbsCertificate); + v.add(new AlgorithmIdentifier(sig.getAlgorithm())); + v.add(struct.getSignature()); + + // verify + ByteArrayInputStream bIn; + String dump = ""; + + bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded()); + + cert = new X509CertificateHolder(new DERSequence(v).getEncoded()); + + assertTrue(cert.isSignatureValid(new BcRSAContentVerifierProviderBuilder(digAlgFinder).build(pubKey))); + } + + public void testCertificates() + throws Exception + { + checkCertificate(1, cert1); + checkCertificate(2, cert2); + checkCertificate(3, cert3); + checkCertificate(4, cert4); + checkCertificate(5, cert5); + //checkCertificate(7, cert7); + + checkKeyUsage(8, keyUsage); + + checkSelfSignedCertificate(11, probSelfSignedCert); + + checkCRL(1, crl1); + + checkCreation1(); + checkCreation2(); + checkCreation5(); + + createPSSCert("SHA1withRSAandMGF1"); + createPSSCert("SHA224withRSAandMGF1"); + createPSSCert("SHA256withRSAandMGF1"); + createPSSCert("SHA384withRSAandMGF1"); + + checkCRLCreation1(); + checkCRLCreation2(); + checkCRLCreation3(); + + pemTest(); + + checkCertificate(18, emptyDNCert); + } +} diff --git a/pkix/src/test/jdk1.3/org/bouncycastle/cert/test/PKCS10Test.java b/pkix/src/test/jdk1.3/org/bouncycastle/cert/test/PKCS10Test.java index 8109824e..2865e825 100644 --- a/pkix/src/test/jdk1.3/org/bouncycastle/cert/test/PKCS10Test.java +++ b/pkix/src/test/jdk1.3/org/bouncycastle/cert/test/PKCS10Test.java @@ -24,6 +24,7 @@ import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.KeyUsage; import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.X509Extension; import org.bouncycastle.asn1.x509.X509Extensions; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; @@ -40,6 +41,7 @@ import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.ContentVerifierProvider; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder; +import org.bouncycastle.cert.bc.BcX509ExtensionUtils; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder; import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest; diff --git a/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/AllTests.java b/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/AllTests.java index f8358aa5..2a7f57e0 100644 --- a/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/AllTests.java +++ b/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/AllTests.java @@ -16,16 +16,24 @@ public class AllTests public static Test suite() throws Exception - { + { TestSuite suite = new TestSuite("CMS tests"); - - suite.addTest(CompressedDataTest.suite()); - suite.addTest(SignedDataTest.suite()); - suite.addTest(EnvelopedDataTest.suite()); - suite.addTest(CompressedDataStreamTest.suite()); - suite.addTest(SignedDataStreamTest.suite()); - suite.addTest(EnvelopedDataStreamTest.suite()); + suite.addTest(NewCompressedDataTest.suite()); + suite.addTest(NewSignedDataTest.suite()); + suite.addTest(NewEnvelopedDataTest.suite()); + suite.addTest(NewAuthenticatedDataTest.suite()); + suite.addTest(NewAuthenticatedDataStreamTest.suite()); + suite.addTest(NewCompressedDataStreamTest.suite()); + suite.addTest(NewSignedDataStreamTest.suite()); + suite.addTest(NewEnvelopedDataStreamTest.suite()); + + suite.addTest(MiscDataStreamTest.suite()); + suite.addTest(Rfc4134Test.suite()); + suite.addTest(ConverterTest.suite()); + + suite.addTest(BcEnvelopedDataTest.suite()); + suite.addTest(BcSignedDataTest.suite()); return suite; } diff --git a/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/Rfc4134Test.java b/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/Rfc4134Test.java deleted file mode 100644 index 39ae6c09..00000000 --- a/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/Rfc4134Test.java +++ /dev/null @@ -1,430 +0,0 @@ -package org.bouncycastle.cms.test; - -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.security.KeyFactory; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Security; -import org.bouncycastle.jce.cert.CertStore; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.security.interfaces.DSAParams; -import java.security.interfaces.DSAPublicKey; -import java.security.spec.DSAPublicKeySpec; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.DERUTF8String; -import org.bouncycastle.asn1.cms.Attribute; -import org.bouncycastle.asn1.cms.AttributeTable; -import org.bouncycastle.asn1.cms.CMSAttributes; -import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.cms.CMSEnvelopedData; -import org.bouncycastle.cms.CMSEnvelopedDataGenerator; -import org.bouncycastle.cms.CMSEnvelopedDataParser; -import org.bouncycastle.cms.CMSException; -import org.bouncycastle.cms.CMSProcessableByteArray; -import org.bouncycastle.cms.CMSSignedData; -import org.bouncycastle.cms.CMSSignedDataParser; -import org.bouncycastle.cms.CMSTypedStream; -import org.bouncycastle.cms.RecipientInformation; -import org.bouncycastle.cms.RecipientInformationStore; -import org.bouncycastle.cms.SignerInformation; -import org.bouncycastle.cms.SignerInformationStore; -import org.bouncycastle.cms.jcajce.JcaX509CertSelectorConverter; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.encoders.Hex; -import org.bouncycastle.util.io.Streams; - -public class Rfc4134Test - extends TestCase -{ - private static final String BC = BouncyCastleProvider.PROVIDER_NAME; - private static final String TEST_DATA_HOME = "bc.test.data.home"; - - private static byte[] exContent = getRfc4134Data("ExContent.bin"); - private static byte[] sha1 = Hex.decode("406aec085279ba6e16022d9e0629c0229687dd48"); - - private static final JcaX509CertSelectorConverter selectorConverter = new JcaX509CertSelectorConverter(); - - public Rfc4134Test(String name) - { - super(name); - } - - public static void main(String args[]) - { - Security.addProvider(new BouncyCastleProvider()); - - junit.textui.TestRunner.run(Rfc4134Test.class); - } - - public static Test suite() - throws Exception - { - return new CMSTestSetup(new TestSuite(Rfc4134Test.class)); - } - - public void test4_1() - throws Exception - { - byte[] data = getRfc4134Data("4.1.bin"); - CMSSignedData signedData = new CMSSignedData(data); - - verifySignatures(signedData); - - CMSSignedDataParser parser = new CMSSignedDataParser(data); - - verifySignatures(parser); - } - - public void test4_2() - throws Exception - { - byte[] data = getRfc4134Data("4.2.bin"); - CMSSignedData signedData = new CMSSignedData(data); - - verifySignatures(signedData); - - CMSSignedDataParser parser = new CMSSignedDataParser(data); - - verifySignatures(parser); - } - - public void testRfc4_3() - throws Exception - { - byte[] data = getRfc4134Data("4.3.bin"); - CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(exContent), data); - - verifySignatures(signedData, sha1); - - CMSSignedDataParser parser = new CMSSignedDataParser( - new CMSTypedStream(new ByteArrayInputStream(exContent)), - data); - - verifySignatures(parser); - } - - public void test4_4() - throws Exception - { - byte[] data = getRfc4134Data("4.4.bin"); - byte[] counterSigCert = getRfc4134Data("AliceRSASignByCarl.cer"); - CMSSignedData signedData = new CMSSignedData(data); - - verifySignatures(signedData, sha1); - - verifySignerInfo4_4(getFirstSignerInfo(signedData.getSignerInfos()), counterSigCert); - - CMSSignedDataParser parser = new CMSSignedDataParser(data); - - verifySignatures(parser); - - verifySignerInfo4_4(getFirstSignerInfo(parser.getSignerInfos()), counterSigCert); - } - - public void test4_5() - throws Exception - { - byte[] data = getRfc4134Data("4.5.bin"); - CMSSignedData signedData = new CMSSignedData(data); - - verifySignatures(signedData); - - CMSSignedDataParser parser = new CMSSignedDataParser(data); - - verifySignatures(parser); - } - - public void test4_6() - throws Exception - { - byte[] data = getRfc4134Data("4.6.bin"); - CMSSignedData signedData = new CMSSignedData(data); - - verifySignatures(signedData); - - CMSSignedDataParser parser = new CMSSignedDataParser(data); - - verifySignatures(parser); - } - - public void test4_7() - throws Exception - { - byte[] data = getRfc4134Data("4.7.bin"); - CMSSignedData signedData = new CMSSignedData(data); - - verifySignatures(signedData); - - CMSSignedDataParser parser = new CMSSignedDataParser(data); - - verifySignatures(parser); - } - - public void test5_1() - throws Exception - { - byte[] data = getRfc4134Data("5.1.bin"); - CMSEnvelopedData envelopedData = new CMSEnvelopedData(data); - - verifyEnvelopedData(envelopedData, CMSEnvelopedDataGenerator.DES_EDE3_CBC); - - CMSEnvelopedDataParser envelopedParser = new CMSEnvelopedDataParser(data); - - verifyEnvelopedData(envelopedParser, CMSEnvelopedDataGenerator.DES_EDE3_CBC); - } - - public void test5_2() - throws Exception - { - byte[] data = getRfc4134Data("5.2.bin"); - CMSEnvelopedData envelopedData = new CMSEnvelopedData(data); - - verifyEnvelopedData(envelopedData, CMSEnvelopedDataGenerator.RC2_CBC); - - CMSEnvelopedDataParser envelopedParser = new CMSEnvelopedDataParser(data); - - verifyEnvelopedData(envelopedParser, CMSEnvelopedDataGenerator.RC2_CBC); - } - - private void verifyEnvelopedData(CMSEnvelopedData envelopedData, String symAlgorithmOID) - throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CMSException - { - byte[] privKeyData = getRfc4134Data("BobPrivRSAEncrypt.pri"); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyData); - KeyFactory keyFact = KeyFactory.getInstance("RSA", BC); - PrivateKey privKey = keyFact.generatePrivate(keySpec); - - RecipientInformationStore recipients = envelopedData.getRecipientInfos(); - - assertEquals(envelopedData.getEncryptionAlgOID(), symAlgorithmOID); - - Collection c = recipients.getRecipients(); - assertTrue(c.size() >= 1 && c.size() <= 2); - - Iterator it = c.iterator(); - verifyRecipient((RecipientInformation)it.next(), privKey); - - if (c.size() == 2) - { - RecipientInformation recInfo = (RecipientInformation)it.next(); - - assertEquals(PKCSObjectIdentifiers.id_alg_CMSRC2wrap.getId(), recInfo.getKeyEncryptionAlgOID()); - } - } - - private void verifyEnvelopedData(CMSEnvelopedDataParser envelopedParser, String symAlgorithmOID) - throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CMSException - { - byte[] privKeyData = getRfc4134Data("BobPrivRSAEncrypt.pri"); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyData); - KeyFactory keyFact = KeyFactory.getInstance("RSA", BC); - PrivateKey privKey = keyFact.generatePrivate(keySpec); - - RecipientInformationStore recipients = envelopedParser.getRecipientInfos(); - - assertEquals(envelopedParser.getEncryptionAlgOID(), symAlgorithmOID); - - Collection c = recipients.getRecipients(); - assertTrue(c.size() >= 1 && c.size() <= 2); - - Iterator it = c.iterator(); - verifyRecipient((RecipientInformation)it.next(), privKey); - - if (c.size() == 2) - { - RecipientInformation recInfo = (RecipientInformation)it.next(); - - assertEquals(PKCSObjectIdentifiers.id_alg_CMSRC2wrap.getId(), recInfo.getKeyEncryptionAlgOID()); - } - } - - private void verifyRecipient(RecipientInformation recipient, PrivateKey privKey) - throws CMSException, NoSuchProviderException - { - assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId()); - - byte[] recData = recipient.getContent(privKey, BC); - - assertEquals(true, Arrays.equals(exContent, recData)); - } - - private void verifySignerInfo4_4(SignerInformation signerInfo, byte[] counterSigCert) - throws Exception - { - verifyCounterSignature(signerInfo, counterSigCert); - - verifyContentHint(signerInfo); - } - - private SignerInformation getFirstSignerInfo(SignerInformationStore store) - { - return (SignerInformation)store.getSigners().iterator().next(); - } - - private void verifyCounterSignature(SignerInformation signInfo, byte[] certificate) - throws Exception - { - SignerInformation csi = (SignerInformation)signInfo.getCounterSignatures().getSigners().iterator().next(); - - CertificateFactory certFact = CertificateFactory.getInstance("X.509", BC); - X509Certificate cert = (X509Certificate)certFact.generateCertificate(new ByteArrayInputStream(certificate)); - - assertTrue(csi.verify(cert, BC)); - } - - private void verifyContentHint(SignerInformation signInfo) - { - AttributeTable attrTable = signInfo.getUnsignedAttributes(); - - Attribute attr = attrTable.get(CMSAttributes.contentHint); - - assertEquals(1, attr.getAttrValues().size()); - - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(new DERUTF8String("Content Hints Description Buffer")); - v.add(CMSObjectIdentifiers.data); - - assertTrue(attr.getAttrValues().getObjectAt(0).equals(new DERSequence(v))); - } - - private void verifySignatures(CMSSignedData s, byte[] contentDigest) - throws Exception - { - CertStore certStore = s.getCertificatesAndCRLs("Collection", BC); - SignerInformationStore signers = s.getSignerInfos(); - - Collection c = signers.getSigners(); - Iterator it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certStore.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - verifySigner(signer, cert); - - if (contentDigest != null) - { - assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest())); - } - } - - Collection certColl = certStore.getCertificates(null); - Collection crlColl = certStore.getCRLs(null); - - assertEquals(certColl.size(), s.getCertificates("Collection", BC).getMatches(null).size()); - assertEquals(crlColl.size(), s.getCRLs("Collection", BC).getMatches(null).size()); - } - - private void verifySignatures(CMSSignedData s) - throws Exception - { - verifySignatures(s, null); - } - - private void verifySignatures(CMSSignedDataParser sp) - throws Exception - { - CMSTypedStream sc = sp.getSignedContent(); - if (sc != null) - { - sc.drain(); - } - - CertStore certs = sp.getCertificatesAndCRLs("Collection", BC); - SignerInformationStore signers = sp.getSignerInfos(); - - Collection c = signers.getSigners(); - Iterator it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certs.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - verifySigner(signer, cert); - } - } - - private void verifySigner(SignerInformation signer, X509Certificate cert) - throws Exception - { - if (cert.getPublicKey() instanceof DSAPublicKey) - { - DSAPublicKey key = (DSAPublicKey)cert.getPublicKey(); - - if (key.getParams() == null) - { - assertEquals(true, signer.verify(getInheritedKey(key), BC)); - } - else - { - assertEquals(true, signer.verify(cert, BC)); - } - } - else - { - assertEquals(true, signer.verify(cert, BC)); - } - } - - private PublicKey getInheritedKey(DSAPublicKey key) - throws Exception - { - CertificateFactory certFact = CertificateFactory.getInstance("X.509", BC); - - X509Certificate cert = (X509Certificate)certFact.generateCertificate(new ByteArrayInputStream(getRfc4134Data("CarlDSSSelf.cer"))); - - DSAParams dsaParams = ((DSAPublicKey)cert.getPublicKey()).getParams(); - - DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec( - key.getY(), dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); - - KeyFactory keyFactory = KeyFactory.getInstance("DSA", BC); - - return keyFactory.generatePublic(dsaPubKeySpec); - } - - private static byte[] getRfc4134Data(String name) - { - String dataHome = System.getProperty(TEST_DATA_HOME); - - if (dataHome == null) - { - throw new IllegalStateException(TEST_DATA_HOME + " property not set"); - } - - try - { - return Streams.readAll(new FileInputStream(dataHome + "/rfc4134/" + name)); - } - catch (IOException e) - { - throw new RuntimeException(e.toString()); - } - } -} diff --git a/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/SignedDataStreamTest.java b/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/SignedDataStreamTest.java deleted file mode 100644 index 39becc42..00000000 --- a/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/SignedDataStreamTest.java +++ /dev/null @@ -1,1158 +0,0 @@ -package org.bouncycastle.cms.test; - -import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.OutputStream; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import org.bouncycastle.jce.cert.CertStore; -import org.bouncycastle.jce.cert.CollectionCertStoreParameters; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.cms.Attribute; -import org.bouncycastle.asn1.cms.AttributeTable; -import org.bouncycastle.asn1.cms.CMSAttributes; -import org.bouncycastle.cms.CMSAttributeTableGenerator; -import org.bouncycastle.cms.CMSProcessable; -import org.bouncycastle.cms.CMSProcessableByteArray; -import org.bouncycastle.cms.CMSSignedData; -import org.bouncycastle.cms.CMSSignedDataGenerator; -import org.bouncycastle.cms.CMSSignedDataParser; -import org.bouncycastle.cms.CMSSignedDataStreamGenerator; -import org.bouncycastle.cms.CMSSignedGenerator; -import org.bouncycastle.cms.CMSTypedStream; -import org.bouncycastle.cms.DefaultSignedAttributeTableGenerator; -import org.bouncycastle.cms.SignerInformation; -import org.bouncycastle.cms.SignerInformationStore; -import org.bouncycastle.cms.jcajce.JcaX509CertSelectorConverter; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.x509.X509AttributeCertificate; -import org.bouncycastle.x509.X509CollectionStoreParameters; -import org.bouncycastle.x509.X509Store; - -public class SignedDataStreamTest - extends TestCase -{ - private static final String BC = BouncyCastleProvider.PROVIDER_NAME; - - private static final String TEST_MESSAGE = "Hello World!"; - private static String _signDN; - private static KeyPair _signKP; - private static X509Certificate _signCert; - - private static String _origDN; - private static KeyPair _origKP; - private static X509Certificate _origCert; - - private static String _reciDN; - private static KeyPair _reciKP; - private static X509Certificate _reciCert; - - private static KeyPair _origDsaKP; - private static X509Certificate _origDsaCert; - - private static X509CRL _signCrl; - private static X509CRL _origCrl; - - private static boolean _initialised = false; - - private static final JcaX509CertSelectorConverter selectorConverter = new JcaX509CertSelectorConverter(); - - public SignedDataStreamTest(String name) - { - super(name); - } - - private static void init() - throws Exception - { - if (!_initialised) - { - _initialised = true; - - _signDN = "O=Bouncy Castle, C=AU"; - _signKP = CMSTestUtil.makeKeyPair(); - _signCert = CMSTestUtil.makeCertificate(_signKP, _signDN, _signKP, _signDN); - - _origDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU"; - _origKP = CMSTestUtil.makeKeyPair(); - _origCert = CMSTestUtil.makeCertificate(_origKP, _origDN, _signKP, _signDN); - - _origDsaKP = CMSTestUtil.makeDsaKeyPair(); - _origDsaCert = CMSTestUtil.makeCertificate(_origDsaKP, _origDN, _signKP, _signDN); - - _reciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU"; - _reciKP = CMSTestUtil.makeKeyPair(); - _reciCert = CMSTestUtil.makeCertificate(_reciKP, _reciDN, _signKP, _signDN); - - _signCrl = CMSTestUtil.makeCrl(_signKP); - _origCrl = CMSTestUtil.makeCrl(_origKP); - } - } - - private void verifySignatures(CMSSignedDataParser sp, byte[] contentDigest) - throws Exception - { - CertStore certStore = sp.getCertificatesAndCRLs("Collection", BC); - SignerInformationStore signers = sp.getSignerInfos(); - - Collection c = signers.getSigners(); - Iterator it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certStore.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertEquals(true, signer.verify(cert, BC)); - - if (contentDigest != null) - { - assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest())); - } - } - - Collection certColl = certStore.getCertificates(null); - Collection crlColl = certStore.getCRLs(null); - - assertEquals(certColl.size(), sp.getCertificates("Collection", BC).getMatches(null).size()); - assertEquals(crlColl.size(), sp.getCRLs("Collection", BC).getMatches(null).size()); - } - - private void verifySignatures(CMSSignedDataParser sp) - throws Exception - { - verifySignatures(sp, null); - } - - private void verifyEncodedData(ByteArrayOutputStream bOut) - throws Exception - { - CMSSignedDataParser sp; - sp = new CMSSignedDataParser(bOut.toByteArray()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - - sp.close(); - } - - private void checkSigParseable(byte[] sig) - throws Exception - { - CMSSignedDataParser sp = new CMSSignedDataParser(sig); - sp.getVersion(); - CMSTypedStream sc = sp.getSignedContent(); - if (sc != null) - { - sc.drain(); - } - sp.getCertificatesAndCRLs("Collection", BC); - sp.getSignerInfos(); - sp.close(); - } - - public void testEarlyInvalidKeyException() throws Exception - { - try - { - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - gen.addSigner( _origKP.getPrivate(), _origCert, - "DSA", // DOESN'T MATCH KEY ALG - CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - fail("Expected InvalidKeyException in addSigner"); - } - catch (InvalidKeyException e) - { - // Ignore - } - } - - public void testEarlyNoSuchAlgorithmException() throws Exception - { - try - { - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - gen.addSigner( _origKP.getPrivate(), _origCert, - CMSSignedDataStreamGenerator.DIGEST_SHA1, // BAD OID! - CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - fail("Expected NoSuchAlgorithmException in addSigner"); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - - public void testSha1EncapsulatedSignature() - throws Exception - { - byte[] encapSigData = Base64.decode( - "MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEH" - + "AaCAJIAEDEhlbGxvIFdvcmxkIQAAAAAAAKCCBGIwggINMIIBdqADAgECAgEF" - + "MA0GCSqGSIb3DQEBBAUAMCUxFjAUBgNVBAoTDUJvdW5jeSBDYXN0bGUxCzAJ" - + "BgNVBAYTAkFVMB4XDTA1MDgwNzA2MjU1OVoXDTA1MTExNTA2MjU1OVowJTEW" - + "MBQGA1UEChMNQm91bmN5IENhc3RsZTELMAkGA1UEBhMCQVUwgZ8wDQYJKoZ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jh3gG8CAwEAAaNNMEswHQYDVR0OBBYEFLfY/4EG" - + "mYrvJa7Cky+K9BJ7YmERMB8GA1UdIwQYMBaAFDddR8QTr4P634sgmAoRJJQT" - + "nx7LMAkGA1UdEwQCMAAwDQYJKoZIhvcNAQEEBQADgYEADIOmpMd6UHdMjkyc" - + "mIE1yiwfClCsGhCK9FigTg6U1G2FmkBwJIMWBlkeH15uvepsAncsgK+Cn3Zr" - + "dZMb022mwtTJDtcaOM+SNeuCnjdowZ4i71Hf68siPm6sMlZkhz49rA0Yidoo" - + "WuzYOO+dggzwDsMldSsvsDo/ARyCGOulDOAxggEvMIIBKwIBATAqMCUxFjAU" - + "BgNVBAoTDUJvdW5jeSBDYXN0bGUxCzAJBgNVBAYTAkFVAgEHMAkGBSsOAwIa" - + "BQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEP" - + "Fw0wNTA4MDcwNjI1NTlaMCMGCSqGSIb3DQEJBDEWBBQu973mCM5UBOl9XwQv" - + "lfifHCMocTANBgkqhkiG9w0BAQEFAASBgGxnBl2qozYKLgZ0ygqSFgWcRGl1" - + "LgNuE587LtO+EKkgoc3aFqEdjXlAyP8K7naRsvWnFrsB6pUpnrgI9Z8ZSKv8" - + "98IlpsSSJ0jBlEb4gzzavwcBpYbr2ryOtDcF+kYmKIpScglyyoLzm+KPXOoT" - + "n7MsJMoKN3Kd2Vzh6s10PFgeAAAAAAAA"); - - CMSSignedDataParser sp = new CMSSignedDataParser(encapSigData); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - } - - public void testSHA1WithRSANoAttributes() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray(TEST_MESSAGE.getBytes()); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData s = gen.generate(CMSSignedDataGenerator.DATA, msg, false, BC, false); - - CMSSignedDataParser sp = new CMSSignedDataParser( - new CMSTypedStream(new ByteArrayInputStream(TEST_MESSAGE.getBytes())), s.getEncoded()); - - sp.getSignedContent().drain(); - - // - // compute expected content digest - // - MessageDigest md = MessageDigest.getInstance("SHA1", BC); - - verifySignatures(sp, md.digest(TEST_MESSAGE.getBytes())); - } - - public void testDSANoAttributes() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray(TEST_MESSAGE.getBytes()); - - certList.add(_origDsaCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origDsaKP.getPrivate(), _origDsaCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData s = gen.generate(CMSSignedDataGenerator.DATA, msg, false, BC, false); - - CMSSignedDataParser sp = new CMSSignedDataParser( - new CMSTypedStream(new ByteArrayInputStream(TEST_MESSAGE.getBytes())), s.getEncoded()); - - sp.getSignedContent().drain(); - - // - // compute expected content digest - // - MessageDigest md = MessageDigest.getInstance("SHA1", BC); - - verifySignatures(sp, md.digest(TEST_MESSAGE.getBytes())); - } - - public void testSHA1WithRSA() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_origCert); - certList.add(_signCert); - - certList.add(_signCrl); - certList.add(_origCrl); - - CertStore certsAndCrls = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certsAndCrls); - - OutputStream sigOut = gen.open(bOut); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - checkSigParseable(bOut.toByteArray()); - - CMSSignedDataParser sp = new CMSSignedDataParser( - new CMSTypedStream(new ByteArrayInputStream(TEST_MESSAGE.getBytes())), bOut.toByteArray()); - - sp.getSignedContent().drain(); - - // - // compute expected content digest - // - MessageDigest md = MessageDigest.getInstance("SHA1", BC); - - verifySignatures(sp, md.digest(TEST_MESSAGE.getBytes())); - - // - // try using existing signer - // - gen = new CMSSignedDataStreamGenerator(); - - gen.addSigners(sp.getSignerInfos()); - - gen.addCertificatesAndCRLs(sp.getCertificatesAndCRLs("Collection", BC)); - - bOut.reset(); - - sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - verifyEncodedData(bOut); - - // - // look for the CRLs - // - Collection col = certsAndCrls.getCRLs(null); - - assertEquals(2, col.size()); - assertTrue(col.contains(_signCrl)); - assertTrue(col.contains(_origCrl)); - } - - public void testSHA1WithRSANonData() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_origCert); - certList.add(_signCert); - - certList.add(_signCrl); - certList.add(_origCrl); - - CertStore certsAndCrls = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certsAndCrls); - - OutputStream sigOut = gen.open(bOut, "1.2.3.4", true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - CMSSignedDataParser sp = new CMSSignedDataParser(bOut.toByteArray()); - - CMSTypedStream stream = sp.getSignedContent(); - - assertEquals(new ASN1ObjectIdentifier("1.2.3.4"), stream.getContentType()); - - stream.drain(); - - // - // compute expected content digest - // - MessageDigest md = MessageDigest.getInstance("SHA1", BC); - - verifySignatures(sp, md.digest(TEST_MESSAGE.getBytes())); - } - - public void testSHA1AndMD5WithRSA() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_MD5, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - checkSigParseable(bOut.toByteArray()); - - CMSSignedDataParser sp = new CMSSignedDataParser( - new CMSTypedStream(new ByteArrayInputStream(TEST_MESSAGE.getBytes())), bOut.toByteArray()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - } - - public void testSHA1WithRSAEncapsulatedBufferedStream() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - // - // find unbuffered length - // - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut, true); - - for (int i = 0; i != 2000; i++) - { - sigOut.write(i & 0xff); - } - - sigOut.close(); - - CMSSignedDataParser sp = new CMSSignedDataParser(bOut.toByteArray()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - - int unbufferedLength = bOut.toByteArray().length; - - // - // find buffered length with buffered stream - should be equal - // - bOut = new ByteArrayOutputStream(); - - gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - sigOut = gen.open(bOut, true); - - BufferedOutputStream bfOut = new BufferedOutputStream(sigOut, 300); - - for (int i = 0; i != 2000; i++) - { - bfOut.write(i & 0xff); - } - - bfOut.close(); - - verifyEncodedData(bOut); - - assertTrue(bOut.toByteArray().length == unbufferedLength); - } - - public void testSHA1WithRSAEncapsulatedBuffered() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - // - // find unbuffered length - // - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut, true); - - for (int i = 0; i != 2000; i++) - { - sigOut.write(i & 0xff); - } - - sigOut.close(); - - CMSSignedDataParser sp = new CMSSignedDataParser(bOut.toByteArray()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - - int unbufferedLength = bOut.toByteArray().length; - - // - // find buffered length - buffer size less than default - // - bOut = new ByteArrayOutputStream(); - - gen = new CMSSignedDataStreamGenerator(); - - gen.setBufferSize(300); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - sigOut = gen.open(bOut, true); - - for (int i = 0; i != 2000; i++) - { - sigOut.write(i & 0xff); - } - - sigOut.close(); - - verifyEncodedData(bOut); - - assertTrue(bOut.toByteArray().length > unbufferedLength); - } - - public void testSHA1WithRSAEncapsulated() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - CMSSignedDataParser sp = new CMSSignedDataParser(bOut.toByteArray()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - - byte[] contentDigest = (byte[])gen.getGeneratedDigests().get(CMSSignedGenerator.DIGEST_SHA1); - - AttributeTable table = ((SignerInformation)sp.getSignerInfos().getSigners().iterator().next()).getSignedAttributes(); - Attribute hash = table.get(CMSAttributes.messageDigest); - - assertTrue(MessageDigest.isEqual(contentDigest, ((ASN1OctetString)hash.getAttrValues().getObjectAt(0)).getOctets())); - - // - // try using existing signer - // - gen = new CMSSignedDataStreamGenerator(); - - gen.addSigners(sp.getSignerInfos()); - - gen.addCertificatesAndCRLs(sp.getCertificatesAndCRLs("Collection", BC)); - - bOut.reset(); - - sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - CMSSignedData sd = new CMSSignedData(new CMSProcessableByteArray(TEST_MESSAGE.getBytes()), bOut.toByteArray()); - - assertEquals(1, sd.getSignerInfos().getSigners().size()); - - verifyEncodedData(bOut); - } - - public void testSHA1WithRSAEncapsulatedSubjectKeyID() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), CMSTestUtil.createSubjectKeyId(_origCert.getPublicKey()).getKeyIdentifier(), CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - CMSSignedDataParser sp = new CMSSignedDataParser(bOut.toByteArray()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - - byte[] contentDigest = (byte[])gen.getGeneratedDigests().get(CMSSignedGenerator.DIGEST_SHA1); - - AttributeTable table = ((SignerInformation)sp.getSignerInfos().getSigners().iterator().next()).getSignedAttributes(); - Attribute hash = table.get(CMSAttributes.messageDigest); - - assertTrue(MessageDigest.isEqual(contentDigest, ((ASN1OctetString)hash.getAttrValues().getObjectAt(0)).getOctets())); - - // - // try using existing signer - // - gen = new CMSSignedDataStreamGenerator(); - - gen.addSigners(sp.getSignerInfos()); - - gen.addCertificatesAndCRLs(sp.getCertificatesAndCRLs("Collection", BC)); - - bOut.reset(); - - sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - CMSSignedData sd = new CMSSignedData(new CMSProcessableByteArray(TEST_MESSAGE.getBytes()), bOut.toByteArray()); - - assertEquals(1, sd.getSignerInfos().getSigners().size()); - - verifyEncodedData(bOut); - } - - public void testAttributeGenerators() - throws Exception - { - final ASN1ObjectIdentifier dummyOid1 = new ASN1ObjectIdentifier("1.2.3"); - final ASN1ObjectIdentifier dummyOid2 = new ASN1ObjectIdentifier("1.2.3.4"); - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - CMSAttributeTableGenerator signedGen = new DefaultSignedAttributeTableGenerator() - { - public AttributeTable getAttributes(Map parameters) - { - Hashtable table = createStandardAttributeTable(parameters); - - DEROctetString val = new DEROctetString((byte[])parameters.get(CMSAttributeTableGenerator.DIGEST)); - Attribute attr = new Attribute(dummyOid1, new DERSet(val)); - - table.put(attr.getAttrType(), attr); - - return new AttributeTable(table); - } - }; - - CMSAttributeTableGenerator unsignedGen = new CMSAttributeTableGenerator() - { - public AttributeTable getAttributes(Map parameters) - { - DEROctetString val = new DEROctetString((byte[])parameters.get(CMSAttributeTableGenerator.SIGNATURE)); - Attribute attr = new Attribute(dummyOid2, new DERSet(val)); - - return new AttributeTable(new DERSet(attr)); - } - }; - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, signedGen, unsignedGen, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - CMSSignedDataParser sp = new CMSSignedDataParser(bOut.toByteArray()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - - // - // check attributes - // - SignerInformationStore signers = sp.getSignerInfos(); - - Collection c = signers.getSigners(); - Iterator it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - checkAttribute(signer.getContentDigest(), signer.getSignedAttributes().get(dummyOid1)); - checkAttribute(signer.getSignature(), signer.getUnsignedAttributes().get(dummyOid2)); - } - } - - private void checkAttribute(byte[] expected, Attribute attr) - { - DEROctetString value = (DEROctetString)attr.getAttrValues().getObjectAt(0); - - assertEquals(new DEROctetString(expected), value); - } - - public void testWithAttributeCertificate() - throws Exception - { - List certList = new ArrayList(); - - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - X509AttributeCertificate attrCert = CMSTestUtil.getAttributeCertificate(); - - X509Store store = X509Store.getInstance("AttributeCertificate/Collection", - new X509CollectionStoreParameters(Collections.singleton(attrCert)), BC); - - gen.addAttributeCertificates(store); - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - OutputStream sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - CMSSignedDataParser sp = new CMSSignedDataParser(bOut.toByteArray()); - - sp.getSignedContent().drain(); - - assertEquals(4, sp.getVersion()); - - store = sp.getAttributeCertificates("Collection", BC); - - Collection coll = store.getMatches(null); - - assertEquals(1, coll.size()); - - assertTrue(coll.contains(attrCert)); - } - - public void testSignerStoreReplacement() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - byte[] data = TEST_MESSAGE.getBytes(); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut, false); - - sigOut.write(data); - - sigOut.close(); - - checkSigParseable(bOut.toByteArray()); - - // - // create new Signer - // - ByteArrayInputStream original = new ByteArrayInputStream(bOut.toByteArray()); - - bOut.reset(); - - gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA224, BC); - - gen.addCertificatesAndCRLs(certs); - - sigOut = gen.open(bOut); - - sigOut.write(data); - - sigOut.close(); - - checkSigParseable(bOut.toByteArray()); - - CMSSignedData sd = new CMSSignedData(bOut.toByteArray()); - - // - // replace signer - // - ByteArrayOutputStream newOut = new ByteArrayOutputStream(); - - CMSSignedDataParser.replaceSigners(original, sd.getSignerInfos(), newOut); - - sd = new CMSSignedData(new CMSProcessableByteArray(data), newOut.toByteArray()); - SignerInformation signer = (SignerInformation)sd.getSignerInfos().getSigners().iterator().next(); - - assertEquals(signer.getDigestAlgOID(), CMSSignedDataStreamGenerator.DIGEST_SHA224); - - CMSSignedDataParser sp = new CMSSignedDataParser(new CMSTypedStream(new ByteArrayInputStream(data)), newOut.toByteArray()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - } - - public void testEncapsulatedSignerStoreReplacement() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - // - // create new Signer - // - ByteArrayInputStream original = new ByteArrayInputStream(bOut.toByteArray()); - - bOut.reset(); - - gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA224, BC); - - gen.addCertificatesAndCRLs(certs); - - sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - CMSSignedData sd = new CMSSignedData(bOut.toByteArray()); - - // - // replace signer - // - ByteArrayOutputStream newOut = new ByteArrayOutputStream(); - - CMSSignedDataParser.replaceSigners(original, sd.getSignerInfos(), newOut); - - sd = new CMSSignedData(newOut.toByteArray()); - SignerInformation signer = (SignerInformation)sd.getSignerInfos().getSigners().iterator().next(); - - assertEquals(signer.getDigestAlgOID(), CMSSignedDataStreamGenerator.DIGEST_SHA224); - - CMSSignedDataParser sp = new CMSSignedDataParser(newOut.toByteArray()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - } - - public void testCertStoreReplacement() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - byte[] data = TEST_MESSAGE.getBytes(); - - certList.add(_origDsaCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut); - - sigOut.write(data); - - sigOut.close(); - - checkSigParseable(bOut.toByteArray()); - - // - // create new certstore with the right certificates - // - certList = new ArrayList(); - certList.add(_origCert); - certList.add(_signCert); - - certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - // - // replace certs - // - ByteArrayInputStream original = new ByteArrayInputStream(bOut.toByteArray()); - ByteArrayOutputStream newOut = new ByteArrayOutputStream(); - - CMSSignedDataParser.replaceCertificatesAndCRLs(original, certs, newOut); - - CMSSignedDataParser sp = new CMSSignedDataParser(new CMSTypedStream(new ByteArrayInputStream(data)), newOut.toByteArray()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - } - - public void testEncapsulatedCertStoreReplacement() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_origDsaCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - // - // create new certstore with the right certificates - // - certList = new ArrayList(); - certList.add(_origCert); - certList.add(_signCert); - - certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - // - // replace certs - // - ByteArrayInputStream original = new ByteArrayInputStream(bOut.toByteArray()); - ByteArrayOutputStream newOut = new ByteArrayOutputStream(); - - CMSSignedDataParser.replaceCertificatesAndCRLs(original, certs, newOut); - - CMSSignedDataParser sp = new CMSSignedDataParser(newOut.toByteArray()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - } - - public void testCertOrdering1() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - CMSSignedDataParser sp = new CMSSignedDataParser(bOut.toByteArray()); - - sp.getSignedContent().drain(); - certs = sp.getCertificatesAndCRLs("Collection", BC); - Iterator it = certs.getCertificates(null).iterator(); - - assertEquals(_origCert, it.next()); - assertEquals(_signCert, it.next()); - } - - public void testCertOrdering2() - throws Exception - { - List certList = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - certList.add(_signCert); - certList.add(_origCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataStreamGenerator.DIGEST_SHA1, BC); - - gen.addCertificatesAndCRLs(certs); - - OutputStream sigOut = gen.open(bOut, true); - - sigOut.write(TEST_MESSAGE.getBytes()); - - sigOut.close(); - - CMSSignedDataParser sp = new CMSSignedDataParser(bOut.toByteArray()); - - sp.getSignedContent().drain(); - certs = sp.getCertificatesAndCRLs("Collection", BC); - Iterator it = certs.getCertificates(null).iterator(); - - assertEquals(_signCert, it.next()); - assertEquals(_origCert, it.next()); - } - - public static Test suite() - throws Exception - { - init(); - - return new CMSTestSetup(new TestSuite(SignedDataStreamTest.class)); - } -} diff --git a/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/SignedDataTest.java b/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/SignedDataTest.java deleted file mode 100644 index ef3f8de5..00000000 --- a/pkix/src/test/jdk1.3/org/bouncycastle/cms/test/SignedDataTest.java +++ /dev/null @@ -1,1573 +0,0 @@ -package org.bouncycastle.cms.test; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import org.bouncycastle.jce.cert.CertStore; -import org.bouncycastle.jce.cert.CollectionCertStoreParameters; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.cms.Attribute; -import org.bouncycastle.asn1.cms.AttributeTable; -import org.bouncycastle.asn1.cms.CMSAttributes; -import org.bouncycastle.asn1.cms.ContentInfo; -import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.cms.CMSConfig; -import org.bouncycastle.cms.CMSProcessable; -import org.bouncycastle.cms.CMSProcessableByteArray; -import org.bouncycastle.cms.CMSSignedData; -import org.bouncycastle.cms.CMSSignedDataGenerator; -import org.bouncycastle.cms.CMSSignedDataParser; -import org.bouncycastle.cms.SignerId; -import org.bouncycastle.cms.SignerInformation; -import org.bouncycastle.cms.SignerInformationStore; -import org.bouncycastle.cms.jcajce.JcaX509CertSelectorConverter; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.util.io.Streams; -import org.bouncycastle.x509.X509AttributeCertificate; -import org.bouncycastle.x509.X509CollectionStoreParameters; -import org.bouncycastle.x509.X509Store; - -public class SignedDataTest - extends TestCase -{ - private static final String BC = BouncyCastleProvider.PROVIDER_NAME; - - boolean DEBUG = true; - - private static String _origDN; - private static KeyPair _origKP; - private static X509Certificate _origCert; - - private static String _signDN; - private static KeyPair _signKP; - private static X509Certificate _signCert; - - private static KeyPair _signGostKP; - private static X509Certificate _signGostCert; - - private static KeyPair _signEcDsaKP; - private static X509Certificate _signEcDsaCert; - - private static KeyPair _signEcGostKP; - private static X509Certificate _signEcGostCert; - - private static KeyPair _signDsaKP; - private static X509Certificate _signDsaCert; - - private static String _reciDN; - private static KeyPair _reciKP; - private static X509Certificate _reciCert; - - private static X509CRL _signCrl; - - private static boolean _initialised = false; - - private byte[] disorderedMessage = Base64.decode( - "SU9fc3RkaW5fdXNlZABfX2xpYmNfc3RhcnRfbWFpbgBnZXRob3N0aWQAX19n" - + "bW9uX3M="); - - private byte[] disorderedSet = Base64.decode( - "MIIYXQYJKoZIhvcNAQcCoIIYTjCCGEoCAQExCzAJBgUrDgMCGgUAMAsGCSqG" - + "SIb3DQEHAaCCFqswggJUMIIBwKADAgECAgMMg6wwCgYGKyQDAwECBQAwbzEL" - + "MAkGA1UEBhMCREUxPTA7BgNVBAoUNFJlZ3VsaWVydW5nc2JlaMhvcmRlIGbI" - + "dXIgVGVsZWtvbW11bmlrYXRpb24gdW5kIFBvc3QxITAMBgcCggYBCgcUEwEx" - + "MBEGA1UEAxQKNFItQ0EgMTpQTjAiGA8yMDAwMDMyMjA5NDM1MFoYDzIwMDQw" - + "MTIxMTYwNDUzWjBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxpZXJ1" - + "bmdzYmVoyG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8bIyTm51azF6clEg0qeWNMKiiXbBXa+ph" - + "hTkGbXiLYvACZ6/MTJMJ1lcrjpRF7BXtYeYMcEF6znD4pxOqrtbf9z5hAgUA" - + "wAAAATAKBgYrJAMDAQIFAAOBgQB99BjSKlGPbMLQAgXlvA9jUsDNhpnVm3a1" - + "YkfxSqS/dbQlYkbOKvCxkPGA9NBxisBM8l1zFynVjJoy++aysRmcnLY/sHaz" - + "23BF2iU7WERy18H3lMBfYB6sXkfYiZtvQZcWaO48m73ZBySuiV3iXpb2wgs/" - + "Cs20iqroAWxwq/W/9jCCAlMwggG/oAMCAQICBDsFZ9UwCgYGKyQDAwECBQAw" - + "bzELMAkGA1UEBhMCREUxITAMBgcCggYBCgcUEwExMBEGA1UEAxQKNFItQ0Eg" - + "MTpQTjE9MDsGA1UEChQ0UmVndWxpZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxl" - + "a29tbXVuaWthdGlvbiB1bmQgUG9zdDAiGA8xOTk5MDEyMTE3MzUzNFoYDzIw" - + "MDQwMTIxMTYwMDAyWjBvMQswCQYDVQQGEwJERTE9MDsGA1UEChQ0UmVndWxp" - + "ZXJ1bmdzYmVoyG9yZGUgZsh1ciBUZWxla29tbXVuaWthdGlvbiB1bmQgUG9z" - + "dDEhMAwGBwKCBgEKBxQTATEwEQYDVQQDFAozUi1DQSAxOlBOMIGfMA0GCSqG" - + "SIb3DQEBAQUAA4GNADCBiQKBgI4B557mbKQg/AqWBXNJhaT/6lwV93HUl4U8" - + "u35udLq2+u9phns1WZkdM3gDfEpL002PeLfHr1ID/96dDYf04lAXQfombils" - + "of1C1k32xOvxjlcrDOuPEMxz9/HDAQZA5MjmmYHAIulGI8Qg4Tc7ERRtg/hd" - + "0QX0/zoOeXoDSEOBAgTAAAABMAoGBiskAwMBAgUAA4GBAIyzwfT3keHI/n2P" - + "LrarRJv96mCohmDZNpUQdZTVjGu5VQjVJwk3hpagU0o/t/FkdzAjOdfEw8Ql" - + "3WXhfIbNLv1YafMm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250cnVzdDE6" - + "UE4xEjAQBgNVBAoTCVNpZ250cnVzdDELMAkGA1UEBhMCREUwYgYIKwYBBQUH" - + "AQEEVjBUMFIGCCsGAQUFBzABhkZodHRwOi8vZGlyLnNpZ250cnVzdC5kZS9T" - + "aWdudHJ1c3QvT0NTUC9zZXJ2bGV0L2h0dHBHYXRld2F5LlBvc3RIYW5kbGVy" - + "MBgGCCsGAQUFBwEDBAwwCjAIBgYEAI5GAQEwDgYHAoIGAQoMAAQDAQH/MA0G" - + "CSqGSIb3DQEBBQUAA4GBAHn1m3GcoyD5GBkKUY/OdtD6Sj38LYqYCF+qDbJR" - + "6pqUBjY2wsvXepUppEler+stH8mwpDDSJXrJyuzf7xroDs4dkLl+Rs2x+2tg" - + "BjU+ABkBDMsym2WpwgA8LCdymmXmjdv9tULxY+ec2pjSEzql6nEZNEfrU8nt" - + "ZCSCavgqW4TtMYIBejCCAXYCAQEwUTBLMQswCQYDVQQGEwJERTESMBAGA1UE" - + "ChQJU2lnbnRydXN0MSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEUNBIFNJR05U" - + "UlVTVCAxOlBOAgJsxzAJBgUrDgMCGgUAoIGAMBgGCSqGSIb3DQEJAzELBgkq" - + "hkiG9w0BBwEwIwYJKoZIhvcNAQkEMRYEFIYfhPoyfGzkLWWSSLjaHb4HQmaK" - + "MBwGCSqGSIb3DQEJBTEPFw0wNTAzMjQwNzM4MzVaMCEGBSskCAYFMRgWFi92" - + "YXIvZmlsZXMvdG1wXzEvdGVzdDEwDQYJKoZIhvcNAQEFBQAEgYA2IvA8lhVz" - + "VD5e/itUxbFboKxeKnqJ5n/KuO/uBCl1N14+7Z2vtw1sfkIG+bJdp3OY2Cmn" - + "mrQcwsN99Vjal4cXVj8t+DJzFG9tK9dSLvD3q9zT/GQ0kJXfimLVwCa4NaSf" - + "Qsu4xtG0Rav6bCcnzabAkKuNNvKtH8amSRzk870DBg=="); - - public static byte[] xtraCounterSig = Base64.decode( - "MIIR/AY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i/E/Spk7LxVume" - + "2bNo8XnlVXhu4pXfkn64en3yBcqnQusczr1XkhEq7K5DMccUGqxfGxEj2joq" - + "g5+CWIP1dz4F4yB0rNCEGEFigVESryFAzSdJuoM0dgBDI0czNQD9lBQ7l2UW" - + "4fwPDeINgCE2190+uVyEom2E"); - - byte[] noSignedAttrSample2 = Base64.decode( - "MIIIlAYJKoZIhvcNAQcCoIIIhTCCCIECAQExCzAJBgUrDgMCGgUAMAsGCSqG" - + "SIb3DQEHAaCCB3UwggOtMIIDa6ADAgECAgEzMAsGByqGSM44BAMFADCBkDEL" - + "MAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRIwEAYDVQQHEwlQYWxvIEFsdG8x" - + "HTAbBgNVBAoTFFN1biBNaWNyb3N5c3RlbXMgSW5jMSMwIQYDVQQLExpKYXZh" - + "IFNvZnR3YXJlIENvZGUgU2lnbmluZzEcMBoGA1UEAxMTSkNFIENvZGUgU2ln" - + "bmluZyBDQTAeFw0wMTA1MjkxNjQ3MTFaFw0wNjA1MjgxNjQ3MTFaMG4xHTAb" - + "BgNVBAoTFFN1biBNaWNyb3N5c3RlbXMgSW5jMSMwIQYDVQQLExpKYXZhIFNv" - + "ZnR3YXJlIENvZGUgU2lnbmluZzEoMCYGA1UEAxMfVGhlIExlZ2lvbiBvZiB0" - + "aGUgQm91bmN5IENhc3RsZTCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQD9f1OB" - + "HXUSKVLfSpwu7OTn9hG3UjzvRADDHj+AtlEmaUVdQCJR+1k9jVj6v8X1ujD2" - + "y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7qdf+t8Yb+DtX58aophUP" - + "BPuD9tPFHsMCNVQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdgUI8VIwvM" - + "spK5gqLrhAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlXTAs9" - + "B4JnUVlXjrrUWU/mcQcQgYC0SRZxI+h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SBT" - + "aWduaW5nIENBAgEzMAkGBSsOAwIaBQAwCwYHKoZIzjgEAQUABC8wLQIVAIGV" - + "khm+kbV4a/+EP45PHcq0hIViAhR4M9os6IrJnoEDS3Y3l7O6zrSosA=="); - - private JcaX509CertSelectorConverter selectorConverter = new JcaX509CertSelectorConverter(); - - /* - * - * INFRASTRUCTURE - * - */ - - public SignedDataTest(String name) - { - super(name); - } - - public static void main(String args[]) - { - - junit.textui.TestRunner.run(SignedDataTest.class); - } - - public static Test suite() - throws Exception - { - init(); - - return new CMSTestSetup(new TestSuite(SignedDataTest.class)); - } - - private static void init() - throws Exception - { - if (!_initialised) - { - _initialised = true; - - _origDN = "O=Bouncy Castle, C=AU"; - _origKP = CMSTestUtil.makeKeyPair(); - _origCert = CMSTestUtil.makeCertificate(_origKP, _origDN, _origKP, _origDN); - - _signDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU"; - _signKP = CMSTestUtil.makeKeyPair(); - _signCert = CMSTestUtil.makeCertificate(_signKP, _signDN, _origKP, _origDN); - - _signGostKP = CMSTestUtil.makeGostKeyPair(); - _signGostCert = CMSTestUtil.makeCertificate(_signGostKP, _signDN, _origKP, _origDN); - - _signDsaKP = CMSTestUtil.makeDsaKeyPair(); - _signDsaCert = CMSTestUtil.makeCertificate(_signDsaKP, _signDN, _origKP, _origDN); - - _signEcDsaKP = CMSTestUtil.makeEcDsaKeyPair(); - _signEcDsaCert = CMSTestUtil.makeCertificate(_signEcDsaKP, _signDN, _origKP, _origDN); - - _signEcGostKP = CMSTestUtil.makeEcGostKeyPair(); - _signEcGostCert = CMSTestUtil.makeCertificate(_signEcGostKP, _signDN, _origKP, _origDN); - - _reciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU"; - _reciKP = CMSTestUtil.makeKeyPair(); - _reciCert = CMSTestUtil.makeCertificate(_reciKP, _reciDN, _signKP, _signDN); - - _signCrl = CMSTestUtil.makeCrl(_signKP); - } - } - - private void verifySignatures(CMSSignedData s, byte[] contentDigest) - throws Exception - { - CertStore certStore = s.getCertificatesAndCRLs("Collection", BC); - SignerInformationStore signers = s.getSignerInfos(); - - Collection c = signers.getSigners(); - Iterator it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certStore.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertEquals(true, signer.verify(cert, BC)); - - if (contentDigest != null) - { - assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest())); - } - } - - Collection certColl = certStore.getCertificates(null); - Collection crlColl = certStore.getCRLs(null); - - assertEquals(certColl.size(), s.getCertificates("Collection", BC).getMatches(null).size()); - assertEquals(crlColl.size(), s.getCRLs("Collection", BC).getMatches(null).size()); - } - - private void verifySignatures(CMSSignedData s) - throws Exception - { - verifySignatures(s, null); - } - - public void testDetachedVerification() - throws Exception - { - byte[] data = "Hello World!".getBytes(); - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray(data); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_MD5); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData s = gen.generate(msg, BC); - - MessageDigest sha1 = MessageDigest.getInstance("SHA1", BC); - MessageDigest md5 = MessageDigest.getInstance("MD5", BC); - Map hashes = new HashMap(); - byte[] sha1Hash = sha1.digest(data); - byte[] md5Hash = md5.digest(data); - - hashes.put(CMSSignedDataGenerator.DIGEST_SHA1, sha1Hash); - hashes.put(CMSSignedDataGenerator.DIGEST_MD5, md5Hash); - - s = new CMSSignedData(hashes, s.getEncoded()); - - verifySignatures(s, null); - } - - public void testSHA1AndMD5WithRSAEncapsulatedRepeated() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_MD5); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData s = gen.generate(msg, true, BC); - - ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); - ASN1InputStream aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); - - certs = s.getCertificatesAndCRLs("Collection", BC); - - SignerInformationStore signers = s.getSignerInfos(); - - assertEquals(2, signers.size()); - - Collection c = signers.getSigners(); - Iterator it = c.iterator(); - SignerId sid = null; - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certs.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - sid = signer.getSID(); - - assertEquals(true, signer.verify(cert, BC)); - - // - // check content digest - // - - byte[] contentDigest = (byte[])gen.getGeneratedDigests().get(signer.getDigestAlgOID()); - - AttributeTable table = signer.getSignedAttributes(); - Attribute hash = table.get(CMSAttributes.messageDigest); - - assertTrue(MessageDigest.isEqual(contentDigest, ((ASN1OctetString)hash.getAttrValues().getObjectAt(0)).getOctets())); - } - - c = signers.getSigners(sid); - - assertEquals(2, c.size()); - - - // - // try using existing signer - // - - gen = new CMSSignedDataGenerator(); - - gen.addSigners(s.getSignerInfos()); - - gen.addCertificatesAndCRLs(s.getCertificatesAndCRLs("Collection", BC)); - - s = gen.generate(msg, true, BC); - - bIn = new ByteArrayInputStream(s.getEncoded()); - aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); - - certs = s.getCertificatesAndCRLs("Collection", BC); - - signers = s.getSignerInfos(); - c = signers.getSigners(); - it = c.iterator(); - - assertEquals(2, c.size()); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certs.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertEquals(true, signer.verify(cert, BC)); - } - - checkSignerStoreReplacement(s, signers); - } - - public void testSHA1WithRSANoAttributes() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello world!".getBytes()); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData s = gen.generate(CMSSignedDataGenerator.DATA, msg, false, BC, false); - - // - // compute expected content digest - // - MessageDigest md = MessageDigest.getInstance("SHA1", BC); - - verifySignatures(s, md.digest("Hello world!".getBytes())); - } - - public void testSHA1WithRSAViaConfig() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello world!".getBytes()); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - // set some bogus mappings. - CMSConfig.setSigningEncryptionAlgorithmMapping(PKCSObjectIdentifiers.rsaEncryption.getId(), "XXXX"); - CMSConfig.setSigningDigestAlgorithmMapping(OIWObjectIdentifiers.idSHA1.getId(), "YYYY"); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData s; - - try - { - // try the bogus mappings - s = gen.generate(CMSSignedDataGenerator.DATA, msg, false, BC, false); - } - catch (NoSuchAlgorithmException e) - { - if (!e.getMessage().startsWith("Unknown signature type requested: YYYYWITHXXXX")) - { - throw e; - } - } - finally - { - // reset to the real ones - CMSConfig.setSigningEncryptionAlgorithmMapping(PKCSObjectIdentifiers.rsaEncryption.getId(), "RSA"); - CMSConfig.setSigningDigestAlgorithmMapping(OIWObjectIdentifiers.idSHA1.getId(), "SHA1"); - } - - s = gen.generate(CMSSignedDataGenerator.DATA, msg, false, BC, false); - - // - // compute expected content digest - // - MessageDigest md = MessageDigest.getInstance("SHA1", BC); - - verifySignatures(s, md.digest("Hello world!".getBytes())); - } - - public void testSHA1WithRSAAndAttributeTable() - throws Exception - { - MessageDigest md = MessageDigest.getInstance("SHA1", BC); - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello world!".getBytes()); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - Attribute attr = new Attribute(CMSAttributes.messageDigest, - new DERSet( - new DEROctetString( - md.digest("Hello world!".getBytes())))); - - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(attr); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1, new AttributeTable(v), null); - - gen.addCertificatesAndCRLs(certs); - - - CMSSignedData s = gen.generate(CMSSignedDataGenerator.DATA, null, false, BC); - - // - // the signature is detached, so need to add msg before passing on - // - s = new CMSSignedData(msg, s.getEncoded()); - // - // compute expected content digest - // - - verifySignatures(s, md.digest("Hello world!".getBytes())); - } - - public void testSHA1WithRSAEncapsulated() - throws Exception - { - encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_SHA1); - } - - public void testSHA1WithRSAEncapsulatedSubjectKeyID() - throws Exception - { - subjectKeyIDTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_SHA1); - } - - public void testSHA1WithRSAPSS() - throws Exception - { - rsaPSSTest("SHA1", CMSSignedDataGenerator.DIGEST_SHA1); - } - - public void testSHA224WithRSAPSS() - throws Exception - { - rsaPSSTest("SHA224", CMSSignedDataGenerator.DIGEST_SHA224); - } - - public void testSHA256WithRSAPSS() - throws Exception - { - rsaPSSTest("SHA256", CMSSignedDataGenerator.DIGEST_SHA256); - } - - public void testSHA384WithRSAPSS() - throws Exception - { - rsaPSSTest("SHA384", CMSSignedDataGenerator.DIGEST_SHA384); - } - - public void testSHA224WithRSAEncapsulated() - throws Exception - { - encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_SHA224); - } - - public void testSHA256WithRSAEncapsulated() - throws Exception - { - encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_SHA256); - } - - public void testRIPEMD128WithRSAEncapsulated() - throws Exception - { - encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_RIPEMD128); - } - - public void testRIPEMD160WithRSAEncapsulated() - throws Exception - { - encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_RIPEMD160); - } - - public void testRIPEMD256WithRSAEncapsulated() - throws Exception - { - encapsulatedTest(_signKP, _signCert, CMSSignedDataGenerator.DIGEST_RIPEMD256); - } - - public void testECDSAEncapsulated() - throws Exception - { - encapsulatedTest(_signEcDsaKP, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA1); - } - - public void testECDSAEncapsulatedSubjectKeyID() - throws Exception - { - subjectKeyIDTest(_signEcDsaKP, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA1); - } - - public void testECDSASHA224Encapsulated() - throws Exception - { - encapsulatedTest(_signEcDsaKP, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA224); - } - - public void testECDSASHA256Encapsulated() - throws Exception - { - encapsulatedTest(_signEcDsaKP, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA256); - } - - public void testECDSASHA384Encapsulated() - throws Exception - { - encapsulatedTest(_signEcDsaKP, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA384); - } - - public void testECDSASHA512Encapsulated() - throws Exception - { - encapsulatedTest(_signEcDsaKP, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA512); - } - - public void testECDSASHA512EncapsulatedWithKeyFactoryAsEC() - throws Exception - { - X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(_signEcDsaKP.getPublic().getEncoded()); - PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(_signEcDsaKP.getPrivate().getEncoded()); - KeyFactory keyFact = KeyFactory.getInstance("EC", BC); - KeyPair kp = new KeyPair(keyFact.generatePublic(pubSpec), keyFact.generatePrivate(privSpec)); - - encapsulatedTest(kp, _signEcDsaCert, CMSSignedDataGenerator.DIGEST_SHA512); - } - - public void testDSAEncapsulated() - throws Exception - { - encapsulatedTest(_signDsaKP, _signDsaCert, CMSSignedDataGenerator.DIGEST_SHA1); - } - - public void testDSAEncapsulatedSubjectKeyID() - throws Exception - { - subjectKeyIDTest(_signDsaKP, _signDsaCert, CMSSignedDataGenerator.DIGEST_SHA1); - } - - public void testGOST3411WithGOST3410Encapsulated() - throws Exception - { - encapsulatedTest(_signGostKP, _signGostCert, CMSSignedDataGenerator.DIGEST_GOST3411); - } - - public void testGOST3411WithECGOST3410Encapsulated() - throws Exception - { - encapsulatedTest(_signEcGostKP, _signEcGostCert, CMSSignedDataGenerator.DIGEST_GOST3411); - } - - public void testSHA1WithRSACounterSignature() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); - - certList.add(_signCert); - certList.add(_origCert); - - certList.add(_signCrl); - - CertStore certsAndCrls = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_signKP.getPrivate(), _signCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certsAndCrls); - - CMSSignedData s = gen.generate(msg, true, BC); - SignerInformation origSigner = (SignerInformation)s.getSignerInfos().getSigners().toArray()[0]; - SignerInformationStore counterSigners1 = gen.generateCounterSigners(origSigner, BC); - SignerInformationStore counterSigners2 = gen.generateCounterSigners(origSigner, BC); - - SignerInformation signer1 = SignerInformation.addCounterSigners(origSigner, counterSigners1); - SignerInformation signer2 = SignerInformation.addCounterSigners(signer1, counterSigners2); - - SignerInformationStore cs = signer2.getCounterSignatures(); - Collection csSigners = cs.getSigners(); - assertEquals(2, csSigners.size()); - - Iterator it = csSigners.iterator(); - while (it.hasNext()) - { - SignerInformation cSigner = (SignerInformation)it.next(); - Collection certCollection = certsAndCrls.getCertificates(selectorConverter.getCertSelector(cSigner.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertNull(cSigner.getSignedAttributes().get(PKCSObjectIdentifiers.pkcs_9_at_contentType)); - assertEquals(true, cSigner.verify(cert, BC)); - } - } - - private void rsaPSSTest(String digestName, String digestOID) - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello world!".getBytes()); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.ENCRYPTION_RSA_PSS, digestOID); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData s = gen.generate(CMSSignedDataGenerator.DATA, msg, false, BC, false); - - // - // compute expected content digest - // - MessageDigest md = MessageDigest.getInstance(digestName, BC); - - verifySignatures(s, md.digest("Hello world!".getBytes())); - } - - private void subjectKeyIDTest( - KeyPair signaturePair, - X509Certificate signatureCert, - String digestAlgorithm) - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); - - certList.add(signatureCert); - certList.add(_origCert); - - certList.add(_signCrl); - - CertStore certsAndCrls = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(signaturePair.getPrivate(), CMSTestUtil.createSubjectKeyId(signatureCert.getPublicKey()).getKeyIdentifier(), digestAlgorithm); - - gen.addCertificatesAndCRLs(certsAndCrls); - - CMSSignedData s = gen.generate(msg, true, BC); - - assertEquals(3, s.getVersion()); - - ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); - ASN1InputStream aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); - - certsAndCrls = s.getCertificatesAndCRLs("Collection", BC); - - SignerInformationStore signers = s.getSignerInfos(); - Collection c = signers.getSigners(); - Iterator it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certsAndCrls.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertEquals(true, signer.verify(cert, BC)); - } - - // - // check for CRLs - // - Collection crls = certsAndCrls.getCRLs(null); - - assertEquals(1, crls.size()); - - assertTrue(crls.contains(_signCrl)); - - // - // try using existing signer - // - - gen = new CMSSignedDataGenerator(); - - gen.addSigners(s.getSignerInfos()); - - gen.addCertificatesAndCRLs(s.getCertificatesAndCRLs("Collection", BC)); - - s = gen.generate(msg, true, BC); - - bIn = new ByteArrayInputStream(s.getEncoded()); - aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); - - certsAndCrls = s.getCertificatesAndCRLs("Collection", BC); - - signers = s.getSignerInfos(); - c = signers.getSigners(); - it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certsAndCrls.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertEquals(true, signer.verify(cert, BC)); - } - - checkSignerStoreReplacement(s, signers); - } - - private void encapsulatedTest( - KeyPair signaturePair, - X509Certificate signatureCert, - String digestAlgorithm) - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); - - certList.add(signatureCert); - certList.add(_origCert); - - certList.add(_signCrl); - - CertStore certsAndCrls = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(signaturePair.getPrivate(), signatureCert, digestAlgorithm); - - gen.addCertificatesAndCRLs(certsAndCrls); - - CMSSignedData s = gen.generate(msg, true, BC); - - ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); - ASN1InputStream aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); - - certsAndCrls = s.getCertificatesAndCRLs("Collection", BC); - - SignerInformationStore signers = s.getSignerInfos(); - Collection c = signers.getSigners(); - Iterator it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certsAndCrls.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertEquals(true, signer.verify(cert, BC)); - } - - // - // check for CRLs - // - Collection crls = certsAndCrls.getCRLs(null); - - assertEquals(1, crls.size()); - - assertTrue(crls.contains(_signCrl)); - - // - // try using existing signer - // - - gen = new CMSSignedDataGenerator(); - - gen.addSigners(s.getSignerInfos()); - - gen.addCertificatesAndCRLs(s.getCertificatesAndCRLs("Collection", BC)); - - s = gen.generate(msg, true, BC); - - bIn = new ByteArrayInputStream(s.getEncoded()); - aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); - - certsAndCrls = s.getCertificatesAndCRLs("Collection", BC); - - signers = s.getSignerInfos(); - c = signers.getSigners(); - it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certsAndCrls.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertEquals(true, signer.verify(cert, BC)); - } - - checkSignerStoreReplacement(s, signers); - } - - // - // signerInformation store replacement test. - // - private void checkSignerStoreReplacement( - CMSSignedData orig, - SignerInformationStore signers) - throws Exception - { - CMSSignedData s = CMSSignedData.replaceSigners(orig, signers); - - CertStore certs = s.getCertificatesAndCRLs("Collection", BC); - - signers = s.getSignerInfos(); - Collection c = signers.getSigners(); - Iterator it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certs.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertEquals(true, signer.verify(cert, BC)); - } - } - - public void testUnsortedAttributes() - throws Exception - { - CMSSignedData s = new CMSSignedData(new CMSProcessableByteArray(disorderedMessage), disorderedSet); - - CertStore certs = s.getCertificatesAndCRLs("Collection", BC); - - SignerInformationStore signers = s.getSignerInfos(); - Collection c = signers.getSigners(); - Iterator it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certs.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertEquals(true, signer.verify(cert, BC)); - } - } - - public void testNullContentWithSigner() - throws Exception - { - List certList = new ArrayList(); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData s = gen.generate(null, false, BC); - - ByteArrayInputStream bIn = new ByteArrayInputStream(s.getEncoded()); - ASN1InputStream aIn = new ASN1InputStream(bIn); - - s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); - - verifySignatures(s); - } - - public void testWithAttributeCertificate() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); - - - certList.add(_signDsaCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certs); - - X509AttributeCertificate attrCert = CMSTestUtil.getAttributeCertificate(); - - X509Store store = X509Store.getInstance("AttributeCertificate/Collection", - new X509CollectionStoreParameters(Collections.singleton(attrCert)), BC); - - gen.addAttributeCertificates(store); - - CMSSignedData sd = gen.generate(msg, BC); - - assertEquals(4, sd.getVersion()); - - store = sd.getAttributeCertificates("Collection", BC); - - Collection coll = store.getMatches(null); - - assertEquals(1, coll.size()); - - assertTrue(coll.contains(attrCert)); - - // - // create new certstore - // - certList = new ArrayList(); - certList.add(_origCert); - certList.add(_signCert); - - certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - - // - // replace certs - // - sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs); - - verifySignatures(sd); - } - - public void testCertStoreReplacement() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); - - - certList.add(_signDsaCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData sd = gen.generate(msg, BC); - - // - // create new certstore - // - certList = new ArrayList(); - certList.add(_origCert); - certList.add(_signCert); - - certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - // - // replace certs - // - sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs); - - verifySignatures(sd); - } - - public void testEncapsulatedCertStoreReplacement() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); - - - certList.add(_signDsaCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData sd = gen.generate(msg, true, BC); - - // - // create new certstore - // - certList = new ArrayList(); - certList.add(_origCert); - certList.add(_signCert); - - certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - // - // replace certs - // - sd = CMSSignedData.replaceCertificatesAndCRLs(sd, certs); - - verifySignatures(sd); - } - - public void testCertOrdering1() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); - - certList.add(_origCert); - certList.add(_signCert); - certList.add(_signDsaCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData sd = gen.generate(msg, true, BC); - - certs = sd.getCertificatesAndCRLs("Collection", BC); - Iterator it = certs.getCertificates(null).iterator(); - - assertEquals(_origCert, it.next()); - assertEquals(_signCert, it.next()); - assertEquals(_signDsaCert, it.next()); - } - - public void testCertOrdering2() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); - - certList.add(_signCert); - certList.add(_signDsaCert); - certList.add(_origCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData sd = gen.generate(msg, true, BC); - - certs = sd.getCertificatesAndCRLs("Collection", BC); - Iterator it = certs.getCertificates(null).iterator(); - - assertEquals(_signCert, it.next()); - assertEquals(_signDsaCert, it.next()); - assertEquals(_origCert, it.next()); - } - - public void testSignerStoreReplacement() - throws Exception - { - List certList = new ArrayList(); - CMSProcessable msg = new CMSProcessableByteArray("Hello World!".getBytes()); - - certList.add(_origCert); - certList.add(_signCert); - - CertStore certs = CertStore.getInstance("Collection", - new CollectionCertStoreParameters(certList), BC); - - CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA1); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData original = gen.generate(msg, true, BC); - - // - // create new Signer - // - gen = new CMSSignedDataGenerator(); - - gen.addSigner(_origKP.getPrivate(), _origCert, CMSSignedDataGenerator.DIGEST_SHA224); - - gen.addCertificatesAndCRLs(certs); - - CMSSignedData newSD = gen.generate(msg, true, BC); - - // - // replace signer - // - CMSSignedData sd = CMSSignedData.replaceSigners(original, newSD.getSignerInfos()); - - SignerInformation signer = (SignerInformation)sd.getSignerInfos().getSigners().iterator().next(); - - assertEquals(CMSSignedDataGenerator.DIGEST_SHA224, signer.getDigestAlgOID()); - - // we use a parser here as it requires the digests to be correct in the digest set, if it - // isn't we'll get a NullPointerException - CMSSignedDataParser sp = new CMSSignedDataParser(sd.getEncoded()); - - sp.getSignedContent().drain(); - - verifySignatures(sp); - } - - public void testEncapsulatedSamples() - throws Exception - { - testSample("PSSSignDataSHA1Enc.sig"); - testSample("PSSSignDataSHA256Enc.sig"); - testSample("PSSSignDataSHA512Enc.sig"); - } - - public void testSamples() - throws Exception - { - testSample("PSSSignData.data", "PSSSignDataSHA1.sig"); - testSample("PSSSignData.data", "PSSSignDataSHA256.sig"); - testSample("PSSSignData.data", "PSSSignDataSHA512.sig"); - } - - public void testCounterSig() - throws Exception - { - CMSSignedData sig = new CMSSignedData(getInput("counterSig.p7m")); - - SignerInformationStore ss = sig.getSignerInfos(); - Collection signers = ss.getSigners(); - - SignerInformationStore cs = ((SignerInformation)signers.iterator().next()).getCounterSignatures(); - Collection csSigners = cs.getSigners(); - assertEquals(1, csSigners.size()); - - Iterator it = csSigners.iterator(); - while (it.hasNext()) - { - SignerInformation cSigner = (SignerInformation)it.next(); - Collection certCollection = sig.getCertificatesAndCRLs("Collection", BC).getCertificates(selectorConverter.getCertSelector(cSigner.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertNull(cSigner.getSignedAttributes().get(PKCSObjectIdentifiers.pkcs_9_at_contentType)); - assertEquals(true, cSigner.verify(cert, BC)); - } - - verifySignatures(sig); - } - - private void testSample(String sigName) - throws Exception - { - CMSSignedData sig = new CMSSignedData(getInput(sigName)); - - verifySignatures(sig); - } - - private void testSample(String messageName, String sigName) - throws Exception - { - CMSSignedData sig = new CMSSignedData(new CMSProcessableByteArray(getInput(messageName)), getInput(sigName)); - - verifySignatures(sig); - } - - private byte[] getInput(String name) - throws IOException - { - return Streams.readAll(getClass().getResourceAsStream(name)); - } - - public void testForMultipleCounterSignatures() - throws Exception - { - CMSSignedData sd = new CMSSignedData(xtraCounterSig); - - for (Iterator sI = sd.getSignerInfos().getSigners().iterator(); sI.hasNext();) - { - SignerInformation sigI = (SignerInformation)sI.next(); - - SignerInformationStore counter = sigI.getCounterSignatures(); - List sigs = new ArrayList(counter.getSigners()); - - assertEquals(2, sigs.size()); - } - } - - private void verifySignatures(CMSSignedDataParser sp) - throws Exception - { - CertStore certs = sp.getCertificatesAndCRLs("Collection", BC); - SignerInformationStore signers = sp.getSignerInfos(); - - Collection c = signers.getSigners(); - Iterator it = c.iterator(); - - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - Collection certCollection = certs.getCertificates(selectorConverter.getCertSelector(signer.getSID())); - - Iterator certIt = certCollection.iterator(); - X509Certificate cert = (X509Certificate)certIt.next(); - - assertEquals(true, signer.verify(cert, BC)); - } - } -} diff --git a/pkix/src/test/jdk1.3/org/bouncycastle/openssl/test/ReaderTest.java b/pkix/src/test/jdk1.3/org/bouncycastle/openssl/test/ReaderTest.java deleted file mode 100644 index 54f9d046..00000000 --- a/pkix/src/test/jdk1.3/org/bouncycastle/openssl/test/ReaderTest.java +++ /dev/null @@ -1,323 +0,0 @@ -package org.bouncycastle.openssl.test; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.Security; -import java.security.Signature; -import java.security.interfaces.DSAPrivateKey; -import java.security.interfaces.RSAPrivateKey; - -import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; -import org.bouncycastle.asn1.cms.ContentInfo; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; -import org.bouncycastle.openssl.PEMWriter; -import org.bouncycastle.openssl.PasswordFinder; -import org.bouncycastle.util.test.SimpleTest; - -/** - * basic class for reading test.pem - the password is "secret" - */ -public class ReaderTest - extends SimpleTest -{ - private static class Password - implements PasswordFinder - { - char[] password; - - Password( - char[] word) - { - this.password = word; - } - - public char[] getPassword() - { - return password; - } - } - - public String getName() - { - return "PEMReaderTest"; - } - - private PEMReader openPEMResource( - String fileName, - PasswordFinder pGet) - { - InputStream res = this.getClass().getResourceAsStream(fileName); - Reader fRd = new BufferedReader(new InputStreamReader(res)); - return new PEMReader(fRd, pGet); - } - - public void performTest() - throws Exception - { - PasswordFinder pGet = new Password("secret".toCharArray()); - PEMReader pemRd = openPEMResource("test.pem", pGet); - Object o; - KeyPair pair; - - while ((o = pemRd.readObject()) != null) - { - if (o instanceof KeyPair) - { - //pair = (KeyPair)o; - - //System.out.println(pair.getPublic()); - //System.out.println(pair.getPrivate()); - } - else - { - //System.out.println(o.toString()); - } - } - - // - // pkcs 7 data - // - pemRd = openPEMResource("pkcs7.pem", null); - ContentInfo d = (ContentInfo)pemRd.readObject(); - - if (!d.getContentType().equals(CMSObjectIdentifiers.envelopedData)) - { - fail("failed envelopedData check"); - } - - // - // ECKey - // - pemRd = openPEMResource("eckey.pem", null); - ECNamedCurveParameterSpec spec = (ECNamedCurveParameterSpec)pemRd.readObject(); - - pair = (KeyPair)pemRd.readObject(); - Signature sgr = Signature.getInstance("ECDSA", "BC"); - - sgr.initSign(pair.getPrivate()); - - byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; - - sgr.update(message); - - byte[] sigBytes = sgr.sign(); - - sgr.initVerify(pair.getPublic()); - - sgr.update(message); - - if (!sgr.verify(sigBytes)) - { - fail("EC verification failed"); - } - - if (!pair.getPublic().getAlgorithm().equals("ECDSA")) - { - fail("wrong algorithm name on public got: " + pair.getPublic().getAlgorithm()); - } - - if (!pair.getPrivate().getAlgorithm().equals("ECDSA")) - { - fail("wrong algorithm name on private"); - } - - // - // writer/parser test - // - KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); - - pair = kpGen.generateKeyPair(); - - keyPairTest("RSA", pair); - - kpGen = KeyPairGenerator.getInstance("DSA", "BC"); - kpGen.initialize(512, new SecureRandom()); - pair = kpGen.generateKeyPair(); - - keyPairTest("DSA", pair); - - // - // PKCS7 - // - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - PEMWriter pWrt = new PEMWriter(new OutputStreamWriter(bOut)); - - pWrt.writeObject(d); - - pWrt.close(); - - pemRd = new PEMReader(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray()))); - d = (ContentInfo)pemRd.readObject(); - - if (!d.getContentType().equals(CMSObjectIdentifiers.envelopedData)) - { - fail("failed envelopedData recode check"); - } - - - // OpenSSL test cases (as embedded resources) - doOpenSslDsaTest("unencrypted"); - doOpenSslRsaTest("unencrypted"); - - doOpenSslTests("aes128"); - doOpenSslTests("aes192"); - doOpenSslTests("aes256"); - doOpenSslTests("blowfish"); - doOpenSslTests("des1"); - doOpenSslTests("des2"); - doOpenSslTests("des3"); - doOpenSslTests("rc2_128"); - - doOpenSslDsaTest("rc2_40_cbc"); - doOpenSslRsaTest("rc2_40_cbc"); - doOpenSslDsaTest("rc2_64_cbc"); - doOpenSslRsaTest("rc2_64_cbc"); - - // heap space check - a failure by the ASN.1 library to detect an - // out of band stream will cause this to run out of memory. - try - { - pGet = new Password("7fd98".toCharArray()); - - pemRd = openPEMResource("test.pem", pGet); - - while ((o = pemRd.readObject()) != null) - { - } - fail("bounds issue not detected"); - } - catch (IOException e) - { - } - } - - private void keyPairTest( - String name, - KeyPair pair) - throws IOException - { - PEMReader pemRd; - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - PEMWriter pWrt = new PEMWriter(new OutputStreamWriter(bOut)); - - pWrt.writeObject(pair.getPublic()); - - pWrt.close(); - - pemRd = new PEMReader(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray()))); - - PublicKey k = (PublicKey)pemRd.readObject(); - if (!k.equals(pair.getPublic())) - { - fail("Failed public key read: " + name); - } - - bOut = new ByteArrayOutputStream(); - pWrt = new PEMWriter(new OutputStreamWriter(bOut)); - - pWrt.writeObject(pair.getPrivate()); - - pWrt.close(); - - pemRd = new PEMReader(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray()))); - - KeyPair kPair = (KeyPair)pemRd.readObject(); - if (!kPair.getPrivate().equals(pair.getPrivate())) - { - fail("Failed private key read: " + name); - } - - if (!kPair.getPublic().equals(pair.getPublic())) - { - fail("Failed private key public read: " + name); - } - } - - private void doOpenSslTests( - String baseName) - throws IOException - { - doOpenSslDsaModesTest(baseName); - doOpenSslRsaModesTest(baseName); - } - - private void doOpenSslDsaModesTest( - String baseName) - throws IOException - { - doOpenSslDsaTest(baseName + "_cbc"); - doOpenSslDsaTest(baseName + "_cfb"); - doOpenSslDsaTest(baseName + "_ecb"); - doOpenSslDsaTest(baseName + "_ofb"); - } - - private void doOpenSslRsaModesTest( - String baseName) - throws IOException - { - doOpenSslRsaTest(baseName + "_cbc"); - doOpenSslRsaTest(baseName + "_cfb"); - doOpenSslRsaTest(baseName + "_ecb"); - doOpenSslRsaTest(baseName + "_ofb"); - } - - private void doOpenSslDsaTest( - String name) - throws IOException - { - String fileName = "dsa/openssl_dsa_" + name + ".pem"; - - doOpenSslTestFile(fileName, DSAPrivateKey.class); - } - - private void doOpenSslRsaTest( - String name) - throws IOException - { - String fileName = "rsa/openssl_rsa_" + name + ".pem"; - - doOpenSslTestFile(fileName, RSAPrivateKey.class); - } - - private void doOpenSslTestFile( - String fileName, - Class expectedPrivKeyClass) - throws IOException - { - PEMReader pr = openPEMResource("data/" + fileName, new Password("changeit".toCharArray())); - Object o = pr.readObject(); - - if (o == null || !(o instanceof KeyPair)) - { - fail("Didn't find OpenSSL key"); - } - - KeyPair kp = (KeyPair) o; - PrivateKey privKey = kp.getPrivate(); - - if (!expectedPrivKeyClass.isInstance(privKey)) - { - fail("Returned key not of correct type"); - } - } - - public static void main( - String[] args) - { - Security.addProvider(new BouncyCastleProvider()); - - runTest(new ReaderTest()); - } -} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/rsa/BCRSAPublicKey.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/rsa/BCRSAPublicKey.java index a2114fa4..6f5292ce 100644 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/rsa/BCRSAPublicKey.java +++ b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/rsa/BCRSAPublicKey.java @@ -1,5 +1,6 @@ package org.bouncycastle.jcajce.provider.asymmetric.rsa; +import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -156,6 +157,10 @@ public class BCRSAPublicKey { algorithmIdentifier = DEFAULT_ALGORITHM_IDENTIFIER; } + catch (EOFException e) + { + algorithmIdentifier = DEFAULT_ALGORITHM_IDENTIFIER; + } } private void writeObject( diff --git a/prov/src/main/jdk1.1/org/bouncycastle/ocsp/OCSPUtil.java b/prov/src/main/jdk1.1/org/bouncycastle/ocsp/OCSPUtil.java deleted file mode 100644 index f6d4bace..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/ocsp/OCSPUtil.java +++ /dev/null @@ -1,198 +0,0 @@ -package org.bouncycastle.ocsp; - -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.util.Strings; - -import java.security.InvalidAlgorithmParameterException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Signature; -import java.security.cert.CertStore; -import java.security.cert.CertStoreParameters; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -class OCSPUtil -{ - private static Hashtable algorithms = new Hashtable(); - private static Hashtable oids = new Hashtable(); - private static Set noParams = new HashSet(); - - static - { - algorithms.put("MD2WITHRSAENCRYPTION", PKCSObjectIdentifiers.md2WithRSAEncryption); - algorithms.put("MD2WITHRSA", PKCSObjectIdentifiers.md2WithRSAEncryption); - algorithms.put("MD5WITHRSAENCRYPTION", PKCSObjectIdentifiers.md5WithRSAEncryption); - algorithms.put("MD5WITHRSA", PKCSObjectIdentifiers.md5WithRSAEncryption); - algorithms.put("SHA1WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha1WithRSAEncryption); - algorithms.put("SHA1WITHRSA", PKCSObjectIdentifiers.sha1WithRSAEncryption); - algorithms.put("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA256WITHRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA384WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA384WITHRSA", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA512WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("SHA512WITHRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("SHA1WITHDSA", X9ObjectIdentifiers.id_dsa_with_sha1); - algorithms.put("DSAWITHSHA1", X9ObjectIdentifiers.id_dsa_with_sha1); - algorithms.put("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224); - algorithms.put("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256); - algorithms.put("SHA1WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("ECDSAWITHSHA1", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("SHA224WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); - algorithms.put("SHA256WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); - algorithms.put("SHA384WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); - algorithms.put("SHA512WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); - algorithms.put("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - algorithms.put("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - - oids.put(PKCSObjectIdentifiers.md2WithRSAEncryption, "MD2WITHRSA"); - oids.put(PKCSObjectIdentifiers.md5WithRSAEncryption, "MD5WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha1WithRSAEncryption, "SHA1WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); - oids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160, "RIPEMD160WITHRSA"); - oids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128, "RIPEMD128WITHRSA"); - oids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256, "RIPEMD256WITHRSA"); - oids.put(X9ObjectIdentifiers.id_dsa_with_sha1, "SHA1WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA1, "SHA1WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); - oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410"); - - // - // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field. - // The parameters field SHALL be NULL for RSA based signature algorithms. - // - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA1); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA224); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA256); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA384); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA512); - noParams.add(X9ObjectIdentifiers.id_dsa_with_sha1); - noParams.add(NISTObjectIdentifiers.dsa_with_sha224); - noParams.add(NISTObjectIdentifiers.dsa_with_sha256); - } - - static ASN1ObjectIdentifier getAlgorithmOID( - String algorithmName) - { - algorithmName = Strings.toUpperCase(algorithmName); - - if (algorithms.containsKey(algorithmName)) - { - return (ASN1ObjectIdentifier)algorithms.get(algorithmName); - } - - return new ASN1ObjectIdentifier(algorithmName); - } - - static String getAlgorithmName( - ASN1ObjectIdentifier oid) - { - if (oids.containsKey(oid)) - { - return (String)oids.get(oid); - } - - return oid.getId(); - } - - static AlgorithmIdentifier getSigAlgID( - ASN1ObjectIdentifier sigOid) - { - if (noParams.contains(sigOid)) - { - return new AlgorithmIdentifier(sigOid); - } - else - { - return new AlgorithmIdentifier(sigOid, new DERNull()); - } - } - - static Iterator getAlgNames() - { - Enumeration e = algorithms.keys(); - List l = new ArrayList(); - - while (e.hasMoreElements()) - { - l.add(e.nextElement()); - } - - return l.iterator(); - } - - static CertStore createCertStoreInstance(String type, CertStoreParameters params, String provider) - throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException - { - if (provider == null) - { - return CertStore.getInstance(type, params); - } - - return CertStore.getInstance(type, params, provider); - } - - static MessageDigest createDigestInstance(String digestName, String provider) - throws NoSuchAlgorithmException, NoSuchProviderException - { - if (provider == null) - { - return MessageDigest.getInstance(digestName); - } - - return MessageDigest.getInstance(digestName, provider); - } - - static Signature createSignatureInstance(String sigName, String provider) - throws NoSuchAlgorithmException, NoSuchProviderException - { - if (provider == null) - { - return Signature.getInstance(sigName); - } - - return Signature.getInstance(sigName, provider); - } - - static CertificateFactory createX509CertificateFactory(String provider) - throws CertificateException, NoSuchProviderException - { - if (provider == null) - { - return CertificateFactory.getInstance("X.509"); - } - - return CertificateFactory.getInstance("X.509", provider); - } -} diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java index b3dcb66d..e0bab367 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java @@ -71,6 +71,8 @@ import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.jcajce.provider.symmetric.util.BCPBEKey; import org.bouncycastle.jcajce.provider.util.SecretKeyUtil; import org.bouncycastle.jce.interfaces.BCKeyStore; @@ -188,10 +190,9 @@ public class PKCS12KeyStoreSpi { try { - SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( - (ASN1Sequence)ASN1Primitive.fromByteArray(pubKey.getEncoded())); + SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); - return new SubjectKeyIdentifier(info); + return new SubjectKeyIdentifier(getDigest(info)); } catch (Exception e) { @@ -199,6 +200,17 @@ public class PKCS12KeyStoreSpi } } + private static byte[] getDigest(SubjectPublicKeyInfo spki) + { + Digest digest = new SHA1Digest(); + byte[] resBuf = new byte[digest.getDigestSize()]; + + byte[] bytes = spki.getPublicKeyData().getBytes(); + digest.update(bytes, 0, bytes.length); + digest.doFinal(resBuf, 0); + return resBuf; + } + public void setRandom( SecureRandom rand) { diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/ProviderJcaJceHelper.java b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/util/ProviderJcaJceHelper.java index 8ae736e9..abd94d36 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jcajce/ProviderJcaJceHelper.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jcajce/util/ProviderJcaJceHelper.java @@ -1,4 +1,4 @@ -package org.bouncycastle.jcajce; +package org.bouncycastle.jcajce.util; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/X509CertSelector.java b/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/X509CertSelector.java index f7745951..5f51f29e 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/X509CertSelector.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jce/cert/X509CertSelector.java @@ -27,6 +27,7 @@ import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DERGeneralizedTime; +import org.bouncycastle.asn1.ASN1GeneralizedTime; import org.bouncycastle.asn1.DEROutputStream; import org.bouncycastle.asn1.util.ASN1Dump; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/JDKPKCS12KeyStore.java b/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/JDKPKCS12KeyStore.java deleted file mode 100644 index 48776dcc..00000000 --- a/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/JDKPKCS12KeyStore.java +++ /dev/null @@ -1,1586 +0,0 @@ -package org.bouncycastle.jce.provider; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.Key; -import java.security.KeyStoreException; -import java.security.KeyStoreSpi; -import java.security.NoSuchAlgorithmException; -import java.security.Principal; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.UnrecoverableKeyException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Vector; - -import javax.crypto.Cipher; -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.PBEParameterSpec; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1Set; -import org.bouncycastle.asn1.BERConstructedOctetString; -import org.bouncycastle.asn1.BEROutputStream; -import org.bouncycastle.asn1.DERBMPString; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DEROutputStream; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.pkcs.AuthenticatedSafe; -import org.bouncycastle.asn1.pkcs.CertBag; -import org.bouncycastle.asn1.pkcs.ContentInfo; -import org.bouncycastle.asn1.pkcs.EncryptedData; -import org.bouncycastle.asn1.pkcs.MacData; -import org.bouncycastle.asn1.pkcs.PKCS12PBEParams; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.Pfx; -import org.bouncycastle.asn1.pkcs.SafeBag; -import org.bouncycastle.asn1.util.ASN1Dump; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; -import org.bouncycastle.asn1.x509.DigestInfo; -import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.asn1.x509.X509Extensions; -import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; -import org.bouncycastle.jcajce.provider.symmetric.util.BCPBEKey; -import org.bouncycastle.jce.interfaces.BCKeyStore; -import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.Strings; -import org.bouncycastle.util.encoders.Hex; - -public class JDKPKCS12KeyStore - extends KeyStoreSpi - implements PKCSObjectIdentifiers, X509ObjectIdentifiers, BCKeyStore -{ - private static final int SALT_SIZE = 20; - private static final int MIN_ITERATIONS = 1024; - - private IgnoresCaseHashtable keys = new IgnoresCaseHashtable(); - private Hashtable localIds = new Hashtable(); - private IgnoresCaseHashtable certs = new IgnoresCaseHashtable(); - private Hashtable chainCerts = new Hashtable(); - private Hashtable keyCerts = new Hashtable(); - - private static final String bcProvider = "BC"; - - // - // generic object types - // - static final int NULL = 0; - static final int CERTIFICATE = 1; - static final int KEY = 2; - static final int SECRET = 3; - static final int SEALED = 4; - - // - // key types - // - static final int KEY_PRIVATE = 0; - static final int KEY_PUBLIC = 1; - static final int KEY_SECRET = 2; - - protected SecureRandom random = new SecureRandom(); - - // use of final causes problems with JDK 1.2 compiler - private CertificateFactory certFact; - private ASN1ObjectIdentifier keyAlgorithm; - private ASN1ObjectIdentifier certAlgorithm; - - private class CertId - { - byte[] id; - - CertId( - PublicKey key) - { - this.id = createSubjectKeyId(key).getKeyIdentifier(); - } - - CertId( - byte[] id) - { - this.id = id; - } - - public int hashCode() - { - return Arrays.hashCode(id); - } - - public boolean equals( - Object o) - { - if (o == this) - { - return true; - } - - if (!(o instanceof CertId)) - { - return false; - } - - CertId cId = (CertId)o; - - return Arrays.areEqual(id, cId.id); - } - } - - public JDKPKCS12KeyStore( - String provider, - ASN1ObjectIdentifier keyAlgorithm, - ASN1ObjectIdentifier certAlgorithm) - { - this.keyAlgorithm = keyAlgorithm; - this.certAlgorithm = certAlgorithm; - - try - { - if (provider != null) - { - certFact = CertificateFactory.getInstance("X.509", provider); - } - else - { - certFact = CertificateFactory.getInstance("X.509"); - } - } - catch (Exception e) - { - throw new IllegalArgumentException("can't create cert factory - " + e.toString()); - } - } - - private SubjectKeyIdentifier createSubjectKeyId( - PublicKey pubKey) - { - try - { - SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( - (ASN1Sequence) ASN1Primitive.fromByteArray(pubKey.getEncoded())); - - return new SubjectKeyIdentifier(info); - } - catch (Exception e) - { - throw new RuntimeException("error creating key"); - } - } - - public void setRandom( - SecureRandom rand) - { - this.random = rand; - } - - public Enumeration engineAliases() - { - Hashtable tab = new Hashtable(); - - Enumeration e = certs.keys(); - while (e.hasMoreElements()) - { - tab.put(e.nextElement(), "cert"); - } - - e = keys.keys(); - while (e.hasMoreElements()) - { - String a = (String)e.nextElement(); - if (tab.get(a) == null) - { - tab.put(a, "key"); - } - } - - return tab.keys(); - } - - public boolean engineContainsAlias( - String alias) - { - return (certs.get(alias) != null || keys.get(alias) != null); - } - - /** - * this is not quite complete - we should follow up on the chain, a bit - * tricky if a certificate appears in more than one chain... - */ - public void engineDeleteEntry( - String alias) - throws KeyStoreException - { - Key k = (Key)keys.remove(alias); - - Certificate c = (Certificate)certs.remove(alias); - - if (c != null) - { - chainCerts.remove(new CertId(c.getPublicKey())); - } - - if (k != null) - { - String id = (String)localIds.remove(alias); - if (id != null) - { - c = (Certificate)keyCerts.remove(id); - } - if (c != null) - { - chainCerts.remove(new CertId(c.getPublicKey())); - } - } - - if (c == null && k == null) - { - throw new KeyStoreException("no such entry as " + alias); - } - } - - /** - * simply return the cert for the private key - */ - public Certificate engineGetCertificate( - String alias) - { - if (alias == null) - { - throw new IllegalArgumentException("null alias passed to getCertificate."); - } - - Certificate c = (Certificate)certs.get(alias); - - // - // look up the key table - and try the local key id - // - if (c == null) - { - String id = (String)localIds.get(alias); - if (id != null) - { - c = (Certificate)keyCerts.get(id); - } - else - { - c = (Certificate)keyCerts.get(alias); - } - } - - return c; - } - - public String engineGetCertificateAlias( - Certificate cert) - { - Enumeration c = certs.elements(); - Enumeration k = certs.keys(); - - while (c.hasMoreElements()) - { - Certificate tc = (Certificate)c.nextElement(); - String ta = (String)k.nextElement(); - - if (tc.equals(cert)) - { - return ta; - } - } - - c = keyCerts.elements(); - k = keyCerts.keys(); - - while (c.hasMoreElements()) - { - Certificate tc = (Certificate)c.nextElement(); - String ta = (String)k.nextElement(); - - if (tc.equals(cert)) - { - return ta; - } - } - - return null; - } - - public Certificate[] engineGetCertificateChain( - String alias) - { - if (alias == null) - { - throw new IllegalArgumentException("null alias passed to getCertificateChain."); - } - - if (!engineIsKeyEntry(alias)) - { - return null; - } - - Certificate c = engineGetCertificate(alias); - - if (c != null) - { - Vector cs = new Vector(); - - while (c != null) - { - X509Certificate x509c = (X509Certificate)c; - Certificate nextC = null; - - byte[] bytes = x509c.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); - if (bytes != null) - { - try - { - ASN1InputStream aIn = new ASN1InputStream(bytes); - - byte[] authBytes = ((ASN1OctetString)aIn.readObject()).getOctets(); - aIn = new ASN1InputStream(authBytes); - - AuthorityKeyIdentifier id = AuthorityKeyIdentifier.getInstance(aIn.readObject()); - if (id.getKeyIdentifier() != null) - { - nextC = (Certificate)chainCerts.get(new CertId(id.getKeyIdentifier())); - } - - } - catch (IOException e) - { - throw new RuntimeException(e.toString()); - } - } - - if (nextC == null) - { - // - // no authority key id, try the Issuer DN - // - Principal i = x509c.getIssuerDN(); - Principal s = x509c.getSubjectDN(); - - if (!i.equals(s)) - { - Enumeration e = chainCerts.keys(); - - while (e.hasMoreElements()) - { - X509Certificate crt = (X509Certificate)chainCerts.get(e.nextElement()); - Principal sub = crt.getSubjectDN(); - if (sub.equals(i)) - { - try - { - x509c.verify(crt.getPublicKey()); - nextC = crt; - break; - } - catch (Exception ex) - { - // continue - } - } - } - } - } - - cs.addElement(c); - if (nextC != c) // self signed - end of the chain - { - c = nextC; - } - else - { - c = null; - } - } - - Certificate[] certChain = new Certificate[cs.size()]; - - for (int i = 0; i != certChain.length; i++) - { - certChain[i] = (Certificate)cs.elementAt(i); - } - - return certChain; - } - - return null; - } - - public Date engineGetCreationDate(String alias) - { - return new Date(); - } - - public Key engineGetKey( - String alias, - char[] password) - throws NoSuchAlgorithmException, UnrecoverableKeyException - { - if (alias == null) - { - throw new IllegalArgumentException("null alias passed to getKey."); - } - - return (Key)keys.get(alias); - } - - public boolean engineIsCertificateEntry( - String alias) - { - return (certs.get(alias) != null && keys.get(alias) == null); - } - - public boolean engineIsKeyEntry( - String alias) - { - return (keys.get(alias) != null); - } - - public void engineSetCertificateEntry( - String alias, - Certificate cert) - throws KeyStoreException - { - if (keys.get(alias) != null) - { - throw new KeyStoreException("There is a key entry with the name " + alias + "."); - } - - certs.put(alias, cert); - chainCerts.put(new CertId(cert.getPublicKey()), cert); - } - - public void engineSetKeyEntry( - String alias, - byte[] key, - Certificate[] chain) - throws KeyStoreException - { - throw new RuntimeException("operation not supported"); - } - - public void engineSetKeyEntry( - String alias, - Key key, - char[] password, - Certificate[] chain) - throws KeyStoreException - { - if ((key instanceof PrivateKey) && (chain == null)) - { - throw new KeyStoreException("no certificate chain for private key"); - } - - if (keys.get(alias) != null) - { - engineDeleteEntry(alias); - } - - keys.put(alias, key); - certs.put(alias, chain[0]); - - for (int i = 0; i != chain.length; i++) - { - chainCerts.put(new CertId(chain[i].getPublicKey()), chain[i]); - } - } - - public int engineSize() - { - Hashtable tab = new Hashtable(); - - Enumeration e = certs.keys(); - while (e.hasMoreElements()) - { - tab.put(e.nextElement(), "cert"); - } - - e = keys.keys(); - while (e.hasMoreElements()) - { - String a = (String)e.nextElement(); - if (tab.get(a) == null) - { - tab.put(a, "key"); - } - } - - return tab.size(); - } - - protected PrivateKey unwrapKey( - AlgorithmIdentifier algId, - byte[] data, - char[] password, - boolean wrongPKCS12Zero) - throws IOException - { - String algorithm = algId.getAlgorithm().getId(); - PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters()); - - PBEKeySpec pbeSpec = new PBEKeySpec(password); - PrivateKey out; - - try - { - SecretKeyFactory keyFact = SecretKeyFactory.getInstance( - algorithm, bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec( - pbeParams.getIV(), - pbeParams.getIterations().intValue()); - - SecretKey k = keyFact.generateSecret(pbeSpec); - - ((BCPBEKey)k).setTryWrongPKCS12Zero(wrongPKCS12Zero); - - Cipher cipher = Cipher.getInstance(algorithm, bcProvider); - - cipher.init(Cipher.UNWRAP_MODE, k, defParams); - - // we pass "" as the key algorithm type as it is unknown at this point - out = (PrivateKey)cipher.unwrap(data, "", Cipher.PRIVATE_KEY); - } - catch (Exception e) - { - throw new IOException("exception unwrapping private key - " + e.toString()); - } - - return out; - } - - protected byte[] wrapKey( - String algorithm, - Key key, - PKCS12PBEParams pbeParams, - char[] password) - throws IOException - { - PBEKeySpec pbeSpec = new PBEKeySpec(password); - byte[] out; - - try - { - SecretKeyFactory keyFact = SecretKeyFactory.getInstance( - algorithm, bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec( - pbeParams.getIV(), - pbeParams.getIterations().intValue()); - - Cipher cipher = Cipher.getInstance(algorithm, bcProvider); - - cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), defParams); - - out = cipher.wrap(key); - } - catch (Exception e) - { - throw new IOException("exception encrypting data - " + e.toString()); - } - - return out; - } - - protected byte[] cryptData( - boolean forEncryption, - AlgorithmIdentifier algId, - char[] password, - boolean wrongPKCS12Zero, - byte[] data) - throws IOException - { - String algorithm = algId.getObjectId().getId(); - PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters()); - PBEKeySpec pbeSpec = new PBEKeySpec(password); - - try - { - SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm, bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec( - pbeParams.getIV(), - pbeParams.getIterations().intValue()); - BCPBEKey key = (BCPBEKey) keyFact.generateSecret(pbeSpec); - - key.setTryWrongPKCS12Zero(wrongPKCS12Zero); - - Cipher cipher = Cipher.getInstance(algorithm, bcProvider); - int mode = forEncryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE; - cipher.init(mode, key, defParams); - return cipher.doFinal(data); - } - catch (Exception e) - { - throw new IOException("exception decrypting data - " + e.toString()); - } - } - - public void engineLoad( - InputStream stream, - char[] password) - throws IOException - { - if (stream == null) // just initialising - { - return; - } - - if (password == null) - { - throw new NullPointerException("No password supplied for PKCS#12 KeyStore."); - } - - BufferedInputStream bufIn = new BufferedInputStream(stream); - - bufIn.mark(10); - - int head = bufIn.read(); - - if (head != 0x30) - { - throw new IOException("stream does not represent a PKCS12 key store"); - } - - bufIn.reset(); - - ASN1InputStream bIn = new ASN1InputStream(bufIn); - ASN1Sequence obj = (ASN1Sequence)bIn.readObject(); - Pfx bag = Pfx.getInstance(obj); - ContentInfo info = bag.getAuthSafe(); - Vector chain = new Vector(); - boolean unmarkedKey = false; - boolean wrongPKCS12Zero = false; - - if (bag.getMacData() != null) // check the mac code - { - MacData mData = bag.getMacData(); - DigestInfo dInfo = mData.getMac(); - AlgorithmIdentifier algId = dInfo.getAlgorithmId(); - byte[] salt = mData.getSalt(); - int itCount = mData.getIterationCount().intValue(); - - byte[] data = ((ASN1OctetString)info.getContent()).getOctets(); - - try - { - byte[] res = calculatePbeMac(algId.getObjectId(), salt, itCount, password, false, data); - byte[] dig = dInfo.getDigest(); - - if (!Arrays.constantTimeAreEqual(res, dig)) - { - if (password.length > 0) - { - throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file."); - } - - // Try with incorrect zero length password - res = calculatePbeMac(algId.getObjectId(), salt, itCount, password, true, data); - - if (!Arrays.constantTimeAreEqual(res, dig)) - { - throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file."); - } - - wrongPKCS12Zero = true; - } - } - catch (IOException e) - { - throw e; - } - catch (Exception e) - { - throw new IOException("error constructing MAC: " + e.toString()); - } - } - - keys = new IgnoresCaseHashtable(); - localIds = new Hashtable(); - - if (info.getContentType().equals(data)) - { - bIn = new ASN1InputStream(((ASN1OctetString)info.getContent()).getOctets()); - - AuthenticatedSafe authSafe = AuthenticatedSafe.getInstance(bIn.readObject()); - ContentInfo[] c = authSafe.getContentInfo(); - - for (int i = 0; i != c.length; i++) - { - if (c[i].getContentType().equals(data)) - { - ASN1InputStream dIn = new ASN1InputStream(((ASN1OctetString)c[i].getContent()).getOctets()); - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - - for (int j = 0; j != seq.size(); j++) - { - SafeBag b = SafeBag.getInstance(seq.getObjectAt(j)); - if (b.getBagId().equals(pkcs8ShroudedKeyBag)) - { - org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue()); - PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero); - - // - // set the attributes on the key - // - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; - String alias = null; - ASN1OctetString localId = null; - - if (b.getBagAttributes() != null) - { - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Set attrSet = (ASN1Set)sq.getObjectAt(1); - ASN1Primitive attr = null; - - if (attrSet.size() > 0) - { - attr = (ASN1Primitive)attrSet.getObjectAt(0); - - ASN1Encodable existing = bagAttr.getBagAttribute(aOid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(aOid, attr); - } - } - - if (aOid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - keys.put(alias, privKey); - } - else if (aOid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - } - - if (localId != null) - { - String name = new String(Hex.encode(localId.getOctets())); - - if (alias == null) - { - keys.put(name, privKey); - } - else - { - localIds.put(alias, name); - } - } - else - { - unmarkedKey = true; - keys.put("unmarked", privKey); - } - } - else if (b.getBagId().equals(certBag)) - { - chain.addElement(b); - } - else - { - System.out.println("extra in data " + b.getBagId()); - System.out.println(ASN1Dump.dumpAsString(b)); - } - } - } - else if (c[i].getContentType().equals(encryptedData)) - { - EncryptedData d = EncryptedData.getInstance(c[i].getContent()); - byte[] octets = cryptData(false, d.getEncryptionAlgorithm(), - password, wrongPKCS12Zero, d.getContent().getOctets()); - ASN1Sequence seq = (ASN1Sequence) ASN1Primitive.fromByteArray(octets); - - for (int j = 0; j != seq.size(); j++) - { - SafeBag b = SafeBag.getInstance(seq.getObjectAt(j)); - - if (b.getBagId().equals(certBag)) - { - chain.addElement(b); - } - else if (b.getBagId().equals(pkcs8ShroudedKeyBag)) - { - org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue()); - PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero); - - // - // set the attributes on the key - // - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; - String alias = null; - ASN1OctetString localId = null; - - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Set attrSet= (ASN1Set)sq.getObjectAt(1); - ASN1Primitive attr = null; - - if (attrSet.size() > 0) - { - attr = (ASN1Primitive)attrSet.getObjectAt(0); - - ASN1Encodable existing = bagAttr.getBagAttribute(aOid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(aOid, attr); - } - } - - if (aOid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - keys.put(alias, privKey); - } - else if (aOid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - - String name = new String(Hex.encode(localId.getOctets())); - - if (alias == null) - { - keys.put(name, privKey); - } - else - { - localIds.put(alias, name); - } - } - else if (b.getBagId().equals(keyBag)) - { - org.bouncycastle.asn1.pkcs.PrivateKeyInfo kInfo = new org.bouncycastle.asn1.pkcs.PrivateKeyInfo((ASN1Sequence)b.getBagValue()); - PrivateKey privKey = BouncyCastleProvider.getPrivateKey(kInfo); - - // - // set the attributes on the key - // - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; - String alias = null; - ASN1OctetString localId = null; - - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Set attrSet = (ASN1Set)sq.getObjectAt(1); - ASN1Primitive attr = null; - - if (attrSet.size() > 0) - { - attr = (ASN1Primitive)attrSet.getObjectAt(0); - - ASN1Encodable existing = bagAttr.getBagAttribute(aOid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(aOid, attr); - } - } - - if (aOid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - keys.put(alias, privKey); - } - else if (aOid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - - String name = new String(Hex.encode(localId.getOctets())); - - if (alias == null) - { - keys.put(name, privKey); - } - else - { - localIds.put(alias, name); - } - } - else - { - System.out.println("extra in encryptedData " + b.getBagId()); - System.out.println(ASN1Dump.dumpAsString(b)); - } - } - } - else - { - System.out.println("extra " + c[i].getContentType().getId()); - System.out.println("extra " + ASN1Dump.dumpAsString(c[i].getContent())); - } - } - } - - certs = new IgnoresCaseHashtable(); - chainCerts = new Hashtable(); - keyCerts = new Hashtable(); - - for (int i = 0; i != chain.size(); i++) - { - SafeBag b = (SafeBag)chain.elementAt(i); - CertBag cb = CertBag.getInstance(b.getBagValue()); - - if (!cb.getCertId().equals(x509Certificate)) - { - throw new RuntimeException("Unsupported certificate type: " + cb.getCertId()); - } - - Certificate cert; - - try - { - ByteArrayInputStream cIn = new ByteArrayInputStream( - ((ASN1OctetString)cb.getCertValue()).getOctets()); - cert = certFact.generateCertificate(cIn); - } - catch (Exception e) - { - throw new RuntimeException(e.toString()); - } - - // - // set the attributes - // - ASN1OctetString localId = null; - String alias = null; - - if (b.getBagAttributes() != null) - { - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Primitive attr = (ASN1Primitive)((ASN1Set)sq.getObjectAt(1)).getObjectAt(0); - PKCS12BagAttributeCarrier bagAttr = null; - - if (cert instanceof PKCS12BagAttributeCarrier) - { - bagAttr = (PKCS12BagAttributeCarrier)cert; - - ASN1Encodable existing = bagAttr.getBagAttribute(oid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(oid, attr); - } - } - - if (oid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - } - else if (oid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - } - - chainCerts.put(new CertId(cert.getPublicKey()), cert); - - if (unmarkedKey) - { - if (keyCerts.isEmpty()) - { - String name = new String(Hex.encode(createSubjectKeyId(cert.getPublicKey()).getKeyIdentifier())); - - keyCerts.put(name, cert); - keys.put(name, keys.remove("unmarked")); - } - } - else - { - // - // the local key id needs to override the friendly name - // - if (localId != null) - { - String name = new String(Hex.encode(localId.getOctets())); - - keyCerts.put(name, cert); - } - if (alias != null) - { - certs.put(alias, cert); - } - } - } - } - - public void engineStore(OutputStream stream, char[] password) - throws IOException - { - doStore(stream, password, false); - } - - private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) - throws IOException - { - if (password == null) - { - throw new NullPointerException("No password supplied for PKCS#12 KeyStore."); - } - - // - // handle the key - // - ASN1EncodableVector keyS = new ASN1EncodableVector(); - - - Enumeration ks = keys.keys(); - - while (ks.hasMoreElements()) - { - byte[] kSalt = new byte[SALT_SIZE]; - - random.nextBytes(kSalt); - - String name = (String)ks.nextElement(); - PrivateKey privKey = (PrivateKey)keys.get(name); - PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS); - byte[] kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password); - AlgorithmIdentifier kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.toASN1Primitive()); - org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(kAlgId, kBytes); - boolean attrSet = false; - ASN1EncodableVector kName = new ASN1EncodableVector(); - - if (privKey instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)privKey; - // - // make sure we are using the local alias on store - // - DERBMPString nm = (DERBMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(name)) - { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name)); - } - - // - // make sure we have a local key-id - // - if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) - { - Certificate ct = engineGetCertificate(name); - - bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(ct.getPublicKey())); - } - - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - ASN1EncodableVector kSeq = new ASN1EncodableVector(); - - kSeq.add(oid); - kSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - - attrSet = true; - - kName.add(new DERSequence(kSeq)); - } - } - - if (!attrSet) - { - // - // set a default friendly name (from the key id) and local id - // - ASN1EncodableVector kSeq = new ASN1EncodableVector(); - Certificate ct = engineGetCertificate(name); - - kSeq.add(pkcs_9_at_localKeyId); - kSeq.add(new DERSet(createSubjectKeyId(ct.getPublicKey()))); - - kName.add(new DERSequence(kSeq)); - - kSeq = new ASN1EncodableVector(); - - kSeq.add(pkcs_9_at_friendlyName); - kSeq.add(new DERSet(new DERBMPString(name))); - - kName.add(new DERSequence(kSeq)); - } - - SafeBag kBag = new SafeBag(pkcs8ShroudedKeyBag, kInfo.toASN1Primitive(), new DERSet(kName)); - keyS.add(kBag); - } - - byte[] keySEncoded = new DERSequence(keyS).getEncoded(ASN1Encoding.DER); - BERConstructedOctetString keyString = new BERConstructedOctetString(keySEncoded); - - // - // certificate processing - // - byte[] cSalt = new byte[SALT_SIZE]; - - random.nextBytes(cSalt); - - ASN1EncodableVector certSeq = new ASN1EncodableVector(); - PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS); - AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.toASN1Primitive()); - Hashtable doneCerts = new Hashtable(); - - Enumeration cs = keys.keys(); - while (cs.hasMoreElements()) - { - try - { - String name = (String)cs.nextElement(); - Certificate cert = engineGetCertificate(name); - boolean cAttrSet = false; - CertBag cBag = new CertBag( - x509Certificate, - new DEROctetString(cert.getEncoded())); - ASN1EncodableVector fName = new ASN1EncodableVector(); - - if (cert instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)cert; - // - // make sure we are using the local alias on store - // - DERBMPString nm = (DERBMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(name)) - { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name)); - } - - // - // make sure we have a local key-id - // - if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) - { - bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(cert.getPublicKey())); - } - - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(oid); - fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - fName.add(new DERSequence(fSeq)); - - cAttrSet = true; - } - } - - if (!cAttrSet) - { - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(pkcs_9_at_localKeyId); - fSeq.add(new DERSet(createSubjectKeyId(cert.getPublicKey()))); - fName.add(new DERSequence(fSeq)); - - fSeq = new ASN1EncodableVector(); - - fSeq.add(pkcs_9_at_friendlyName); - fSeq.add(new DERSet(new DERBMPString(name))); - - fName.add(new DERSequence(fSeq)); - } - - SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName)); - - certSeq.add(sBag); - - doneCerts.put(cert, cert); - } - catch (CertificateEncodingException e) - { - throw new IOException("Error encoding certificate: " + e.toString()); - } - } - - cs = certs.keys(); - while (cs.hasMoreElements()) - { - try - { - String certId = (String)cs.nextElement(); - Certificate cert = (Certificate)certs.get(certId); - boolean cAttrSet = false; - - if (keys.get(certId) != null) - { - continue; - } - - CertBag cBag = new CertBag( - x509Certificate, - new DEROctetString(cert.getEncoded())); - ASN1EncodableVector fName = new ASN1EncodableVector(); - - if (cert instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)cert; - // - // make sure we are using the local alias on store - // - DERBMPString nm = (DERBMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(certId)) - { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId)); - } - - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - - // a certificate not immediately linked to a key doesn't require - // a localKeyID and will confuse some PKCS12 implementations. - // - // If we find one, we'll prune it out. - if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) - { - continue; - } - - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(oid); - fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - fName.add(new DERSequence(fSeq)); - - cAttrSet = true; - } - } - - if (!cAttrSet) - { - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(pkcs_9_at_friendlyName); - fSeq.add(new DERSet(new DERBMPString(certId))); - - fName.add(new DERSequence(fSeq)); - } - - SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName)); - - certSeq.add(sBag); - - doneCerts.put(cert, cert); - } - catch (CertificateEncodingException e) - { - throw new IOException("Error encoding certificate: " + e.toString()); - } - } - - cs = chainCerts.keys(); - while (cs.hasMoreElements()) - { - try - { - CertId certId = (CertId)cs.nextElement(); - Certificate cert = (Certificate)chainCerts.get(certId); - - if (doneCerts.get(cert) != null) - { - continue; - } - - CertBag cBag = new CertBag( - x509Certificate, - new DEROctetString(cert.getEncoded())); - ASN1EncodableVector fName = new ASN1EncodableVector(); - - if (cert instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)cert; - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - - // a certificate not immediately linked to a key doesn't require - // a localKeyID and will confuse some PKCS12 implementations. - // - // If we find one, we'll prune it out. - if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) - { - continue; - } - - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(oid); - fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - fName.add(new DERSequence(fSeq)); - } - } - - SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName)); - - certSeq.add(sBag); - } - catch (CertificateEncodingException e) - { - throw new IOException("Error encoding certificate: " + e.toString()); - } - } - - byte[] certSeqEncoded = new DERSequence(certSeq).getEncoded(ASN1Encoding.DER); - byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded); - EncryptedData cInfo = new EncryptedData(data, cAlgId, new BERConstructedOctetString(certBytes)); - - ContentInfo[] info = new ContentInfo[] - { - new ContentInfo(data, keyString), - new ContentInfo(encryptedData, cInfo.toASN1Primitive()) - }; - - AuthenticatedSafe auth = new AuthenticatedSafe(info); - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream asn1Out; - if (useDEREncoding) - { - asn1Out = new DEROutputStream(bOut); - } - else - { - asn1Out = new BEROutputStream(bOut); - } - - asn1Out.writeObject(auth); - - byte[] pkg = bOut.toByteArray(); - - ContentInfo mainInfo = new ContentInfo(data, new BERConstructedOctetString(pkg)); - - // - // create the mac - // - byte[] mSalt = new byte[20]; - int itCount = MIN_ITERATIONS; - - random.nextBytes(mSalt); - - byte[] data = ((ASN1OctetString)mainInfo.getContent()).getOctets(); - - MacData mData; - - try - { - byte[] res = calculatePbeMac(id_SHA1, mSalt, itCount, password, false, data); - - AlgorithmIdentifier algId = new AlgorithmIdentifier(id_SHA1, new DERNull()); - DigestInfo dInfo = new DigestInfo(algId, res); - - mData = new MacData(dInfo, mSalt, itCount); - } - catch (Exception e) - { - throw new IOException("error constructing MAC: " + e.toString()); - } - - // - // output the Pfx - // - Pfx pfx = new Pfx(mainInfo, mData); - - if (useDEREncoding) - { - asn1Out = new DEROutputStream(stream); - } - else - { - asn1Out = new BEROutputStream(stream); - } - - asn1Out.writeObject(pfx); - } - - private static byte[] calculatePbeMac( - ASN1ObjectIdentifier oid, - byte[] salt, - int itCount, - char[] password, - boolean wrongPkcs12Zero, - byte[] data) - throws Exception - { - SecretKeyFactory keyFact = SecretKeyFactory.getInstance(oid.getId(), bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec(salt, itCount); - PBEKeySpec pbeSpec = new PBEKeySpec(password); - BCPBEKey key = (BCPBEKey) keyFact.generateSecret(pbeSpec); - key.setTryWrongPKCS12Zero(wrongPkcs12Zero); - - Mac mac = Mac.getInstance(oid.getId(), bcProvider); - mac.init(key, defParams); - mac.update(data); - return mac.doFinal(); - } - - public static class BCPKCS12KeyStore - extends JDKPKCS12KeyStore - { - public BCPKCS12KeyStore() - { - super(bcProvider, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd40BitRC2_CBC); - } - } - - public static class BCPKCS12KeyStore3DES - extends JDKPKCS12KeyStore - { - public BCPKCS12KeyStore3DES() - { - super(bcProvider, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd3_KeyTripleDES_CBC); - } - } - - public static class DefPKCS12KeyStore - extends JDKPKCS12KeyStore - { - public DefPKCS12KeyStore() - { - super(null, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd40BitRC2_CBC); - } - } - - public static class DefPKCS12KeyStore3DES - extends JDKPKCS12KeyStore - { - public DefPKCS12KeyStore3DES() - { - super(null, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd3_KeyTripleDES_CBC); - } - } - - private static class IgnoresCaseHashtable - { - private Hashtable orig = new Hashtable(); - private Hashtable keys = new Hashtable(); - - public void put(String key, Object value) - { - String lower = Strings.toLowerCase(key); - String k = (String)keys.get(lower); - if (k != null) - { - orig.remove(k); - } - - keys.put(lower, key); - orig.put(key, value); - } - - public Enumeration keys() - { - return orig.keys(); - } - - public Object remove(String alias) - { - String k = (String)keys.remove(Strings.toLowerCase(alias)); - if (k == null) - { - return null; - } - - return orig.remove(k); - } - - public Object get(String alias) - { - String k = (String)keys.get(Strings.toLowerCase(alias)); - if (k == null) - { - return null; - } - - return orig.get(k); - } - - public Enumeration elements() - { - return orig.elements(); - } - } -} diff --git a/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java b/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java index 8d6066ec..4c97c165 100644 --- a/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java +++ b/prov/src/main/jdk1.3/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.PublicKey; +import java.text.SimpleDateFormat; import org.bouncycastle.jce.cert.CertPath; import org.bouncycastle.jce.cert.CertPathBuilder; import org.bouncycastle.jce.cert.CertPathBuilderException; @@ -2018,7 +2019,7 @@ public class RFC3280CertPathUtilities } if (certStatus.getCertStatus() != CertStatus.UNREVOKED) { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss +0000"); df.setTimeZone(TimeZone.getTimeZone("UTC")); String message = "Certificate revocation after " + df.format(certStatus.getRevocationDate()); message += ", reason: " + crlReasons[certStatus.getCertStatus()]; diff --git a/prov/src/main/jdk1.3/org/bouncycastle/ocsp/BasicOCSPResp.java b/prov/src/main/jdk1.3/org/bouncycastle/ocsp/BasicOCSPResp.java deleted file mode 100644 index ebccccba..00000000 --- a/prov/src/main/jdk1.3/org/bouncycastle/ocsp/BasicOCSPResp.java +++ /dev/null @@ -1,366 +0,0 @@ -package org.bouncycastle.ocsp; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PublicKey; -import java.security.Signature; -import org.bouncycastle.jce.cert.CertStore; -import org.bouncycastle.jce.cert.CertStoreParameters; -import java.security.cert.CertificateException; -import org.bouncycastle.jce.cert.CertificateFactory; -import org.bouncycastle.jce.cert.CollectionCertStoreParameters; -import java.security.cert.X509Certificate; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1OutputStream; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ocsp.BasicOCSPResponse; -import org.bouncycastle.asn1.ocsp.ResponseData; -import org.bouncycastle.asn1.ocsp.SingleResponse; -import org.bouncycastle.asn1.x509.X509Extension; -import org.bouncycastle.asn1.x509.X509Extensions; - -/** - * <pre> - * BasicOCSPResponse ::= SEQUENCE { - * tbsResponseData ResponseData, - * signatureAlgorithm AlgorithmIdentifier, - * signature BIT STRING, - * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } - * </pre> - * - * @deprecated use classes in org.bouncycastle.cert.ocsp. - */ -public class BasicOCSPResp - implements java.security.cert.X509Extension -{ - BasicOCSPResponse resp; - ResponseData data; - X509Certificate[] chain = null; - - public BasicOCSPResp( - BasicOCSPResponse resp) - { - this.resp = resp; - this.data = resp.getTbsResponseData(); - } - - /** - * Return the DER encoding of the tbsResponseData field. - * @return DER encoding of tbsResponseData - * @throws OCSPException in the event of an encoding error. - */ - public byte[] getTBSResponseData() - throws OCSPException - { - try - { - return resp.getTbsResponseData().getEncoded(); - } - catch (IOException e) - { - throw new OCSPException("problem encoding tbsResponseData", e); - } - } - - public int getVersion() - { - return data.getVersion().getValue().intValue() + 1; - } - - public RespID getResponderId() - { - return new RespID(data.getResponderID()); - } - - public Date getProducedAt() - { - try - { - return data.getProducedAt().getDate(); - } - catch (ParseException e) - { - throw new IllegalStateException("ParseException:" + e.getMessage()); - } - } - - public SingleResp[] getResponses() - { - ASN1Sequence s = data.getResponses(); - SingleResp[] rs = new SingleResp[s.size()]; - - for (int i = 0; i != rs.length; i++) - { - rs[i] = new SingleResp(SingleResponse.getInstance(s.getObjectAt(i))); - } - - return rs; - } - - public X509Extensions getResponseExtensions() - { - return X509Extensions.getInstance(data.getResponseExtensions()); - } - - /** - * RFC 2650 doesn't specify any critical extensions so we return true - * if any are encountered. - * - * @return true if any critical extensions are present. - */ - public boolean hasUnsupportedCriticalExtension() - { - Set extns = getCriticalExtensionOIDs(); - if (extns != null && !extns.isEmpty()) - { - return true; - } - - return false; - } - - private Set getExtensionOIDs(boolean critical) - { - Set set = new HashSet(); - X509Extensions extensions = this.getResponseExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - X509Extension ext = extensions.getExtension(oid); - - if (critical == ext.isCritical()) - { - set.add(oid.getId()); - } - } - } - - return set; - } - - public Set getCriticalExtensionOIDs() - { - return getExtensionOIDs(true); - } - - public Set getNonCriticalExtensionOIDs() - { - return getExtensionOIDs(false); - } - - public byte[] getExtensionValue(String oid) - { - X509Extensions exts = this.getResponseExtensions(); - - if (exts != null) - { - X509Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getValue().getEncoded(ASN1Encoding.DER); - } - catch (Exception e) - { - throw new RuntimeException("error encoding " + e.toString()); - } - } - } - - return null; - } - - public String getSignatureAlgName() - { - return OCSPUtil.getAlgorithmName(resp.getSignatureAlgorithm().getObjectId()); - } - - public String getSignatureAlgOID() - { - return resp.getSignatureAlgorithm().getObjectId().getId(); - } - - /** - * @deprecated RespData class is no longer required as all functionality is - * available on this class. - * @return the RespData object - */ - public RespData getResponseData() - { - return new RespData(resp.getTbsResponseData()); - } - - public byte[] getSignature() - { - return resp.getSignature().getBytes(); - } - - private List getCertList( - String provider) - throws OCSPException, NoSuchProviderException - { - List certs = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - CertificateFactory cf; - - try - { - cf = OCSPUtil.createX509CertificateFactory(provider); - } - catch (CertificateException ex) - { - throw new OCSPException("can't get certificate factory.", ex); - } - - // - // load the certificates and revocation lists if we have any - // - ASN1Sequence s = resp.getCerts(); - - if (s != null) - { - Enumeration e = s.getObjects(); - - while (e.hasMoreElements()) - { - try - { - aOut.writeObject((ASN1Encodable)e.nextElement()); - - certs.add(cf.generateCertificate( - new ByteArrayInputStream(bOut.toByteArray()))); - } - catch (IOException ex) - { - throw new OCSPException( - "can't re-encode certificate!", ex); - } - catch (CertificateException ex) - { - throw new OCSPException( - "can't re-encode certificate!", ex); - } - - bOut.reset(); - } - } - - return certs; - } - - public X509Certificate[] getCerts( - String provider) - throws OCSPException, NoSuchProviderException - { - List certs = getCertList(provider); - - return (X509Certificate[])certs.toArray(new X509Certificate[certs.size()]); - } - - /** - * Return the certificates, if any associated with the response. - * @param type type of CertStore to create - * @param provider provider to use - * @return a CertStore, possibly empty - * @throws NoSuchAlgorithmException - * @throws NoSuchProviderException - * @throws OCSPException - */ - public CertStore getCertificates( - String type, - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException, OCSPException - { - try - { - CertStoreParameters params = new CollectionCertStoreParameters(this.getCertList(provider)); - return OCSPUtil.createCertStoreInstance(type, params, provider); - } - catch (InvalidAlgorithmParameterException e) - { - throw new OCSPException("can't setup the CertStore", e); - } - } - - /** - * verify the signature against the tbsResponseData object we contain. - */ - public boolean verify( - PublicKey key, - String sigProvider) - throws OCSPException, NoSuchProviderException - { - try - { - Signature signature = OCSPUtil.createSignatureInstance(this.getSignatureAlgName(), sigProvider); - - signature.initVerify(key); - - signature.update(resp.getTbsResponseData().getEncoded(ASN1Encoding.DER)); - - return signature.verify(this.getSignature()); - } - catch (NoSuchProviderException e) - { - // TODO Why this special case? - throw e; - } - catch (Exception e) - { - throw new OCSPException("exception processing sig: " + e, e); - } - } - - /** - * return the ASN.1 encoded representation of this object. - */ - public byte[] getEncoded() - throws IOException - { - return resp.getEncoded(); - } - - public boolean equals(Object o) - { - if (o == this) - { - return true; - } - - if (!(o instanceof BasicOCSPResp)) - { - return false; - } - - BasicOCSPResp r = (BasicOCSPResp)o; - - return resp.equals(r.resp); - } - - public int hashCode() - { - return resp.hashCode(); - } -} diff --git a/prov/src/main/jdk1.3/org/bouncycastle/ocsp/OCSPReq.java b/prov/src/main/jdk1.3/org/bouncycastle/ocsp/OCSPReq.java deleted file mode 100644 index 405c11a3..00000000 --- a/prov/src/main/jdk1.3/org/bouncycastle/ocsp/OCSPReq.java +++ /dev/null @@ -1,415 +0,0 @@ -package org.bouncycastle.ocsp; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PublicKey; -import java.security.Signature; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OutputStream; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ocsp.OCSPRequest; -import org.bouncycastle.asn1.ocsp.Request; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.X509Extension; -import org.bouncycastle.asn1.x509.X509Extensions; -import org.bouncycastle.jce.cert.CertStore; -import org.bouncycastle.jce.cert.CertStoreParameters; -import org.bouncycastle.jce.cert.CertificateFactory; -import org.bouncycastle.jce.cert.CollectionCertStoreParameters; - -/** - * <pre> - * OCSPRequest ::= SEQUENCE { - * tbsRequest TBSRequest, - * optionalSignature [0] EXPLICIT Signature OPTIONAL } - * - * TBSRequest ::= SEQUENCE { - * version [0] EXPLICIT Version DEFAULT v1, - * requestorName [1] EXPLICIT GeneralName OPTIONAL, - * requestList SEQUENCE OF Request, - * requestExtensions [2] EXPLICIT Extensions OPTIONAL } - * - * Signature ::= SEQUENCE { - * signatureAlgorithm AlgorithmIdentifier, - * signature BIT STRING, - * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL} - * - * Version ::= INTEGER { v1(0) } - * - * Request ::= SEQUENCE { - * reqCert CertID, - * singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } - * - * CertID ::= SEQUENCE { - * hashAlgorithm AlgorithmIdentifier, - * issuerNameHash OCTET STRING, -- Hash of Issuer's DN - * issuerKeyHash OCTET STRING, -- Hash of Issuers public key - * serialNumber CertificateSerialNumber } - * </pre> - */ -public class OCSPReq - implements java.security.cert.X509Extension -{ - private OCSPRequest req; - - public OCSPReq( - OCSPRequest req) - { - this.req = req; - } - - public OCSPReq( - byte[] req) - throws IOException - { - this(new ASN1InputStream(req)); - } - - public OCSPReq( - InputStream in) - throws IOException - { - this(new ASN1InputStream(in)); - } - - private OCSPReq( - ASN1InputStream aIn) - throws IOException - { - try - { - this.req = OCSPRequest.getInstance(aIn.readObject()); - } - catch (IllegalArgumentException e) - { - throw new IOException("malformed request: " + e.getMessage()); - } - catch (ClassCastException e) - { - throw new IOException("malformed request: " + e.getMessage()); - } - } - - /** - * Return the DER encoding of the tbsRequest field. - * @return DER encoding of tbsRequest - * @throws OCSPException in the event of an encoding error. - */ - public byte[] getTBSRequest() - throws OCSPException - { - try - { - return req.getTbsRequest().getEncoded(); - } - catch (IOException e) - { - throw new OCSPException("problem encoding tbsRequest", e); - } - } - - public int getVersion() - { - return req.getTbsRequest().getVersion().getValue().intValue() + 1; - } - - public GeneralName getRequestorName() - { - return GeneralName.getInstance(req.getTbsRequest().getRequestorName()); - } - - public Req[] getRequestList() - { - ASN1Sequence seq = req.getTbsRequest().getRequestList(); - Req[] requests = new Req[seq.size()]; - - for (int i = 0; i != requests.length; i++) - { - requests[i] = new Req(Request.getInstance(seq.getObjectAt(i))); - } - - return requests; - } - - public X509Extensions getRequestExtensions() - { - return X509Extensions.getInstance(req.getTbsRequest().getRequestExtensions()); - } - - /** - * return the object identifier representing the signature algorithm - */ - public String getSignatureAlgOID() - { - if (!this.isSigned()) - { - return null; - } - - return req.getOptionalSignature().getSignatureAlgorithm().getObjectId().getId(); - } - - public byte[] getSignature() - { - if (!this.isSigned()) - { - return null; - } - - return req.getOptionalSignature().getSignature().getBytes(); - } - - private List getCertList( - String provider) - throws OCSPException, NoSuchProviderException - { - List certs = new ArrayList(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - CertificateFactory cf; - - try - { - cf = OCSPUtil.createX509CertificateFactory(provider); - } - catch (CertificateException ex) - { - throw new OCSPException("can't get certificate factory.", ex); - } - - // - // load the certificates if we have any - // - ASN1Sequence s = req.getOptionalSignature().getCerts(); - - if (s != null) - { - Enumeration e = s.getObjects(); - - while (e.hasMoreElements()) - { - try - { - aOut.writeObject((ASN1Encodable)e.nextElement()); - - certs.add(cf.generateCertificate( - new ByteArrayInputStream(bOut.toByteArray()))); - } - catch (IOException ex) - { - throw new OCSPException( - "can't re-encode certificate!", ex); - } - catch (CertificateException ex) - { - throw new OCSPException( - "can't re-encode certificate!", ex); - } - - bOut.reset(); - } - } - - return certs; - } - - public X509Certificate[] getCerts( - String provider) - throws OCSPException, NoSuchProviderException - { - if (!this.isSigned()) - { - return null; - } - - List certs = this.getCertList(provider); - - return (X509Certificate[])certs.toArray(new X509Certificate[certs.size()]); - } - - /** - * If the request is signed return a possibly empty CertStore containing the certificates in the - * request. If the request is not signed the method returns null. - * - * @param type type of CertStore to return - * @param provider provider to use - * @return null if not signed, a CertStore otherwise - * @throws NoSuchAlgorithmException - * @throws NoSuchProviderException - * @throws OCSPException - */ - public CertStore getCertificates( - String type, - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException, OCSPException - { - if (!this.isSigned()) - { - return null; - } - - try - { - CertStoreParameters params = new CollectionCertStoreParameters(this.getCertList(provider)); - return OCSPUtil.createCertStoreInstance(type, params, provider); - } - catch (InvalidAlgorithmParameterException e) - { - throw new OCSPException("can't setup the CertStore", e); - } - } - - /** - * Return whether or not this request is signed. - * - * @return true if signed false otherwise. - */ - public boolean isSigned() - { - return req.getOptionalSignature() != null; - } - - /** - * verify the signature against the TBSRequest object we contain. - */ - public boolean verify( - PublicKey key, - String sigProvider) - throws OCSPException, NoSuchProviderException - { - if (!this.isSigned()) - { - throw new OCSPException("attempt to verify signature on unsigned object"); - } - - try - { - Signature signature = OCSPUtil.createSignatureInstance(this.getSignatureAlgOID(), sigProvider); - - signature.initVerify(key); - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - aOut.writeObject(req.getTbsRequest()); - - signature.update(bOut.toByteArray()); - - return signature.verify(this.getSignature()); - } - catch (NoSuchProviderException e) - { - // TODO Why this special case? - throw e; - } - catch (Exception e) - { - throw new OCSPException("exception processing sig: " + e, e); - } - } - - /** - * return the ASN.1 encoded representation of this object. - */ - public byte[] getEncoded() - throws IOException - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - aOut.writeObject(req); - - return bOut.toByteArray(); - } - - /** - * RFC 2650 doesn't specify any critical extensions so we return true - * if any are encountered. - * - * @return true if any critical extensions are present. - */ - public boolean hasUnsupportedCriticalExtension() - { - Set extns = getCriticalExtensionOIDs(); - if (extns != null && !extns.isEmpty()) - { - return true; - } - - return false; - } - - private Set getExtensionOIDs(boolean critical) - { - Set set = new HashSet(); - X509Extensions extensions = this.getRequestExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - X509Extension ext = extensions.getExtension(oid); - - if (critical == ext.isCritical()) - { - set.add(oid.getId()); - } - } - } - - return set; - } - - public Set getCriticalExtensionOIDs() - { - return getExtensionOIDs(true); - } - - public Set getNonCriticalExtensionOIDs() - { - return getExtensionOIDs(false); - } - - public byte[] getExtensionValue(String oid) - { - X509Extensions exts = this.getRequestExtensions(); - - if (exts != null) - { - X509Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getValue().getEncoded(ASN1Encoding.DER); - } - catch (Exception e) - { - throw new RuntimeException("error encoding " + e.toString()); - } - } - } - - return null; - } -} diff --git a/prov/src/main/jdk1.3/org/bouncycastle/ocsp/OCSPReqGenerator.java b/prov/src/main/jdk1.3/org/bouncycastle/ocsp/OCSPReqGenerator.java deleted file mode 100644 index f4d01dc9..00000000 --- a/prov/src/main/jdk1.3/org/bouncycastle/ocsp/OCSPReqGenerator.java +++ /dev/null @@ -1,292 +0,0 @@ -package org.bouncycastle.ocsp; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1OutputStream; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.ocsp.OCSPRequest; -import org.bouncycastle.asn1.ocsp.Request; -import org.bouncycastle.asn1.ocsp.Signature; -import org.bouncycastle.asn1.ocsp.TBSRequest; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.Extensions; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.X509CertificateStructure; -import org.bouncycastle.asn1.x509.X509Extensions; -import org.bouncycastle.jce.X509Principal; - -/** - * @deprecated use classes in org.bouncycastle.cert.ocsp. - */ -public class OCSPReqGenerator -{ - private List list = new ArrayList(); - private GeneralName requestorName = null; - private X509Extensions requestExtensions = null; - - private class RequestObject - { - CertificateID certId; - X509Extensions extensions; - - public RequestObject( - CertificateID certId, - X509Extensions extensions) - { - this.certId = certId; - this.extensions = extensions; - } - - public Request toRequest() - throws Exception - { - return new Request(certId.toASN1Object(), Extensions.getInstance(extensions)); - } - } - - /** - * Add a request for the given CertificateID. - * - * @param certId certificate ID of interest - */ - public void addRequest( - CertificateID certId) - { - list.add(new RequestObject(certId, null)); - } - - /** - * Add a request with extensions - * - * @param certId certificate ID of interest - * @param singleRequestExtensions the extensions to attach to the request - */ - public void addRequest( - CertificateID certId, - X509Extensions singleRequestExtensions) - { - list.add(new RequestObject(certId, singleRequestExtensions)); - } - - /** - * Set the requestor name to the passed in X500Principal - * - * @param requestorName a X500Principal representing the requestor name. - */ - public void setRequestorName( - X509Principal requestorName) - { - try - { - this.requestorName = new GeneralName(GeneralName.directoryName, new X509Principal(requestorName.getEncoded())); - } - catch (IOException e) - { - throw new IllegalArgumentException("cannot encode principal: " + e); - } - } - - public void setRequestorName( - GeneralName requestorName) - { - this.requestorName = requestorName; - } - - public void setRequestExtensions( - X509Extensions requestExtensions) - { - this.requestExtensions = requestExtensions; - } - - private OCSPReq generateRequest( - ASN1ObjectIdentifier signingAlgorithm, - PrivateKey key, - X509Certificate[] chain, - String provider, - SecureRandom random) - throws OCSPException, NoSuchProviderException - { - Iterator it = list.iterator(); - - ASN1EncodableVector requests = new ASN1EncodableVector(); - - while (it.hasNext()) - { - try - { - requests.add(((RequestObject)it.next()).toRequest()); - } - catch (Exception e) - { - throw new OCSPException("exception creating Request", e); - } - } - - TBSRequest tbsReq = new TBSRequest(requestorName, new DERSequence(requests), requestExtensions); - - java.security.Signature sig = null; - Signature signature = null; - - if (signingAlgorithm != null) - { - if (requestorName == null) - { - throw new OCSPException("requestorName must be specified if request is signed."); - } - - try - { - sig = OCSPUtil.createSignatureInstance(signingAlgorithm.getId(), provider); - if (random != null) - { - sig.initSign(key, random); - } - else - { - sig.initSign(key); - } - } - catch (NoSuchProviderException e) - { - // TODO Why this special case? - throw e; - } - catch (GeneralSecurityException e) - { - throw new OCSPException("exception creating signature: " + e, e); - } - - DERBitString bitSig = null; - - try - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - aOut.writeObject(tbsReq); - - sig.update(bOut.toByteArray()); - - bitSig = new DERBitString(sig.sign()); - } - catch (Exception e) - { - throw new OCSPException("exception processing TBSRequest: " + e, e); - } - - AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, new DERNull()); - - if (chain != null && chain.length > 0) - { - ASN1EncodableVector v = new ASN1EncodableVector(); - try - { - for (int i = 0; i != chain.length; i++) - { - v.add(new X509CertificateStructure( - (ASN1Sequence)ASN1Primitive.fromByteArray(chain[i].getEncoded()))); - } - } - catch (IOException e) - { - throw new OCSPException("error processing certs", e); - } - catch (CertificateEncodingException e) - { - throw new OCSPException("error encoding certs", e); - } - - signature = new Signature(sigAlgId, bitSig, new DERSequence(v)); - } - else - { - signature = new Signature(sigAlgId, bitSig); - } - } - - return new OCSPReq(new OCSPRequest(tbsReq, signature)); - } - - /** - * Generate an unsigned request - * - * @return the OCSPReq - * @throws OCSPException - */ - public OCSPReq generate() - throws OCSPException - { - try - { - return generateRequest(null, null, null, null, null); - } - catch (NoSuchProviderException e) - { - // - // this shouldn't happen but... - // - throw new OCSPException("no provider! - " + e, e); - } - } - - public OCSPReq generate( - String signingAlgorithm, - PrivateKey key, - X509Certificate[] chain, - String provider) - throws OCSPException, NoSuchProviderException, IllegalArgumentException - { - return generate(signingAlgorithm, key, chain, provider, null); - } - - public OCSPReq generate( - String signingAlgorithm, - PrivateKey key, - X509Certificate[] chain, - String provider, - SecureRandom random) - throws OCSPException, NoSuchProviderException, IllegalArgumentException - { - if (signingAlgorithm == null) - { - throw new IllegalArgumentException("no signing algorithm specified"); - } - - try - { - ASN1ObjectIdentifier oid = OCSPUtil.getAlgorithmOID(signingAlgorithm); - - return generateRequest(oid, key, chain, provider, random); - } - catch (IllegalArgumentException e) - { - throw new IllegalArgumentException("unknown signing algorithm specified: " + signingAlgorithm); - } - } - - /** - * Return an iterator of the signature names supported by the generator. - * - * @return an iterator containing recognised names. - */ - public Iterator getSignatureAlgNames() - { - return OCSPUtil.getAlgNames(); - } -} diff --git a/prov/src/main/jdk1.3/org/bouncycastle/ocsp/OCSPUtil.java b/prov/src/main/jdk1.3/org/bouncycastle/ocsp/OCSPUtil.java deleted file mode 100644 index 69e86437..00000000 --- a/prov/src/main/jdk1.3/org/bouncycastle/ocsp/OCSPUtil.java +++ /dev/null @@ -1,198 +0,0 @@ -package org.bouncycastle.ocsp; - -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.util.Strings; - -import java.security.InvalidAlgorithmParameterException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Signature; -import org.bouncycastle.jce.cert.CertStore; -import org.bouncycastle.jce.cert.CertStoreParameters; -import java.security.cert.CertificateException; -import org.bouncycastle.jce.cert.CertificateFactory; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -class OCSPUtil -{ - private static Hashtable algorithms = new Hashtable(); - private static Hashtable oids = new Hashtable(); - private static Set noParams = new HashSet(); - - static - { - algorithms.put("MD2WITHRSAENCRYPTION", PKCSObjectIdentifiers.md2WithRSAEncryption); - algorithms.put("MD2WITHRSA", PKCSObjectIdentifiers.md2WithRSAEncryption); - algorithms.put("MD5WITHRSAENCRYPTION", PKCSObjectIdentifiers.md5WithRSAEncryption); - algorithms.put("MD5WITHRSA", PKCSObjectIdentifiers.md5WithRSAEncryption); - algorithms.put("SHA1WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha1WithRSAEncryption); - algorithms.put("SHA1WITHRSA", PKCSObjectIdentifiers.sha1WithRSAEncryption); - algorithms.put("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA256WITHRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA384WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA384WITHRSA", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA512WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("SHA512WITHRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("SHA1WITHDSA", X9ObjectIdentifiers.id_dsa_with_sha1); - algorithms.put("DSAWITHSHA1", X9ObjectIdentifiers.id_dsa_with_sha1); - algorithms.put("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224); - algorithms.put("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256); - algorithms.put("SHA1WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("ECDSAWITHSHA1", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("SHA224WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); - algorithms.put("SHA256WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); - algorithms.put("SHA384WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); - algorithms.put("SHA512WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); - algorithms.put("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - algorithms.put("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - - oids.put(PKCSObjectIdentifiers.md2WithRSAEncryption, "MD2WITHRSA"); - oids.put(PKCSObjectIdentifiers.md5WithRSAEncryption, "MD5WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha1WithRSAEncryption, "SHA1WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); - oids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160, "RIPEMD160WITHRSA"); - oids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128, "RIPEMD128WITHRSA"); - oids.put(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256, "RIPEMD256WITHRSA"); - oids.put(X9ObjectIdentifiers.id_dsa_with_sha1, "SHA1WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA1, "SHA1WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); - oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410"); - - // - // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field. - // The parameters field SHALL be NULL for RSA based signature algorithms. - // - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA1); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA224); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA256); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA384); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA512); - noParams.add(X9ObjectIdentifiers.id_dsa_with_sha1); - noParams.add(NISTObjectIdentifiers.dsa_with_sha224); - noParams.add(NISTObjectIdentifiers.dsa_with_sha256); - } - - static ASN1ObjectIdentifier getAlgorithmOID( - String algorithmName) - { - algorithmName = Strings.toUpperCase(algorithmName); - - if (algorithms.containsKey(algorithmName)) - { - return (ASN1ObjectIdentifier)algorithms.get(algorithmName); - } - - return new ASN1ObjectIdentifier(algorithmName); - } - - static String getAlgorithmName( - ASN1ObjectIdentifier oid) - { - if (oids.containsKey(oid)) - { - return (String)oids.get(oid); - } - - return oid.getId(); - } - - static AlgorithmIdentifier getSigAlgID( - ASN1ObjectIdentifier sigOid) - { - if (noParams.contains(sigOid)) - { - return new AlgorithmIdentifier(sigOid); - } - else - { - return new AlgorithmIdentifier(sigOid, new DERNull()); - } - } - - static Iterator getAlgNames() - { - Enumeration e = algorithms.keys(); - List l = new ArrayList(); - - while (e.hasMoreElements()) - { - l.add(e.nextElement()); - } - - return l.iterator(); - } - - static CertStore createCertStoreInstance(String type, CertStoreParameters params, String provider) - throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException - { - if (provider == null) - { - return CertStore.getInstance(type, params); - } - - return CertStore.getInstance(type, params, provider); - } - - static MessageDigest createDigestInstance(String digestName, String provider) - throws NoSuchAlgorithmException, NoSuchProviderException - { - if (provider == null) - { - return MessageDigest.getInstance(digestName); - } - - return MessageDigest.getInstance(digestName, provider); - } - - static Signature createSignatureInstance(String sigName, String provider) - throws NoSuchAlgorithmException, NoSuchProviderException - { - if (provider == null) - { - return Signature.getInstance(sigName); - } - - return Signature.getInstance(sigName, provider); - } - - static CertificateFactory createX509CertificateFactory(String provider) - throws CertificateException, NoSuchProviderException - { - if (provider == null) - { - return CertificateFactory.getInstance("X.509"); - } - - return CertificateFactory.getInstance("X.509", provider); - } -} diff --git a/prov/src/main/jdk1.3/org/bouncycastle/ocsp/RespID.java b/prov/src/main/jdk1.3/org/bouncycastle/ocsp/RespID.java deleted file mode 100644 index 0cf66c77..00000000 --- a/prov/src/main/jdk1.3/org/bouncycastle/ocsp/RespID.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.bouncycastle.ocsp; - -import java.security.MessageDigest; -import java.security.PublicKey; - -import org.bouncycastle.jce.X509Principal; - -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.ocsp.ResponderID; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; - -/** - * Carrier for a ResponderID. - */ -public class RespID -{ - ResponderID id; - - public RespID( - ResponderID id) - { - this.id = id; - } - - public RespID( - X509Principal name) - { - this.id = new ResponderID(X500Name.getInstance(name.getEncoded())); - } - - public RespID( - PublicKey key) - throws OCSPException - { - try - { - // TODO Allow specification of a particular provider - MessageDigest digest = OCSPUtil.createDigestInstance("SHA1", null); - - ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); - - digest.update(info.getPublicKeyData().getBytes()); - - ASN1OctetString keyHash = new DEROctetString(digest.digest()); - - this.id = new ResponderID(keyHash); - } - catch (Exception e) - { - throw new OCSPException("problem creating ID: " + e, e); - } - } - - public ResponderID toASN1Object() - { - return id; - } - - public boolean equals( - Object o) - { - if (!(o instanceof RespID)) - { - return false; - } - - RespID obj = (RespID)o; - - return id.equals(obj.id); - } - - public int hashCode() - { - return id.hashCode(); - } -} diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/RegressionTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/RegressionTest.java index c17f2c08..29f016c1 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/RegressionTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/RegressionTest.java @@ -48,7 +48,6 @@ public class RegressionTest new NamedCurveTest(), new PKIXTest(), new NetscapeCertRequestTest(), - new X509StoreTest(), new X509StreamParserTest(), new X509CertificatePairTest(), new CertPathTest(), diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/X509StoreTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/X509StoreTest.java deleted file mode 100644 index 6043fa27..00000000 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/X509StoreTest.java +++ /dev/null @@ -1,345 +0,0 @@ -package org.bouncycastle.jce.provider.test; - -import java.io.ByteArrayInputStream; -import java.math.BigInteger; -import java.security.Security; -import java.security.cert.CertificateFactory; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import org.bouncycastle.jce.PrincipalUtil; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.test.SimpleTest; -import org.bouncycastle.x509.X509AttributeCertStoreSelector; -import org.bouncycastle.x509.X509AttributeCertificate; -import org.bouncycastle.x509.X509CRLStoreSelector; -import org.bouncycastle.x509.X509CertPairStoreSelector; -import org.bouncycastle.x509.X509CertStoreSelector; -import org.bouncycastle.x509.X509CertificatePair; -import org.bouncycastle.x509.X509CollectionStoreParameters; -import org.bouncycastle.x509.X509Store; -import org.bouncycastle.x509.X509V2AttributeCertificate; - -public class X509StoreTest - extends SimpleTest -{ - private void certPairTest() - throws Exception - { - CertificateFactory cf = CertificateFactory.getInstance("X.509", - "BC"); - - X509Certificate rootCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.rootCertBin)); - X509Certificate interCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.interCertBin)); - X509Certificate finalCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.finalCertBin)); - - // Testing CollectionCertStore generation from List - X509CertificatePair pair1 = new X509CertificatePair(rootCert, interCert); - List certList = new ArrayList(); - - certList.add(pair1); - certList.add(new X509CertificatePair(interCert, finalCert)); - - X509CollectionStoreParameters ccsp = new X509CollectionStoreParameters(certList); - - X509Store certStore = X509Store.getInstance("CertificatePair/Collection", ccsp, "BC"); - X509CertPairStoreSelector selector = new X509CertPairStoreSelector(); - X509CertStoreSelector fwSelector = new X509CertStoreSelector(); - - fwSelector.setSerialNumber(rootCert.getSerialNumber()); - fwSelector.setSubject(rootCert.getIssuerDN().getName()); - - selector.setForwardSelector(fwSelector); - - Collection col = certStore.getMatches(selector); - - if (col.size() != 1 || !col.contains(pair1)) - { - fail("failed pair1 test"); - } - - col = certStore.getMatches(null); - - if (col.size() != 2) - { - fail("failed null test"); - } - } - - public void performTest() - throws Exception - { - CertificateFactory cf = CertificateFactory.getInstance("X.509", - "BC"); - - X509Certificate rootCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.rootCertBin)); - X509Certificate interCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.interCertBin)); - X509Certificate finalCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.finalCertBin)); - X509CRL rootCrl = (X509CRL)cf.generateCRL(new ByteArrayInputStream( - CertPathTest.rootCrlBin)); - X509CRL interCrl = (X509CRL)cf - .generateCRL(new ByteArrayInputStream( - CertPathTest.interCrlBin)); - - // Testing CollectionCertStore generation from List - List certList = new ArrayList(); - certList.add(rootCert); - certList.add(interCert); - certList.add(finalCert); - X509CollectionStoreParameters ccsp = new X509CollectionStoreParameters(certList); - X509Store certStore = X509Store.getInstance("Certificate/Collection", ccsp, "BC"); - // set default to be the same as for SUN X500 name - X509Principal.DefaultReverse = true; - - // Searching for rootCert by subjectDN - - X509CertStoreSelector targetConstraints = new X509CertStoreSelector(); - targetConstraints.setSubject(PrincipalUtil.getSubjectX509Principal(rootCert).getEncoded()); - Collection certs = certStore.getMatches(targetConstraints); - if (certs.size() != 1 || !certs.contains(rootCert)) - { - fail("rootCert not found by subjectDN"); - } - - // Searching for rootCert by subjectDN encoded as byte - targetConstraints = new X509CertStoreSelector(); - targetConstraints.setSubject(PrincipalUtil.getSubjectX509Principal(rootCert).getEncoded()); - certs = certStore.getMatches(targetConstraints); - if (certs.size() != 1 || !certs.contains(rootCert)) - { - fail("rootCert not found by encoded subjectDN"); - } - - X509Principal.DefaultReverse = false; - - // Searching for rootCert by public key encoded as byte - targetConstraints = new X509CertStoreSelector(); - targetConstraints.setSubjectPublicKey(rootCert.getPublicKey().getEncoded()); - certs = certStore.getMatches(targetConstraints); - if (certs.size() != 1 || !certs.contains(rootCert)) - { - fail("rootCert not found by encoded public key"); - } - - // Searching for interCert by issuerDN - targetConstraints = new X509CertStoreSelector(); - targetConstraints.setIssuer(PrincipalUtil.getSubjectX509Principal(rootCert).getEncoded()); - certs = certStore.getMatches(targetConstraints); - if (certs.size() != 2) - { - fail("did not found 2 certs"); - } - if (!certs.contains(rootCert)) - { - fail("rootCert not found"); - } - if (!certs.contains(interCert)) - { - fail("interCert not found"); - } - - // Searching for rootCrl by issuerDN - List crlList = new ArrayList(); - crlList.add(rootCrl); - crlList.add(interCrl); - ccsp = new X509CollectionStoreParameters(crlList); - X509Store store = X509Store.getInstance("CRL/Collection", ccsp, "BC"); - X509CRLStoreSelector targetConstraintsCRL = new X509CRLStoreSelector(); - targetConstraintsCRL.setIssuers(Collections.singleton(rootCrl.getIssuerX500Principal())); - Collection crls = store.getMatches(targetConstraintsCRL); - if (crls.size() != 1 || !crls.contains(rootCrl)) - { - fail("rootCrl not found"); - } - - crls = certStore.getMatches(targetConstraintsCRL); - if (crls.size() != 0) - { - fail("error using wrong selector (CRL)"); - } - certs = store.getMatches(targetConstraints); - if (certs.size() != 0) - { - fail("error using wrong selector (certs)"); - } - // Searching for attribute certificates - X509V2AttributeCertificate attrCert = new X509V2AttributeCertificate(AttrCertData.attrCert); - X509AttributeCertificate attrCert2 = new X509V2AttributeCertificate(AttrCertData.certWithBaseCertificateID); - - List attrList = new ArrayList(); - attrList.add(attrCert); - attrList.add(attrCert2); - ccsp = new X509CollectionStoreParameters(attrList); - store = X509Store.getInstance("AttributeCertificate/Collection", ccsp, "BC"); - X509AttributeCertStoreSelector attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setHolder(attrCert.getHolder()); - if (!attrSelector.getHolder().equals(attrCert.getHolder())) - { - fail("holder get not correct"); - } - Collection attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on holder"); - } - attrSelector.setHolder(attrCert2.getHolder()); - if (attrSelector.getHolder().equals(attrCert.getHolder())) - { - fail("holder get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert2)) - { - fail("attrCert2 not found on holder"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setIssuer(attrCert.getIssuer()); - if (!attrSelector.getIssuer().equals(attrCert.getIssuer())) - { - fail("issuer get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on issuer"); - } - attrSelector.setIssuer(attrCert2.getIssuer()); - if (attrSelector.getIssuer().equals(attrCert.getIssuer())) - { - fail("issuer get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert2)) - { - fail("attrCert2 not found on issuer"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setAttributeCert(attrCert); - if (!attrSelector.getAttributeCert().equals(attrCert)) - { - fail("attrCert get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on attrCert"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setSerialNumber(attrCert.getSerialNumber()); - if (!attrSelector.getSerialNumber().equals(attrCert.getSerialNumber())) - { - fail("serial number get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on serial number"); - } - attrSelector = (X509AttributeCertStoreSelector)attrSelector.clone(); - if (!attrSelector.getSerialNumber().equals(attrCert.getSerialNumber())) - { - fail("serial number get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on serial number"); - } - - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setAttributeCertificateValid(attrCert.getNotBefore()); - if (!attrSelector.getAttributeCertificateValid().equals(attrCert.getNotBefore())) - { - fail("valid get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on valid"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setAttributeCertificateValid(new Date(attrCert.getNotBefore().getTime() - 100)); - attrs = store.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("attrCert found on before"); - } - attrSelector.setAttributeCertificateValid(new Date(attrCert.getNotAfter().getTime() + 100)); - attrs = store.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("attrCert found on after"); - } - attrSelector.setSerialNumber(BigInteger.valueOf(10000)); - attrs = store.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("attrCert found on wrong serial number"); - } - - attrSelector.setAttributeCert(null); - attrSelector.setAttributeCertificateValid(null); - attrSelector.setHolder(null); - attrSelector.setIssuer(null); - attrSelector.setSerialNumber(null); - if (attrSelector.getAttributeCert() != null) - { - fail("null attrCert"); - } - if (attrSelector.getAttributeCertificateValid() != null) - { - fail("null attrCertValid"); - } - if (attrSelector.getHolder() != null) - { - fail("null attrCert holder"); - } - if (attrSelector.getIssuer() != null) - { - fail("null attrCert issuer"); - } - if (attrSelector.getSerialNumber() != null) - { - fail("null attrCert serial"); - } - - attrs = certStore.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("error using wrong selector (attrs)"); - } - - certPairTest(); - } - - public String getName() - { - return "X509Store"; - } - - public static void main(String[] args) - { - Security.addProvider(new BouncyCastleProvider()); - - runTest(new X509StoreTest()); - } - -} diff --git a/prov/src/test/java/org/bouncycastle/jce/provider/test/nist/NistCertPathTest.java b/prov/src/test/java/org/bouncycastle/jce/provider/test/nist/NistCertPathTest.java index f314ee38..af94e4e1 100644 --- a/prov/src/test/java/org/bouncycastle/jce/provider/test/nist/NistCertPathTest.java +++ b/prov/src/test/java/org/bouncycastle/jce/provider/test/nist/NistCertPathTest.java @@ -34,8 +34,9 @@ import junit.framework.TestCase; import junit.framework.TestSuite; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.x509.X509Extension; -import org.bouncycastle.x509.extension.X509ExtensionUtil; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.x509.Extension; /** * NIST CertPath test data for RFC 3280 @@ -830,11 +831,11 @@ public class NistCertPathTest throws Exception { X509Certificate cert = loadCert(trustAnchorName); - byte[] extBytes = cert.getExtensionValue(X509Extension.nameConstraints.getId()); + byte[] extBytes = cert.getExtensionValue(Extension.nameConstraints.getId()); if (extBytes != null) { - ASN1Encodable extValue = X509ExtensionUtil.fromExtensionValue(extBytes); + ASN1Encodable extValue = ASN1Primitive.fromByteArray(ASN1OctetString.getInstance(extBytes).getOctets()); return new TrustAnchor(cert, extValue.toASN1Primitive().getEncoded(ASN1Encoding.DER)); } diff --git a/prov/src/test/jdk1.3/org/bouncycastle/jce/provider/test/CertTest.java b/prov/src/test/jdk1.3/org/bouncycastle/jce/provider/test/CertTest.java index 7b38b720..aa0c785b 100644 --- a/prov/src/test/jdk1.3/org/bouncycastle/jce/provider/test/CertTest.java +++ b/prov/src/test/jdk1.3/org/bouncycastle/jce/provider/test/CertTest.java @@ -2281,7 +2281,7 @@ public class CertTest ASN1EncodableVector certs = new ASN1EncodableVector(); certs.add(new ASN1InputStream(CertPathTest.rootCertBin).readObject()); - certs.add(new DERTaggedObject(false, 2, new ASN1InputStream(AttrCertTest.attrCert).readObject())); + certs.add(new DERTaggedObject(false, 2, new ASN1InputStream(AttrCertData.attrCert).readObject())); ASN1EncodableVector crls = new ASN1EncodableVector(); diff --git a/prov/src/test/jdk1.3/org/bouncycastle/jce/provider/test/X509StoreTest.java b/prov/src/test/jdk1.3/org/bouncycastle/jce/provider/test/X509StoreTest.java deleted file mode 100644 index 6524229f..00000000 --- a/prov/src/test/jdk1.3/org/bouncycastle/jce/provider/test/X509StoreTest.java +++ /dev/null @@ -1,320 +0,0 @@ -package org.bouncycastle.jce.provider.test; - -import org.bouncycastle.jce.PrincipalUtil; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.test.SimpleTest; -import org.bouncycastle.x509.X509AttributeCertStoreSelector; -import org.bouncycastle.x509.X509AttributeCertificate; -import org.bouncycastle.x509.X509CRLStoreSelector; -import org.bouncycastle.x509.X509CertPairStoreSelector; -import org.bouncycastle.x509.X509CertStoreSelector; -import org.bouncycastle.x509.X509CertificatePair; -import org.bouncycastle.x509.X509CollectionStoreParameters; -import org.bouncycastle.x509.X509Store; -import org.bouncycastle.x509.X509V2AttributeCertificate; - -import java.io.ByteArrayInputStream; -import java.math.BigInteger; -import java.security.Security; -import java.security.cert.CertificateFactory; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -public class X509StoreTest - extends SimpleTest -{ - private void certPairTest() - throws Exception - { - CertificateFactory cf = CertificateFactory.getInstance("X.509", - "BC"); - - X509Certificate rootCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.rootCertBin)); - X509Certificate interCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.interCertBin)); - X509Certificate finalCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.finalCertBin)); - - // Testing CollectionCertStore generation from List - X509CertificatePair pair1 = new X509CertificatePair(rootCert, interCert); - List certList = new ArrayList(); - - certList.add(pair1); - certList.add(new X509CertificatePair(interCert, finalCert)); - - X509CollectionStoreParameters ccsp = new X509CollectionStoreParameters(certList); - - X509Store certStore = X509Store.getInstance("CertificatePair/Collection", ccsp, "BC"); - X509CertPairStoreSelector selector = new X509CertPairStoreSelector(); - X509CertStoreSelector fwSelector = new X509CertStoreSelector(); - - fwSelector.setSerialNumber(rootCert.getSerialNumber()); - - selector.setForwardSelector(fwSelector); - - Collection col = certStore.getMatches(selector); - - if (col.size() != 1 || !col.contains(pair1)) - { - fail("failed pair1 test"); - } - - col = certStore.getMatches(null); - - if (col.size() != 2) - { - fail("failed null test"); - } - } - - public void performTest() - throws Exception - { - CertificateFactory cf = CertificateFactory.getInstance("X.509", - "BC"); - - X509Certificate rootCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.rootCertBin)); - X509Certificate interCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.interCertBin)); - X509Certificate finalCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.finalCertBin)); - X509CRL rootCrl = (X509CRL)cf.generateCRL(new ByteArrayInputStream( - CertPathTest.rootCrlBin)); - X509CRL interCrl = (X509CRL)cf - .generateCRL(new ByteArrayInputStream( - CertPathTest.interCrlBin)); - - // Testing CollectionCertStore generation from List - List certList = new ArrayList(); - certList.add(rootCert); - certList.add(interCert); - certList.add(finalCert); - X509CollectionStoreParameters ccsp = new X509CollectionStoreParameters(certList); - X509Store certStore = X509Store.getInstance("Certificate/Collection", ccsp, "BC"); - // set default to be the same as for SUN X500 name - X509Principal.DefaultReverse = true; - - // Searching for rootCert by subjectDN - - X509CertStoreSelector targetConstraints = new X509CertStoreSelector(); - targetConstraints.setSubject(PrincipalUtil.getSubjectX509Principal(rootCert).getEncoded()); - Collection certs = certStore.getMatches(targetConstraints); - if (certs.size() != 1 || !certs.contains(rootCert)) - { - fail("rootCert not found by subjectDN"); - } - - // Searching for rootCert by subjectDN encoded as byte - targetConstraints = new X509CertStoreSelector(); - targetConstraints.setSubject(PrincipalUtil.getSubjectX509Principal(rootCert).getEncoded()); - certs = certStore.getMatches(targetConstraints); - if (certs.size() != 1 || !certs.contains(rootCert)) - { - fail("rootCert not found by encoded subjectDN"); - } - - X509Principal.DefaultReverse = false; - - // Searching for rootCert by public key encoded as byte - targetConstraints = new X509CertStoreSelector(); - targetConstraints.setSubjectPublicKey(rootCert.getPublicKey().getEncoded()); - certs = certStore.getMatches(targetConstraints); - if (certs.size() != 1 || !certs.contains(rootCert)) - { - fail("rootCert not found by encoded public key"); - } - - // Searching for interCert by issuerDN - targetConstraints = new X509CertStoreSelector(); - targetConstraints.setIssuer(PrincipalUtil.getSubjectX509Principal(rootCert).getEncoded()); - certs = certStore.getMatches(targetConstraints); - if (certs.size() != 2) - { - fail("did not found 2 certs"); - } - if (!certs.contains(rootCert)) - { - fail("rootCert not found"); - } - if (!certs.contains(interCert)) - { - fail("interCert not found"); - } - - // Searching for attribute certificates - X509V2AttributeCertificate attrCert = new X509V2AttributeCertificate(AttrCertTest.attrCert); - X509AttributeCertificate attrCert2 = new X509V2AttributeCertificate(AttrCertTest.certWithBaseCertificateID); - - List attrList = new ArrayList(); - attrList.add(attrCert); - attrList.add(attrCert2); - ccsp = new X509CollectionStoreParameters(attrList); - X509Store store = X509Store.getInstance("AttributeCertificate/Collection", ccsp, "BC"); - X509AttributeCertStoreSelector attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setHolder(attrCert.getHolder()); - if (!attrSelector.getHolder().equals(attrCert.getHolder())) - { - fail("holder get not correct"); - } - Collection attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on holder"); - } - attrSelector.setHolder(attrCert2.getHolder()); - if (attrSelector.getHolder().equals(attrCert.getHolder())) - { - fail("holder get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert2)) - { - fail("attrCert2 not found on holder"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setIssuer(attrCert.getIssuer()); - if (!attrSelector.getIssuer().equals(attrCert.getIssuer())) - { - fail("issuer get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on issuer"); - } - attrSelector.setIssuer(attrCert2.getIssuer()); - if (attrSelector.getIssuer().equals(attrCert.getIssuer())) - { - fail("issuer get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert2)) - { - fail("attrCert2 not found on issuer"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setAttributeCert(attrCert); - if (!attrSelector.getAttributeCert().equals(attrCert)) - { - fail("attrCert get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on attrCert"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setSerialNumber(attrCert.getSerialNumber()); - if (!attrSelector.getSerialNumber().equals(attrCert.getSerialNumber())) - { - fail("serial number get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on serial number"); - } - attrSelector = (X509AttributeCertStoreSelector)attrSelector.clone(); - if (!attrSelector.getSerialNumber().equals(attrCert.getSerialNumber())) - { - fail("serial number get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on serial number"); - } - - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setAttributeCertificateValid(attrCert.getNotBefore()); - if (!attrSelector.getAttributeCertificateValid().equals(attrCert.getNotBefore())) - { - fail("valid get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on valid"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setAttributeCertificateValid(new Date(attrCert.getNotBefore().getTime() - 100)); - attrs = store.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("attrCert found on before"); - } - attrSelector.setAttributeCertificateValid(new Date(attrCert.getNotAfter().getTime() + 100)); - attrs = store.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("attrCert found on after"); - } - attrSelector.setSerialNumber(BigInteger.valueOf(10000)); - attrs = store.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("attrCert found on wrong serial number"); - } - - attrSelector.setAttributeCert(null); - attrSelector.setAttributeCertificateValid(null); - attrSelector.setHolder(null); - attrSelector.setIssuer(null); - attrSelector.setSerialNumber(null); - if (attrSelector.getAttributeCert() != null) - { - fail("null attrCert"); - } - if (attrSelector.getAttributeCertificateValid() != null) - { - fail("null attrCertValid"); - } - if (attrSelector.getHolder() != null) - { - fail("null attrCert holder"); - } - if (attrSelector.getIssuer() != null) - { - fail("null attrCert issuer"); - } - if (attrSelector.getSerialNumber() != null) - { - fail("null attrCert serial"); - } - - attrs = certStore.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("error using wrong selector (attrs)"); - } - - certPairTest(); - } - - public String getName() - { - return "X509Store"; - } - - public static void main(String[] args) - { - Security.addProvider(new BouncyCastleProvider()); - - runTest(new X509StoreTest()); - } - -} |