diff options
Diffstat (limited to 'prov/src/main/jdk1.1/org/bouncycastle')
33 files changed, 0 insertions, 10570 deletions
diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/dsa/DSASigner.java b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/dsa/DSASigner.java deleted file mode 100644 index 381511f9..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/dsa/DSASigner.java +++ /dev/null @@ -1,280 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.dsa; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.Signature; -import java.security.interfaces.DSAKey; -import java.security.spec.AlgorithmParameterSpec; - -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.DSA; -import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.digests.NullDigest; -import org.bouncycastle.crypto.digests.SHA1Digest; -import org.bouncycastle.crypto.digests.SHA224Digest; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.digests.SHA384Digest; -import org.bouncycastle.crypto.digests.SHA512Digest; -import org.bouncycastle.crypto.params.ParametersWithRandom; - -public class DSASigner - extends Signature - implements PKCSObjectIdentifiers, X509ObjectIdentifiers -{ - private Digest digest; - private DSA signer; - private SecureRandom random; - - protected DSASigner( - Digest digest, - DSA signer) - { - super("DSA"); - this.digest = digest; - this.signer = signer; - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param; - -// if (publicKey instanceof GOST3410Key) -// { -// param = GOST3410Util.generatePublicKeyParameter(publicKey); -// } -// else if (publicKey instanceof DSAKey) - if (publicKey instanceof DSAKey) - { - param = DSAUtil.generatePublicKeyParameter(publicKey); - } - else - { - try - { - byte[] bytes = publicKey.getEncoded(); - - publicKey = new BCDSAPublicKey(SubjectPublicKeyInfo.getInstance(bytes)); - - if (publicKey instanceof DSAKey) - { - param = DSAUtil.generatePublicKeyParameter(publicKey); - } - else - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - catch (Exception e) - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - - digest.reset(); - signer.init(false, param); - } - - protected void engineInitSign( - PrivateKey privateKey, - SecureRandom random) - throws InvalidKeyException - { - this.random = random; - engineInitSign(privateKey); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - CipherParameters param; - -// if (privateKey instanceof GOST3410Key) -// { -// param = GOST3410Util.generatePrivateKeyParameter(privateKey); -// } -// else -// { - param = DSAUtil.generatePrivateKeyParameter(privateKey); -// } - - if (random != null) - { - param = new ParametersWithRandom(param, random); - } - - digest.reset(); - signer.init(true, param); - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - BigInteger[] sig = signer.generateSignature(hash); - - return derEncode(sig[0], sig[1]); - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - BigInteger[] sig; - - try - { - sig = derDecode(sigBytes); - } - catch (Exception e) - { - throw new SignatureException("error decoding signature bytes."); - } - - return signer.verifySignature(hash, sig[0], sig[1]); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)"> - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - private byte[] derEncode( - BigInteger r, - BigInteger s) - throws IOException - { - ASN1Integer[] rs = new ASN1Integer[]{ new ASN1Integer(r), new ASN1Integer(s) }; - return new DERSequence(rs).getEncoded(ASN1Encoding.DER); - } - - private BigInteger[] derDecode( - byte[] encoding) - throws IOException - { - ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); - return new BigInteger[]{ - ((ASN1Integer)s.getObjectAt(0)).getValue(), - ((ASN1Integer)s.getObjectAt(1)).getValue() - }; - } - - static public class stdDSA - extends DSASigner - { - public stdDSA() - { - super(new SHA1Digest(), new org.bouncycastle.crypto.signers.DSASigner()); - } - } - - static public class dsa224 - extends DSASigner - { - public dsa224() - { - super(new SHA224Digest(), new org.bouncycastle.crypto.signers.DSASigner()); - } - } - - static public class dsa256 - extends DSASigner - { - public dsa256() - { - super(new SHA256Digest(), new org.bouncycastle.crypto.signers.DSASigner()); - } - } - - static public class dsa384 - extends DSASigner - { - public dsa384() - { - super(new SHA384Digest(), new org.bouncycastle.crypto.signers.DSASigner()); - } - } - - static public class dsa512 - extends DSASigner - { - public dsa512() - { - super(new SHA512Digest(), new org.bouncycastle.crypto.signers.DSASigner()); - } - } - - static public class noneDSA - extends DSASigner - { - public noneDSA() - { - super(new NullDigest(), new org.bouncycastle.crypto.signers.DSASigner()); - } - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/ecgost/SignatureSpi.java b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/ecgost/SignatureSpi.java deleted file mode 100644 index 65fa03eb..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/ecgost/SignatureSpi.java +++ /dev/null @@ -1,221 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.ecgost; - -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.spec.AlgorithmParameterSpec; - -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.DSA; -import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.digests.GOST3411Digest; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.crypto.signers.ECGOST3410Signer; -import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.bouncycastle.jce.interfaces.ECKey; -import org.bouncycastle.jce.interfaces.ECPublicKey; -import org.bouncycastle.jce.interfaces.GOST3410Key; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.jcajce.provider.asymmetric.util.GOST3410Util; - -public class SignatureSpi - extends java.security.Signature - implements PKCSObjectIdentifiers, X509ObjectIdentifiers -{ - private Digest digest; - private DSA signer; - private SecureRandom appRandom; - - public SignatureSpi() - { - super("ECGOST3410"); - this.digest = new GOST3411Digest(); - this.signer = new ECGOST3410Signer(); - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param; - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else if (publicKey instanceof GOST3410Key) - { - param = GOST3410Util.generatePublicKeyParameter(publicKey); - } - else - { - try - { - byte[] bytes = publicKey.getEncoded(); - - publicKey = BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(bytes)); - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - catch (Exception e) - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - - digest.reset(); - signer.init(false, param); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - CipherParameters param; - - if (privateKey instanceof ECKey) - { - param = ECUtil.generatePrivateKeyParameter(privateKey); - } - else - { - param = GOST3410Util.generatePrivateKeyParameter(privateKey); - } - - digest.reset(); - - if (appRandom != null) - { - signer.init(true, new ParametersWithRandom(param, appRandom)); - } - else - { - signer.init(true, param); - } - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - byte[] sigBytes = new byte[64]; - BigInteger[] sig = signer.generateSignature(hash); - byte[] r = sig[0].toByteArray(); - byte[] s = sig[1].toByteArray(); - - if (s[0] != 0) - { - System.arraycopy(s, 0, sigBytes, 32 - s.length, s.length); - } - else - { - System.arraycopy(s, 1, sigBytes, 32 - (s.length - 1), s.length - 1); - } - - if (r[0] != 0) - { - System.arraycopy(r, 0, sigBytes, 64 - r.length, r.length); - } - else - { - System.arraycopy(r, 1, sigBytes, 64 - (r.length - 1), r.length - 1); - } - - return sigBytes; - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - BigInteger[] sig; - - try - { - byte[] r = new byte[32]; - byte[] s = new byte[32]; - - System.arraycopy(sigBytes, 0, s, 0, 32); - - System.arraycopy(sigBytes, 32, r, 0, 32); - - sig = new BigInteger[2]; - sig[0] = new BigInteger(1, r); - sig[1] = new BigInteger(1, s); - } - catch (Exception e) - { - throw new SignatureException("error decoding signature bytes."); - } - - return signer.verifySignature(hash, sig[0], sig[1]); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)"> - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/gost/SignatureSpi.java b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/gost/SignatureSpi.java deleted file mode 100644 index 22aaa82f..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/gost/SignatureSpi.java +++ /dev/null @@ -1,230 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.gost; - -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.spec.AlgorithmParameterSpec; - -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.DSA; -import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.digests.GOST3411Digest; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.crypto.signers.GOST3410Signer; -import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.bouncycastle.jce.interfaces.ECKey; -import org.bouncycastle.jce.interfaces.ECPublicKey; -import org.bouncycastle.jce.interfaces.GOST3410Key; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.jcajce.provider.asymmetric.util.GOST3410Util; - -public class SignatureSpi - extends java.security.Signature - implements PKCSObjectIdentifiers, X509ObjectIdentifiers -{ - private Digest digest; - private DSA signer; - private SecureRandom random; - - public SignatureSpi() - { - super("GOST3410"); - this.digest = new GOST3411Digest(); - this.signer = new GOST3410Signer(); - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param; - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else if (publicKey instanceof GOST3410Key) - { - param = GOST3410Util.generatePublicKeyParameter(publicKey); - } - else - { - try - { - byte[] bytes = publicKey.getEncoded(); - - publicKey = BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(bytes)); - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - catch (Exception e) - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - - digest.reset(); - signer.init(false, param); - } - - protected void engineInitSign( - PrivateKey privateKey, - SecureRandom random) - throws InvalidKeyException - { - this.random = random; - engineInitSign(privateKey); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - CipherParameters param; - - if (privateKey instanceof ECKey) - { - param = ECUtil.generatePrivateKeyParameter(privateKey); - } - else - { - param = GOST3410Util.generatePrivateKeyParameter(privateKey); - } - - digest.reset(); - - if (random != null) - { - signer.init(true, new ParametersWithRandom(param, random)); - } - else - { - signer.init(true, param); - } - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - byte[] sigBytes = new byte[64]; - BigInteger[] sig = signer.generateSignature(hash); - byte[] r = sig[0].toByteArray(); - byte[] s = sig[1].toByteArray(); - - if (s[0] != 0) - { - System.arraycopy(s, 0, sigBytes, 32 - s.length, s.length); - } - else - { - System.arraycopy(s, 1, sigBytes, 32 - (s.length - 1), s.length - 1); - } - - if (r[0] != 0) - { - System.arraycopy(r, 0, sigBytes, 64 - r.length, r.length); - } - else - { - System.arraycopy(r, 1, sigBytes, 64 - (r.length - 1), r.length - 1); - } - - return sigBytes; - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - BigInteger[] sig; - - try - { - byte[] r = new byte[32]; - byte[] s = new byte[32]; - - System.arraycopy(sigBytes, 0, s, 0, 32); - - System.arraycopy(sigBytes, 32, r, 0, 32); - - sig = new BigInteger[2]; - sig[0] = new BigInteger(1, r); - sig[1] = new BigInteger(1, s); - } - catch (Exception e) - { - throw new SignatureException("error decoding signature bytes."); - } - - return signer.verifySignature(hash, sig[0], sig[1]); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)"> - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/rsa/DigestSignatureSpi.java b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/rsa/DigestSignatureSpi.java deleted file mode 100644 index d909f94a..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/rsa/DigestSignatureSpi.java +++ /dev/null @@ -1,368 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.rsa; - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SignatureException; -import java.security.Signature; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.AlgorithmParameterSpec; - -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.DigestInfo; -import org.bouncycastle.crypto.AsymmetricBlockCipher; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.digests.MD2Digest; -import org.bouncycastle.crypto.digests.MD4Digest; -import org.bouncycastle.crypto.digests.MD5Digest; -import org.bouncycastle.crypto.digests.NullDigest; -import org.bouncycastle.crypto.digests.RIPEMD128Digest; -import org.bouncycastle.crypto.digests.RIPEMD160Digest; -import org.bouncycastle.crypto.digests.RIPEMD256Digest; -import org.bouncycastle.crypto.digests.SHA1Digest; -import org.bouncycastle.crypto.digests.SHA224Digest; -import org.bouncycastle.crypto.digests.SHA256Digest; -import org.bouncycastle.crypto.digests.SHA384Digest; -import org.bouncycastle.crypto.digests.SHA512Digest; -import org.bouncycastle.crypto.encodings.PKCS1Encoding; -import org.bouncycastle.crypto.engines.RSABlindedEngine; - -public class DigestSignatureSpi - extends Signature -{ - private Digest digest; - private AsymmetricBlockCipher cipher; - private AlgorithmIdentifier algId; - - // care - this constructor is actually used by outside organisations - protected DigestSignatureSpi( - Digest digest, - AsymmetricBlockCipher cipher) - { - super(digest.getAlgorithmName() + "withRSA"); - this.digest = digest; - this.cipher = cipher; - this.algId = null; - } - - // care - this constructor is actually used by outside organisations - protected DigestSignatureSpi( - ASN1ObjectIdentifier objId, - Digest digest, - AsymmetricBlockCipher cipher) - { - super(digest.getAlgorithmName() + "withRSA"); - this.digest = digest; - this.cipher = cipher; - this.algId = new AlgorithmIdentifier(objId, DERNull.INSTANCE); - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - if (!(publicKey instanceof RSAPublicKey)) - { - throw new InvalidKeyException("Supplied key (" + getType(publicKey) + ") is not a RSAPublicKey instance"); - } - - CipherParameters param = RSAUtil.generatePublicKeyParameter((RSAPublicKey)publicKey); - - digest.reset(); - cipher.init(false, param); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - if (!(privateKey instanceof RSAPrivateKey)) - { - throw new InvalidKeyException("Supplied key (" + getType(privateKey) + ") is not a RSAPrivateKey instance"); - } - - CipherParameters param = RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey); - - digest.reset(); - - cipher.init(true, param); - } - - private String getType( - Object o) - { - if (o == null) - { - return null; - } - - return o.getClass().getName(); - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - byte[] bytes = derEncode(hash); - - return cipher.processBlock(bytes, 0, bytes.length); - } - catch (ArrayIndexOutOfBoundsException e) - { - throw new SignatureException("key too small for signature type"); - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - byte[] sig; - byte[] expected; - - try - { - sig = cipher.processBlock(sigBytes, 0, sigBytes.length); - - expected = derEncode(hash); - } - catch (Exception e) - { - return false; - } - - if (sig.length == expected.length) - { - for (int i = 0; i < sig.length; i++) - { - if (sig[i] != expected[i]) - { - return false; - } - } - } - else if (sig.length == expected.length - 2) // NULL left out - { - int sigOffset = sig.length - hash.length - 2; - int expectedOffset = expected.length - hash.length - 2; - - expected[1] -= 2; // adjust lengths - expected[3] -= 2; - - for (int i = 0; i < hash.length; i++) - { - if (sig[sigOffset + i] != expected[expectedOffset + i]) // check hash - { - return false; - } - } - - for (int i = 0; i < sigOffset; i++) - { - if (sig[i] != expected[i]) // check header less NULL - { - return false; - } - } - } - else - { - return false; - } - - return true; - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)"> - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - return null; - } - - protected AlgorithmParameters engineGetParameters() - { - return null; - } - - private byte[] derEncode( - byte[] hash) - throws IOException - { - if (algId == null) - { - // For raw RSA, the DigestInfo must be prepared externally - return hash; - } - - DigestInfo dInfo = new DigestInfo(algId, hash); - - return dInfo.getEncoded(ASN1Encoding.DER); - } - - static public class SHA1 - extends DigestSignatureSpi - { - public SHA1() - { - super(OIWObjectIdentifiers.idSHA1, new SHA1Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class SHA224 - extends DigestSignatureSpi - { - public SHA224() - { - super(NISTObjectIdentifiers.id_sha224, new SHA224Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class SHA256 - extends DigestSignatureSpi - { - public SHA256() - { - super(NISTObjectIdentifiers.id_sha256, new SHA256Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class SHA384 - extends DigestSignatureSpi - { - public SHA384() - { - super(NISTObjectIdentifiers.id_sha384, new SHA384Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class SHA512 - extends DigestSignatureSpi - { - public SHA512() - { - super(NISTObjectIdentifiers.id_sha512, new SHA512Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class MD2 - extends DigestSignatureSpi - { - public MD2() - { - super(PKCSObjectIdentifiers.md2, new MD2Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class MD4 - extends DigestSignatureSpi - { - public MD4() - { - super(PKCSObjectIdentifiers.md4, new MD4Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class MD5 - extends DigestSignatureSpi - { - public MD5() - { - super(PKCSObjectIdentifiers.md5, new MD5Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class RIPEMD160 - extends DigestSignatureSpi - { - public RIPEMD160() - { - super(TeleTrusTObjectIdentifiers.ripemd160, new RIPEMD160Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class RIPEMD128 - extends DigestSignatureSpi - { - public RIPEMD128() - { - super(TeleTrusTObjectIdentifiers.ripemd128, new RIPEMD128Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class RIPEMD256 - extends DigestSignatureSpi - { - public RIPEMD256() - { - super(TeleTrusTObjectIdentifiers.ripemd256, new RIPEMD256Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class noneRSA - extends DigestSignatureSpi - { - public noneRSA() - { - super(new NullDigest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/rsa/ISOSignatureSpi.java b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/rsa/ISOSignatureSpi.java deleted file mode 100644 index eb5d8aac..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/rsa/ISOSignatureSpi.java +++ /dev/null @@ -1,143 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.rsa; - -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SignatureException; -import java.security.Signature; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.AlgorithmParameterSpec; - -import org.bouncycastle.crypto.AsymmetricBlockCipher; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.digests.MD5Digest; -import org.bouncycastle.crypto.digests.RIPEMD160Digest; -import org.bouncycastle.crypto.digests.SHA1Digest; -import org.bouncycastle.crypto.engines.RSABlindedEngine; -import org.bouncycastle.crypto.signers.ISO9796d2Signer; - -public class ISOSignatureSpi - extends Signature -{ - private ISO9796d2Signer signer; - - protected ISOSignatureSpi( - Digest digest, - AsymmetricBlockCipher cipher) - { - super(digest.getAlgorithmName() + "withRSA/ISO9796-2"); - signer = new ISO9796d2Signer(cipher, digest, true); - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param = RSAUtil.generatePublicKeyParameter((RSAPublicKey)publicKey); - - signer.init(false, param); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - CipherParameters param = RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey); - - signer.init(true, param); - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - signer.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - signer.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - try - { - byte[] sig = signer.generateSignature(); - - return sig; - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - boolean yes = signer.verifySignature(sigBytes); - - return yes; - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)"> - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - static public class SHA1WithRSAEncryption - extends ISOSignatureSpi - { - public SHA1WithRSAEncryption() - { - super(new SHA1Digest(), new RSABlindedEngine()); - } - } - - static public class MD5WithRSAEncryption - extends ISOSignatureSpi - { - public MD5WithRSAEncryption() - { - super(new MD5Digest(), new RSABlindedEngine()); - } - } - - static public class RIPEMD160WithRSAEncryption - extends ISOSignatureSpi - { - public RIPEMD160WithRSAEncryption() - { - super(new RIPEMD160Digest(), new RSABlindedEngine()); - } - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/util/DSABase.java b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/util/DSABase.java deleted file mode 100644 index 479fafcc..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/util/DSABase.java +++ /dev/null @@ -1,129 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.util; - -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.AlgorithmParameterSpec; - -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; -import org.bouncycastle.crypto.DSA; -import org.bouncycastle.crypto.Digest; - -public abstract class DSABase - extends Signature - implements PKCSObjectIdentifiers, X509ObjectIdentifiers -{ - protected Digest digest; - protected DSA signer; - protected DSAEncoder encoder; - private SecureRandom appRandom; - - protected DSABase( - String name, - Digest digest, - DSA signer, - DSAEncoder encoder) - { - super(name); - - this.digest = digest; - this.signer = signer; - this.encoder = encoder; - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - doEngineInitSign(privateKey, appRandom); - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - BigInteger[] sig = signer.generateSignature(hash); - - return encoder.encode(sig[0], sig[1]); - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - BigInteger[] sig; - - try - { - sig = encoder.decode(sigBytes); - } - catch (Exception e) - { - throw new SignatureException("error decoding signature bytes."); - } - - return signer.verifySignature(hash, sig[0], sig[1]); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)"> - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - protected abstract void doEngineInitSign(PrivateKey privateKey, SecureRandom random) - throws InvalidKeyException; -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java deleted file mode 100644 index 2ed6ca69..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java +++ /dev/null @@ -1,397 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.security.cert.CRL; -import java.security.cert.CRLException; -import java.security.cert.CertPath; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactorySpi; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1Set; -import org.bouncycastle.asn1.ASN1TaggedObject; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.SignedData; -import org.bouncycastle.asn1.x509.Certificate; -import org.bouncycastle.asn1.x509.CertificateList; -import org.bouncycastle.jce.provider.X509CRLObject; -import org.bouncycastle.jce.provider.X509CertificateObject; - -/** - * class for dealing with X509 certificates. - * <p> - * At the moment this will deal with "-----BEGIN CERTIFICATE-----" to "-----END CERTIFICATE-----" - * base 64 encoded certs, as well as the BER binaries of certificates and some classes of PKCS#7 - * objects. - */ -public class CertificateFactory - extends CertificateFactorySpi -{ - private static final PEMUtil PEM_CERT_PARSER = new PEMUtil("CERTIFICATE"); - private static final PEMUtil PEM_CRL_PARSER = new PEMUtil("CRL"); - - private ASN1Set sData = null; - private int sDataObjectCount = 0; - private InputStream currentStream = null; - - private ASN1Set sCrlData = null; - private int sCrlDataObjectCount = 0; - private InputStream currentCrlStream = null; - - private java.security.cert.Certificate readDERCertificate( - ASN1InputStream dIn) - throws IOException, CertificateParsingException - { - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - - if (seq.size() > 1 - && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) - { - if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) - { - sData = SignedData.getInstance(ASN1Sequence.getInstance( - (ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates(); - - return getCertificate(); - } - } - - return new X509CertificateObject( - Certificate.getInstance(seq)); - } - - private java.security.cert.Certificate getCertificate() - throws CertificateParsingException - { - if (sData != null) - { - while (sDataObjectCount < sData.size()) - { - Object obj = sData.getObjectAt(sDataObjectCount++); - - if (obj instanceof ASN1Sequence) - { - return new X509CertificateObject( - Certificate.getInstance(obj)); - } - } - } - - return null; - } - - private java.security.cert.Certificate readPEMCertificate( - InputStream in) - throws IOException, CertificateParsingException - { - ASN1Sequence seq = PEM_CERT_PARSER.readPEMObject(in); - - if (seq != null) - { - return new X509CertificateObject( - Certificate.getInstance(seq)); - } - - return null; - } - - protected CRL createCRL(CertificateList c) - throws CRLException - { - return new X509CRLObject(c); - } - - private CRL readPEMCRL( - InputStream in) - throws IOException, CRLException - { - ASN1Sequence seq = PEM_CRL_PARSER.readPEMObject(in); - - if (seq != null) - { - return createCRL( - CertificateList.getInstance(seq)); - } - - return null; - } - - private CRL readDERCRL( - ASN1InputStream aIn) - throws IOException, CRLException - { - ASN1Sequence seq = (ASN1Sequence)aIn.readObject(); - - if (seq.size() > 1 - && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) - { - if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) - { - sCrlData = SignedData.getInstance(ASN1Sequence.getInstance( - (ASN1TaggedObject)seq.getObjectAt(1), true)).getCRLs(); - - return getCRL(); - } - } - - return createCRL( - CertificateList.getInstance(seq)); - } - - private CRL getCRL() - throws CRLException - { - if (sCrlData == null || sCrlDataObjectCount >= sCrlData.size()) - { - return null; - } - - return createCRL( - CertificateList.getInstance( - sCrlData.getObjectAt(sCrlDataObjectCount++))); - } - - /** - * Generates a certificate object and initializes it with the data - * read from the input stream inStream. - */ - public java.security.cert.Certificate engineGenerateCertificate( - InputStream in) - throws CertificateException - { - if (currentStream == null) - { - currentStream = in; - sData = null; - sDataObjectCount = 0; - } - else if (currentStream != in) // reset if input stream has changed - { - currentStream = in; - sData = null; - sDataObjectCount = 0; - } - - try - { - if (sData != null) - { - if (sDataObjectCount != sData.size()) - { - return getCertificate(); - } - else - { - sData = null; - sDataObjectCount = 0; - return null; - } - } - - PushbackInputStream pis = new PushbackInputStream(in); - int tag = pis.read(); - - if (tag == -1) - { - return null; - } - - pis.unread(tag); - - if (tag != 0x30) // assume ascii PEM encoded. - { - return readPEMCertificate(pis); - } - else - { - return readDERCertificate(new ASN1InputStream(pis)); - } - } - catch (Exception e) - { - throw new ExCertificateException(e); - } - } - - /** - * Returns a (possibly empty) collection view of the certificates - * read from the given input stream inStream. - */ - public Collection engineGenerateCertificates( - InputStream inStream) - throws CertificateException - { - java.security.cert.Certificate cert; - List certs = new ArrayList(); - - while ((cert = engineGenerateCertificate(inStream)) != null) - { - certs.add(cert); - } - - return certs; - } - - /** - * Generates a certificate revocation list (CRL) object and initializes - * it with the data read from the input stream inStream. - */ - public CRL engineGenerateCRL( - InputStream inStream) - throws CRLException - { - if (currentCrlStream == null) - { - currentCrlStream = inStream; - sCrlData = null; - sCrlDataObjectCount = 0; - } - else if (currentCrlStream != inStream) // reset if input stream has changed - { - currentCrlStream = inStream; - sCrlData = null; - sCrlDataObjectCount = 0; - } - - try - { - if (sCrlData != null) - { - if (sCrlDataObjectCount != sCrlData.size()) - { - return getCRL(); - } - else - { - sCrlData = null; - sCrlDataObjectCount = 0; - return null; - } - } - - PushbackInputStream pis = new PushbackInputStream(inStream); - int tag = pis.read(); - - if (tag == -1) - { - return null; - } - - pis.unread(tag); - - if (tag != 0x30) // assume ascii PEM encoded. - { - return readPEMCRL(pis); - } - else - { // lazy evaluate to help processing of large CRLs - return readDERCRL(new ASN1InputStream(pis, true)); - } - } - catch (CRLException e) - { - throw e; - } - catch (Exception e) - { - throw new CRLException(e.toString()); - } - } - - /** - * Returns a (possibly empty) collection view of the CRLs read from - * the given input stream inStream. - * - * The inStream may contain a sequence of DER-encoded CRLs, or - * a PKCS#7 CRL set. This is a PKCS#7 SignedData object, with the - * only signficant field being crls. In particular the signature - * and the contents are ignored. - */ - public Collection engineGenerateCRLs( - InputStream inStream) - throws CRLException - { - CRL crl; - List crls = new ArrayList(); - - while ((crl = engineGenerateCRL(inStream)) != null) - { - crls.add(crl); - } - - return crls; - } - - public Iterator engineGetCertPathEncodings() - { - return null; // TODO: PKIXCertPath.certPathEncodings.iterator(); - } - - public CertPath engineGenerateCertPath( - InputStream inStream) - throws CertificateException - { - return engineGenerateCertPath(inStream, "PkiPath"); - } - - public CertPath engineGenerateCertPath( - InputStream inStream, - String encoding) - throws CertificateException - { - return new PKIXCertPath(inStream, encoding); - } - - public CertPath engineGenerateCertPath( - List certificates) - throws CertificateException - { - Iterator iter = certificates.iterator(); - Object obj; - while (iter.hasNext()) - { - obj = iter.next(); - if (obj != null) - { - if (!(obj instanceof X509Certificate)) - { - throw new CertificateException("list contains non X509Certificate object while creating CertPath\n" + obj.toString()); - } - } - } - return new PKIXCertPath(certificates); - } - - private class ExCertificateException - extends CertificateException - { - private Throwable cause; - - public ExCertificateException(Throwable cause) - { - this.cause = cause; - } - - public ExCertificateException(String msg, Throwable cause) - { - super(msg); - - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java deleted file mode 100644 index 1b97e5fd..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java +++ /dev/null @@ -1,379 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.security.NoSuchProviderException; -import java.security.cert.CertPath; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.PrincipalUtil; -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.pkcs.ContentInfo; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.SignedData; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.io.pem.PemObject; -import org.bouncycastle.util.io.pem.PemWriter; - -/** - * CertPath implementation for X.509 certificates. - * <br /> - **/ -public class PKIXCertPath - extends CertPath -{ - static final List certPathEncodings; - - static - { - List encodings = new ArrayList(); - encodings.add("PkiPath"); - encodings.add("PEM"); - encodings.add("PKCS7"); - certPathEncodings = Collections.unmodifiableList(encodings); - } - - private List certificates; - - /** - * @param certs - */ - private List sortCerts( - List certs) - { - try - { - if (certs.size() < 2) - { - return certs; - } - - X509Principal issuer = PrincipalUtil.getIssuerX509Principal(((X509Certificate)certs.get(0))); - boolean okay = true; - - for (int i = 1; i != certs.size(); i++) - { - X509Certificate cert = (X509Certificate)certs.get(i); - - if (issuer.equals(PrincipalUtil.getSubjectX509Principal(cert))) - { - issuer = PrincipalUtil.getIssuerX509Principal(((X509Certificate)certs.get(i))); - } - else - { - okay = false; - break; - } - } - - if (okay) - { - return certs; - } - - // find end-entity cert - List retList = new ArrayList(certs.size()); - List orig = new ArrayList(certs); - - for (int i = 0; i < certs.size(); i++) - { - X509Certificate cert = (X509Certificate)certs.get(i); - boolean found = false; - - X509Principal subject = PrincipalUtil.getSubjectX509Principal(cert); - - for (int j = 0; j != certs.size(); j++) - { - X509Certificate c = (X509Certificate)certs.get(j); - if (PrincipalUtil.getIssuerX509Principal(c).equals(subject)) - { - found = true; - break; - } - } - - if (!found) - { - retList.add(cert); - certs.remove(i); - } - } - - // can only have one end entity cert - something's wrong, give up. - if (retList.size() > 1) - { - return orig; - } - - for (int i = 0; i != retList.size(); i++) - { - issuer = PrincipalUtil.getIssuerX509Principal(((X509Certificate)retList.get(i))); - - for (int j = 0; j < certs.size(); j++) - { - X509Certificate c = (X509Certificate)certs.get(j); - if (issuer.equals(PrincipalUtil.getSubjectX509Principal(c))) - { - retList.add(c); - certs.remove(j); - break; - } - } - } - - // make sure all certificates are accounted for. - if (certs.size() > 0) - { - return orig; - } - - return retList; - } - catch (Exception e) - { - return certs; - } - } - - PKIXCertPath(List certificates) - { - super("X.509"); - this.certificates = sortCerts(new ArrayList(certificates)); - } - - /** - * Creates a CertPath of the specified type. - * This constructor is protected because most users should use - * a CertificateFactory to create CertPaths. - **/ - PKIXCertPath( - InputStream inStream, - String encoding) - throws CertificateException - { - super("X.509"); - try - { - if (encoding.equalsIgnoreCase("PkiPath")) - { - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Primitive derObject = derInStream.readObject(); - if (!(derObject instanceof ASN1Sequence)) - { - throw new CertificateException("input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath"); - } - Enumeration e = ((ASN1Sequence)derObject).getObjects(); - certificates = new ArrayList(); - CertificateFactory certFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); - while (e.hasMoreElements()) - { - ASN1Encodable element = (ASN1Encodable)e.nextElement(); - byte[] encoded = element.toASN1Primitive().getEncoded(ASN1Encoding.DER); - certificates.add(0, certFactory.generateCertificate( - new ByteArrayInputStream(encoded))); - } - } - else if (encoding.equalsIgnoreCase("PKCS7") || encoding.equalsIgnoreCase("PEM")) - { - inStream = new BufferedInputStream(inStream); - certificates = new ArrayList(); - CertificateFactory certFactory= CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); - Certificate cert; - while ((cert = certFactory.generateCertificate(inStream)) != null) - { - certificates.add(cert); - } - } - else - { - throw new CertificateException("unsupported encoding: " + encoding); - } - } - catch (IOException ex) - { - throw new CertificateException("IOException throw while decoding CertPath:\n" + ex.toString()); - } - catch (NoSuchProviderException ex) - { - throw new CertificateException("BouncyCastle provider not found while trying to get a CertificateFactory:\n" + ex.toString()); - } - - this.certificates = sortCerts(certificates); - } - - /** - * Returns an iteration of the encodings supported by this - * certification path, with the default encoding - * first. Attempts to modify the returned Iterator via its - * remove method result in an UnsupportedOperationException. - * - * @return an Iterator over the names of the supported encodings (as Strings) - **/ - public Iterator getEncodings() - { - return certPathEncodings.iterator(); - } - - /** - * Returns the encoded form of this certification path, using - * the default encoding. - * - * @return the encoded bytes - * @exception java.security.cert.CertificateEncodingException if an encoding error occurs - **/ - public byte[] getEncoded() - throws CertificateEncodingException - { - Iterator iter = getEncodings(); - if (iter.hasNext()) - { - Object enc = iter.next(); - if (enc instanceof String) - { - return getEncoded((String)enc); - } - } - return null; - } - - /** - * Returns the encoded form of this certification path, using - * the specified encoding. - * - * @param encoding the name of the encoding to use - * @return the encoded bytes - * @exception java.security.cert.CertificateEncodingException if an encoding error - * occurs or the encoding requested is not supported - * - **/ - public byte[] getEncoded(String encoding) - throws CertificateEncodingException - { - if (encoding.equalsIgnoreCase("PkiPath")) - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - ListIterator iter = certificates.listIterator(certificates.size()); - while (iter.hasPrevious()) - { - v.add(toASN1Object((X509Certificate)iter.previous())); - } - - return toDEREncoded(new DERSequence(v)); - } - else if (encoding.equalsIgnoreCase("PKCS7")) - { - ContentInfo encInfo = new ContentInfo(PKCSObjectIdentifiers.data, null); - - ASN1EncodableVector v = new ASN1EncodableVector(); - for (int i = 0; i != certificates.size(); i++) - { - v.add(toASN1Object((X509Certificate)certificates.get(i))); - } - - SignedData sd = new SignedData( - new ASN1Integer(1), - new DERSet(), - encInfo, - new DERSet(v), - null, - new DERSet()); - - return toDEREncoded(new ContentInfo( - PKCSObjectIdentifiers.signedData, sd)); - } - else if (encoding.equalsIgnoreCase("PEM")) - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - PemWriter pWrt = new PemWriter(new OutputStreamWriter(bOut)); - - try - { - for (int i = 0; i != certificates.size(); i++) - { - pWrt.writeObject(new PemObject("CERTIFICATE", ((X509Certificate)certificates.get(i)).getEncoded())); - } - - pWrt.close(); - } - catch (Exception e) - { - throw new CertificateEncodingException("can't encode certificate for PEM encoded path"); - } - - return bOut.toByteArray(); - } - else - { - throw new CertificateEncodingException("unsupported encoding: " + encoding); - } - } - - /** - * Returns the list of certificates in this certification - * path. The List returned must be immutable and thread-safe. - * - * @return an immutable List of Certificates (may be empty, but not null) - **/ - public List getCertificates() - { - return Collections.unmodifiableList(new ArrayList(certificates)); - } - - /** - * Return a DERObject containing the encoded certificate. - * - * @param cert the X509Certificate object to be encoded - * - * @return the DERObject - **/ - private ASN1Primitive toASN1Object( - X509Certificate cert) - throws CertificateEncodingException - { - try - { - return new ASN1InputStream(cert.getEncoded()).readObject(); - } - catch (Exception e) - { - throw new CertificateEncodingException("Exception while encoding certificate: " + e.toString()); - } - } - - private byte[] toDEREncoded(ASN1Encodable obj) - throws CertificateEncodingException - { - try - { - return obj.toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException("Exception thrown: " + e); - } - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/SignatureUtil.java b/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/SignatureUtil.java deleted file mode 100644 index af18e625..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jcajce/provider/asymmetric/x509/SignatureUtil.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Signature; -import java.security.SignatureException; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1Null; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.RSASSAPSSparams; -import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; - -class SignatureUtil -{ - private static final ASN1Null derNull = new DERNull(); - - static String getSignatureName( - AlgorithmIdentifier sigAlgId) - { - ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !derNull.equals(params)) - { - if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { - RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - - return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "withRSAandMGF1"; - } - if (sigAlgId.getAlgorithm().equals(X9ObjectIdentifiers.ecdsa_with_SHA2)) - { - ASN1Sequence ecDsaParams = ASN1Sequence.getInstance(params); - - return getDigestAlgName((ASN1ObjectIdentifier)ecDsaParams.getObjectAt(0)) + "withECDSA"; - } - } - - return sigAlgId.getAlgorithm().getId(); - } - - /** - * Return the digest algorithm using one of the standard JCA string - * representations rather the the algorithm identifier (if possible). - */ - private static String getDigestAlgName( - ASN1ObjectIdentifier digestAlgOID) - { - if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) - { - return "MD5"; - } - else if (OIWObjectIdentifiers.idSHA1.equals(digestAlgOID)) - { - return "SHA1"; - } - else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOID)) - { - return "SHA224"; - } - else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOID)) - { - return "SHA256"; - } - else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOID)) - { - return "SHA384"; - } - else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOID)) - { - return "SHA512"; - } - else if (TeleTrusTObjectIdentifiers.ripemd128.equals(digestAlgOID)) - { - return "RIPEMD128"; - } - else if (TeleTrusTObjectIdentifiers.ripemd160.equals(digestAlgOID)) - { - return "RIPEMD160"; - } - else if (TeleTrusTObjectIdentifiers.ripemd256.equals(digestAlgOID)) - { - return "RIPEMD256"; - } - else if (CryptoProObjectIdentifiers.gostR3411.equals(digestAlgOID)) - { - return "GOST3411"; - } - else - { - return digestAlgOID.getId(); - } - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/MultiCertStoreParameters.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/MultiCertStoreParameters.java deleted file mode 100644 index 2ffa031a..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/MultiCertStoreParameters.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.bouncycastle.jce; - -import java.security.cert.CertStoreParameters; -import java.util.Collection; - -public class MultiCertStoreParameters - implements CertStoreParameters -{ - private Collection certStores; - private boolean searchAllStores; - - /** - * Create a parameters object which specifies searching of all the passed in stores. - * - * @param certStores CertStores making up the multi CertStore - */ - public MultiCertStoreParameters(Collection certStores) - { - this(certStores, true); - } - - /** - * Create a parameters object which can be to used to make a multi store made up - * of the passed in CertStores. If the searchAllStores parameter is false, any search on - * the multi-store will terminate as soon as a search query produces a result. - * - * @param certStores CertStores making up the multi CertStore - * @param searchAllStores true if all CertStores should be searched on request, false if a result - * should be returned on the first successful CertStore query. - */ - public MultiCertStoreParameters(Collection certStores, boolean searchAllStores) - { - this.certStores = certStores; - this.searchAllStores = searchAllStores; - } - - public Collection getCertStores() - { - return certStores; - } - - public boolean getSearchAllStores() - { - return searchAllStores; - } - - public Object clone() - { - return this; - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/netscape/NetscapeCertRequest.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/netscape/NetscapeCertRequest.java deleted file mode 100644 index 427f0a06..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/netscape/NetscapeCertRequest.java +++ /dev/null @@ -1,296 +0,0 @@ -package org.bouncycastle.jce.netscape; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.X509EncodedKeySpec; - -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Object; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.DERIA5String; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; - -/** - * - * - * Handles NetScape certificate request (KEYGEN), these are constructed as: - * <pre><code> - * SignedPublicKeyAndChallenge ::= SEQUENCE { - * publicKeyAndChallenge PublicKeyAndChallenge, - * signatureAlgorithm AlgorithmIdentifier, - * signature BIT STRING - * } - * </pre> - * - * PublicKey's encoded-format has to be X.509. - * - **/ -public class NetscapeCertRequest - extends ASN1Object -{ - AlgorithmIdentifier sigAlg; - AlgorithmIdentifier keyAlg; - byte sigBits []; - String challenge; - DERBitString content; - PublicKey pubkey ; - - private static ASN1Sequence getReq( - byte[] r) - throws IOException - { - ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(r)); - - return ASN1Sequence.getInstance(aIn.readObject()); - } - - public NetscapeCertRequest( - byte[] req) - throws IOException - { - this(getReq(req)); - } - - public NetscapeCertRequest (ASN1Sequence spkac) - { - try - { - - // - // SignedPublicKeyAndChallenge ::= SEQUENCE { - // publicKeyAndChallenge PublicKeyAndChallenge, - // signatureAlgorithm AlgorithmIdentifier, - // signature BIT STRING - // } - // - if (spkac.size() != 3) - { - throw new IllegalArgumentException("invalid SPKAC (size):" - + spkac.size()); - } - - sigAlg = new AlgorithmIdentifier((ASN1Sequence)spkac - .getObjectAt(1)); - sigBits = ((DERBitString)spkac.getObjectAt(2)).getBytes(); - - // - // PublicKeyAndChallenge ::= SEQUENCE { - // spki SubjectPublicKeyInfo, - // challenge IA5STRING - // } - // - ASN1Sequence pkac = (ASN1Sequence)spkac.getObjectAt(0); - - if (pkac.size() != 2) - { - throw new IllegalArgumentException("invalid PKAC (len): " - + pkac.size()); - } - - challenge = ((DERIA5String)pkac.getObjectAt(1)).getString(); - - //this could be dangerous, as ASN.1 decoding/encoding - //could potentially alter the bytes - content = new DERBitString(pkac); - - SubjectPublicKeyInfo pubkeyinfo = new SubjectPublicKeyInfo( - (ASN1Sequence)pkac.getObjectAt(0)); - - X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString( - pubkeyinfo).getBytes()); - - keyAlg = pubkeyinfo.getAlgorithmId(); - pubkey = KeyFactory.getInstance(keyAlg.getObjectId().getId(), "BC") - .generatePublic(xspec); - - } - catch (Exception e) - { - throw new IllegalArgumentException(e.toString()); - } - } - - public NetscapeCertRequest( - String challenge, - AlgorithmIdentifier signing_alg, - PublicKey pub_key) throws NoSuchAlgorithmException, - InvalidKeySpecException, NoSuchProviderException, IOException - { - - this.challenge = challenge; - sigAlg = signing_alg; - pubkey = pub_key; - - ASN1EncodableVector content_der = new ASN1EncodableVector(); - content_der.add(getKeySpec()); - //content_der.add(new SubjectPublicKeyInfo(sigAlg, new RSAPublicKeyStructure(pubkey.getModulus(), pubkey.getPublicExponent()).getDERObject())); - content_der.add(new DERIA5String(challenge)); - - content = new DERBitString(new DERSequence(content_der)); - } - - public String getChallenge() - { - return challenge; - } - - public void setChallenge(String value) - { - challenge = value; - } - - public AlgorithmIdentifier getSigningAlgorithm() - { - return sigAlg; - } - - public void setSigningAlgorithm(AlgorithmIdentifier value) - { - sigAlg = value; - } - - public AlgorithmIdentifier getKeyAlgorithm() - { - return keyAlg; - } - - public void setKeyAlgorithm(AlgorithmIdentifier value) - { - keyAlg = value; - } - - public PublicKey getPublicKey() - { - return pubkey; - } - - public void setPublicKey(PublicKey value) - { - pubkey = value; - } - - public boolean verify(String challenge) throws NoSuchAlgorithmException, - InvalidKeyException, SignatureException, NoSuchProviderException - { - if (!challenge.equals(this.challenge)) - { - return false; - } - - // - // Verify the signature .. shows the response was generated - // by someone who knew the associated private key - // - Signature sig = Signature.getInstance(sigAlg.getObjectId().getId(), - "BC"); - sig.initVerify(pubkey); - sig.update(content.getBytes()); - - return sig.verify(sigBits); - } - - public void sign(PrivateKey priv_key) throws NoSuchAlgorithmException, - InvalidKeyException, SignatureException, NoSuchProviderException, - InvalidKeySpecException - { - sign(priv_key, null); - } - - public void sign(PrivateKey priv_key, SecureRandom rand) - throws NoSuchAlgorithmException, InvalidKeyException, - SignatureException, NoSuchProviderException, - InvalidKeySpecException - { - Signature sig = Signature.getInstance(sigAlg.getAlgorithm().getId(), - "BC"); - - if (rand != null) - { - sig.initSign(priv_key); - } - else - { - sig.initSign(priv_key); - } - - ASN1EncodableVector pkac = new ASN1EncodableVector(); - - pkac.add(getKeySpec()); - pkac.add(new DERIA5String(challenge)); - - try - { - sig.update(new DERSequence(pkac).getEncoded(ASN1Encoding.DER)); - } - catch (IOException ioe) - { - throw new SignatureException(ioe.getMessage()); - } - - sigBits = sig.sign(); - } - - private ASN1Primitive getKeySpec() throws NoSuchAlgorithmException, - InvalidKeySpecException, NoSuchProviderException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - ASN1Primitive obj = null; - try - { - - baos.write(pubkey.getEncoded()); - baos.close(); - - ASN1InputStream derin = new ASN1InputStream( - new ByteArrayInputStream(baos.toByteArray())); - - obj = derin.readObject(); - } - catch (IOException ioe) - { - throw new InvalidKeySpecException(ioe.getMessage()); - } - return obj; - } - - public ASN1Primitive toASN1Primitive() - { - ASN1EncodableVector spkac = new ASN1EncodableVector(); - ASN1EncodableVector pkac = new ASN1EncodableVector(); - - try - { - pkac.add(getKeySpec()); - } - catch (Exception e) - { - //ignore - } - - pkac.add(new DERIA5String(challenge)); - - spkac.add(new DERSequence(pkac)); - spkac.add(sigAlg); - spkac.add(new DERBitString(sigBits)); - - return new DERSequence(spkac); - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/AnnotatedException.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/AnnotatedException.java deleted file mode 100644 index 0141e908..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/AnnotatedException.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bouncycastle.jce.provider; - -public class AnnotatedException - extends Exception -{ - private Throwable _underlyingException; - - AnnotatedException(String string, Throwable e) - { - super(string); - - _underlyingException = e; - } - - AnnotatedException(String string) - { - this(string, null); - } - - Throwable getUnderlyingException() - { - return _underlyingException; - } - - public Throwable getCause() - { - return _underlyingException; - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/BouncyCastleProvider.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/BouncyCastleProvider.java deleted file mode 100644 index 9b9b82bb..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/BouncyCastleProvider.java +++ /dev/null @@ -1,274 +0,0 @@ -package org.bouncycastle.jce.provider; - -import java.io.IOException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.util.HashMap; -import java.util.Map; - -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; -import org.bouncycastle.jcajce.provider.config.ProviderConfiguration; -import org.bouncycastle.jcajce.provider.util.AlgorithmProvider; -import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; - -/** - * To add the provider at runtime use: - * <pre> - * import java.security.Security; - * import org.bouncycastle.jce.provider.BouncyCastleProvider; - * - * Security.addProvider(new BouncyCastleProvider()); - * </pre> - * The provider can also be configured as part of your environment via - * static registration by adding an entry to the java.security properties - * file (found in $JAVA_HOME/jre/lib/security/java.security, where - * $JAVA_HOME is the location of your JDK/JRE distribution). You'll find - * detailed instructions in the file but basically it comes down to adding - * a line: - * <pre> - * <code> - * security.provider.<n>=org.bouncycastle.jce.provider.BouncyCastleProvider - * </code> - * </pre> - * Where <n> is the preference you want the provider at (1 being the - * most preferred). - * <p>Note: JCE algorithm names should be upper-case only so the case insensitive - * test for getInstance works. - */ -public final class BouncyCastleProvider extends Provider - implements ConfigurableProvider -{ - private static String info = "BouncyCastle Security Provider v1.51"; - - public static final String PROVIDER_NAME = "BC"; - - public static final ProviderConfiguration CONFIGURATION = new BouncyCastleProviderConfiguration(); - - private static final Map keyInfoConverters = new HashMap(); - - /* - * Configurable symmetric ciphers - */ - private static final String SYMMETRIC_PACKAGE = "org.bouncycastle.jcajce.provider.symmetric."; - - private static final String[] SYMMETRIC_GENERIC = - { - "PBEPBKDF2", "PBEPKCS12" - }; - - private static final String[] SYMMETRIC_MACS = - { - "SipHash" - }; - - private static final String[] SYMMETRIC_CIPHERS = - { - "AES", "ARC4", "Blowfish", "Camellia", "CAST5", "CAST6", "ChaCha", "DES", "DESede", - "GOST28147", "Grainv1", "Grain128", "HC128", "HC256", "IDEA", "Noekeon", "RC2", "RC5", - "RC6", "Rijndael", "Salsa20", "SEED", "Serpent", "Shacal2", "Skipjack", "TEA", "Twofish", "Threefish", - "VMPC", "VMPCKSA3", "XTEA", "XSalsa20" - }; - - /* - * Configurable asymmetric ciphers - */ - private static final String ASYMMETRIC_PACKAGE = "org.bouncycastle.jcajce.provider.asymmetric."; - - // this one is required for GNU class path - it needs to be loaded first as the - // later ones configure it. - private static final String[] ASYMMETRIC_GENERIC = - { - "X509", "IES" - }; - - private static final String[] ASYMMETRIC_CIPHERS = - { - "DSA", "DH", "EC", "RSA", "GOST", "ECGOST", "ElGamal", "DSTU4145" - }; - - /* - * Configurable digests - */ - private static final String DIGEST_PACKAGE = "org.bouncycastle.jcajce.provider.digest."; - private static final String[] DIGESTS = - { - "GOST3411", "MD2", "MD4", "MD5", "SHA1", "RIPEMD128", "RIPEMD160", "RIPEMD256", "RIPEMD320", "SHA224", "SHA256", "SHA384", "SHA512", "SHA3", "Skein", "SM3", "Tiger", "Whirlpool" - }; - - /* - * Configurable keystores - */ - private static final String KEYSTORE_PACKAGE = "org.bouncycastle.jcajce.provider.keystore."; - private static final String[] KEYSTORES = - { - "BC", "PKCS12" - }; - - /** - * Construct a new provider. This should only be required when - * using runtime registration of the provider using the - * <code>Security.addProvider()</code> mechanism. - */ - public BouncyCastleProvider() - { - super(PROVIDER_NAME, 1.51, info); - - setup(); - } - - private void setup() - { - loadAlgorithms(DIGEST_PACKAGE, DIGESTS); - - loadAlgorithms(SYMMETRIC_PACKAGE, SYMMETRIC_GENERIC); - - loadAlgorithms(SYMMETRIC_PACKAGE, SYMMETRIC_MACS); - - loadAlgorithms(SYMMETRIC_PACKAGE, SYMMETRIC_CIPHERS); - - loadAlgorithms(ASYMMETRIC_PACKAGE, ASYMMETRIC_GENERIC); - - loadAlgorithms(ASYMMETRIC_PACKAGE, ASYMMETRIC_CIPHERS); - - loadAlgorithms(KEYSTORE_PACKAGE, KEYSTORES); - - // - // X509Store - // - put("X509Store.CERTIFICATE/COLLECTION", "org.bouncycastle.jce.provider.X509StoreCertCollection"); - put("X509Store.ATTRIBUTECERTIFICATE/COLLECTION", "org.bouncycastle.jce.provider.X509StoreAttrCertCollection"); - put("X509Store.CRL/COLLECTION", "org.bouncycastle.jce.provider.X509StoreCRLCollection"); - put("X509Store.CERTIFICATEPAIR/COLLECTION", "org.bouncycastle.jce.provider.X509StoreCertPairCollection"); - - put("X509Store.CERTIFICATE/LDAP", "org.bouncycastle.jce.provider.X509StoreLDAPCerts"); - put("X509Store.CRL/LDAP", "org.bouncycastle.jce.provider.X509StoreLDAPCRLs"); - put("X509Store.ATTRIBUTECERTIFICATE/LDAP", "org.bouncycastle.jce.provider.X509StoreLDAPAttrCerts"); - put("X509Store.CERTIFICATEPAIR/LDAP", "org.bouncycastle.jce.provider.X509StoreLDAPCertPairs"); - - // - // X509StreamParser - // - put("X509StreamParser.CERTIFICATE", "org.bouncycastle.jce.provider.X509CertParser"); - put("X509StreamParser.ATTRIBUTECERTIFICATE", "org.bouncycastle.jce.provider.X509AttrCertParser"); - put("X509StreamParser.CRL", "org.bouncycastle.jce.provider.X509CRLParser"); - put("X509StreamParser.CERTIFICATEPAIR", "org.bouncycastle.jce.provider.X509CertPairParser"); - - // - // cipher engines - // - put("Cipher.BROKENPBEWITHMD5ANDDES", "org.bouncycastle.jce.provider.BrokenJCEBlockCipher$BrokePBEWithMD5AndDES"); - - put("Cipher.BROKENPBEWITHSHA1ANDDES", "org.bouncycastle.jce.provider.BrokenJCEBlockCipher$BrokePBEWithSHA1AndDES"); - - - put("Cipher.OLDPBEWITHSHAANDTWOFISH-CBC", "org.bouncycastle.jce.provider.BrokenJCEBlockCipher$OldPBEWithSHAAndTwofish"); - - // Certification Path API - put("CertPathValidator.RFC3281", "org.bouncycastle.jce.provider.PKIXAttrCertPathValidatorSpi"); - put("CertPathBuilder.RFC3281", "org.bouncycastle.jce.provider.PKIXAttrCertPathBuilderSpi"); - put("CertPathValidator.RFC3280", "org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi"); - put("CertPathBuilder.RFC3280", "org.bouncycastle.jce.provider.PKIXCertPathBuilderSpi"); - put("CertPathValidator.PKIX", "org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi"); - put("CertPathBuilder.PKIX", "org.bouncycastle.jce.provider.PKIXCertPathBuilderSpi"); - put("CertStore.Collection", "org.bouncycastle.jce.provider.CertStoreCollectionSpi"); - put("CertStore.LDAP", "org.bouncycastle.jce.provider.X509LDAPCertStoreSpi"); - put("CertStore.Multi", "org.bouncycastle.jce.provider.MultiCertStoreSpi"); - put("Alg.Alias.CertStore.X509LDAP", "LDAP"); - } - - private void loadAlgorithms(String packageName, String[] names) - { - for (int i = 0; i != names.length; i++) - { - Class clazz = null; - try - { - ClassLoader loader = this.getClass().getClassLoader(); - - if (loader != null) - { - clazz = loader.loadClass(packageName + names[i] + "$Mappings"); - } - else - { - clazz = Class.forName(packageName + names[i] + "$Mappings"); - } - } - catch (ClassNotFoundException e) - { - // ignore - } - - if (clazz != null) - { - try - { - ((AlgorithmProvider)clazz.newInstance()).configure(this); - } - catch (Exception e) - { // this should never ever happen!! - throw new InternalError("cannot create instance of " - + packageName + names[i] + "$Mappings : " + e); - } - } - } - } - - public void setParameter(String parameterName, Object parameter) - { - synchronized (CONFIGURATION) - { - ((BouncyCastleProviderConfiguration)CONFIGURATION).setParameter(parameterName, parameter); - } - } - - public boolean hasAlgorithm(String type, String name) - { - return containsKey(type + "." + name) || containsKey("Alg.Alias." + type + "." + name); - } - - public void addAlgorithm(String key, String value) - { - if (containsKey(key)) - { - throw new IllegalStateException("duplicate provider key (" + key + ") found"); - } - - put(key, value); - } - - public void addKeyInfoConverter(ASN1ObjectIdentifier oid, AsymmetricKeyInfoConverter keyInfoConverter) - { - keyInfoConverters.put(oid, keyInfoConverter); - } - - public static PublicKey getPublicKey(SubjectPublicKeyInfo publicKeyInfo) - throws IOException - { - AsymmetricKeyInfoConverter converter = (AsymmetricKeyInfoConverter)keyInfoConverters.get(publicKeyInfo.getAlgorithm().getAlgorithm()); - - if (converter == null) - { - return null; - } - - return converter.generatePublic(publicKeyInfo); - } - - public static PrivateKey getPrivateKey(PrivateKeyInfo privateKeyInfo) - throws IOException - { - AsymmetricKeyInfoConverter converter = (AsymmetricKeyInfoConverter)keyInfoConverters.get(privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm()); - - if (converter == null) - { - return null; - } - - return converter.generatePrivate(privateKeyInfo); - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/BouncyCastleProviderConfiguration.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/BouncyCastleProviderConfiguration.java deleted file mode 100644 index b4de62fb..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/BouncyCastleProviderConfiguration.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.bouncycastle.jce.provider; - -import javax.crypto.spec.DHParameterSpec; - -import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; -import org.bouncycastle.jcajce.provider.config.ProviderConfiguration; -import org.bouncycastle.jce.spec.ECParameterSpec; - -class BouncyCastleProviderConfiguration - implements ProviderConfiguration -{ - private volatile ECParameterSpec ecImplicitCaParams; - private volatile Object dhDefaultParams; - - void setParameter(String parameterName, Object parameter) - { - SecurityManager securityManager = System.getSecurityManager(); - - if (parameterName.equals(ConfigurableProvider.THREAD_LOCAL_EC_IMPLICITLY_CA)) - { - ECParameterSpec curveSpec; - - if (parameter instanceof ECParameterSpec || parameter == null) - { - curveSpec = (ECParameterSpec)parameter; - } - else - { - throw new IllegalArgumentException("not a valid ECParameterSpec"); - } - - ecImplicitCaParams = (ECParameterSpec)curveSpec; - } - else if (parameterName.equals(ConfigurableProvider.EC_IMPLICITLY_CA)) - { - if (parameter instanceof ECParameterSpec || parameter == null) - { - ecImplicitCaParams = (ECParameterSpec)parameter; - } - else // assume java.security.spec - { - throw new IllegalArgumentException("not a valid ECParameterSpec"); - } - } - else if (parameterName.equals(ConfigurableProvider.THREAD_LOCAL_DH_DEFAULT_PARAMS)) - { - Object dhSpec; - - - if (parameter instanceof DHParameterSpec || parameter instanceof DHParameterSpec[] || parameter == null) - { - dhSpec = parameter; - } - else - { - throw new IllegalArgumentException("not a valid DHParameterSpec"); - } - - dhDefaultParams = dhSpec; - } - else if (parameterName.equals(ConfigurableProvider.DH_DEFAULT_PARAMS)) - { - - if (parameter instanceof DHParameterSpec || parameter instanceof DHParameterSpec[] || parameter == null) - { - dhDefaultParams = parameter; - } - else - { - throw new IllegalArgumentException("not a valid DHParameterSpec or DHParameterSpec[]"); - } - } - } - - public ECParameterSpec getEcImplicitlyCa() - { - return ecImplicitCaParams; - } - - public DHParameterSpec getDHDefaultParameters(int keySize) - { - Object params = dhDefaultParams; - - if (params instanceof DHParameterSpec) - { - DHParameterSpec spec = (DHParameterSpec)params; - - if (spec.getP().bitLength() == keySize) - { - return spec; - } - } - else if (params instanceof DHParameterSpec[]) - { - DHParameterSpec[] specs = (DHParameterSpec[])params; - - for (int i = 0; i != specs.length; i++) - { - if (specs[i].getP().bitLength() == keySize) - { - return specs[i]; - } - } - } - - return null; - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/CertStoreCollectionSpi.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/CertStoreCollectionSpi.java deleted file mode 100644 index 9d234b7c..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/CertStoreCollectionSpi.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.bouncycastle.jce.provider; - -import java.security.InvalidAlgorithmParameterException; -import java.security.cert.CRL; -import java.security.cert.CRLSelector; -import java.security.cert.CertSelector; -import java.security.cert.CertStoreException; -import java.security.cert.CertStoreParameters; -import java.security.cert.CertStoreSpi; -import java.security.cert.Certificate; -import java.security.cert.CollectionCertStoreParameters; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -public class CertStoreCollectionSpi extends CertStoreSpi -{ - private CollectionCertStoreParameters params; - - public CertStoreCollectionSpi(CertStoreParameters params) - throws InvalidAlgorithmParameterException - { - super(params); - - if (!(params instanceof CollectionCertStoreParameters)) - { - throw new InvalidAlgorithmParameterException( "org.bouncycastle.jce.provider.CertStoreCollectionSpi: parameter must be a CollectionCertStoreParameters object\n" + params.toString() ); - } - - this.params = (CollectionCertStoreParameters)params; - } - - public Collection engineGetCertificates( - CertSelector selector) - throws CertStoreException - { - Set col = new HashSet(); - Iterator iter = params.getCollection().iterator(); - - if (selector == null) - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof Certificate) - { - col.add(obj); - } - } - } - else - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if ((obj instanceof Certificate) && selector.match((Certificate)obj)) - { - col.add(obj); - } - } - } - - return col; - } - - - public Collection engineGetCRLs( - CRLSelector selector) - throws CertStoreException - { - Set col = new HashSet(); - Iterator iter = params.getCollection().iterator(); - - if (selector == null) - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof CRL) - { - col.add(obj); - } - } - } - else - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if ((obj instanceof CRL) && selector.match((CRL)obj)) - { - col.add(obj); - } - } - } - - return col; - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/MultiCertStoreSpi.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/MultiCertStoreSpi.java deleted file mode 100644 index 9d2975e7..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/MultiCertStoreSpi.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.bouncycastle.jce.provider; - -import org.bouncycastle.jce.MultiCertStoreParameters; - -import java.security.InvalidAlgorithmParameterException; -import java.security.cert.CRLSelector; -import java.security.cert.CertSelector; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.security.cert.CertStoreParameters; -import java.security.cert.CertStoreSpi; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -public class MultiCertStoreSpi - extends CertStoreSpi -{ - private MultiCertStoreParameters params; - - public MultiCertStoreSpi(CertStoreParameters params) - throws InvalidAlgorithmParameterException - { - super(params); - - if (!(params instanceof MultiCertStoreParameters)) - { - throw new InvalidAlgorithmParameterException("org.bouncycastle.jce.provider.MultiCertStoreSpi: parameter must be a MultiCertStoreParameters object\n" + params.toString()); - } - - this.params = (MultiCertStoreParameters)params; - } - - public Collection engineGetCertificates(CertSelector certSelector) - throws CertStoreException - { - boolean searchAllStores = params.getSearchAllStores(); - Iterator iter = params.getCertStores().iterator(); - List allCerts = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST; - - while (iter.hasNext()) - { - CertStore store = (CertStore)iter.next(); - Collection certs = store.getCertificates(certSelector); - - if (searchAllStores) - { - allCerts.addAll(certs); - } - else if (!certs.isEmpty()) - { - return certs; - } - } - - return allCerts; - } - - public Collection engineGetCRLs(CRLSelector crlSelector) - throws CertStoreException - { - boolean searchAllStores = params.getSearchAllStores(); - Iterator iter = params.getCertStores().iterator(); - List allCRLs = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST; - - while (iter.hasNext()) - { - CertStore store = (CertStore)iter.next(); - Collection crls = store.getCRLs(crlSelector); - - if (searchAllStores) - { - allCRLs.addAll(crls); - } - else if (!crls.isEmpty()) - { - return crls; - } - } - - return allCRLs; - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/PKIXCertPathBuilderSpi.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/PKIXCertPathBuilderSpi.java deleted file mode 100644 index e3828d8e..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/PKIXCertPathBuilderSpi.java +++ /dev/null @@ -1,365 +0,0 @@ -package org.bouncycastle.jce.provider; - -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.PublicKey; -import java.security.cert.*; -import org.bouncycastle.jce.*; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -/** - * Implements the PKIX CertPathBuilding algorithem for BouncyCastle. - * <br /> - * <b>MAYBE: implement more CertPath validation whil build path to omit invalid pathes</b> - * - * @see CertPathBuilderSpi - **/ -public class PKIXCertPathBuilderSpi - extends CertPathBuilderSpi -{ - /** - * Build and validate a CertPath using the given parameter. - * - * @param params PKIXBuilderParameters object containing all - * information to build the CertPath - **/ - public CertPathBuilderResult engineBuild( - CertPathParameters params) - throws CertPathBuilderException, InvalidAlgorithmParameterException - { - if (!(params instanceof PKIXBuilderParameters)) - { - throw new InvalidAlgorithmParameterException("params must be a PKIXBuilderParameters instance"); - } - - PKIXBuilderParameters pkixParams = (PKIXBuilderParameters)params; - - Collection targets; - Iterator targetIter; - List certPathList = new ArrayList(); - X509Certificate cert; - Collection certs; - CertPath certPath = null; - Exception certPathException = null; - - // search target certificates - CertSelector certSelect = pkixParams.getTargetCertConstraints(); - if (certSelect == null) - { - throw new CertPathBuilderException("targetCertConstraints must be non-null for CertPath building"); - } - - try - { - targets = findCertificates(certSelect, pkixParams.getCertStores()); - } - catch (CertStoreException e) - { - throw new CertPathBuilderException(e); - } - - if (targets.isEmpty()) - { - throw new CertPathBuilderException("no certificate found matching targetCertContraints"); - } - - CertificateFactory cFact; - CertPathValidator validator; - - try - { - cFact = CertificateFactory.getInstance("X.509", "BC"); - validator = CertPathValidator.getInstance("PKIX", "BC"); - } - catch (Exception e) - { - throw new CertPathBuilderException("exception creating support classes: " + e); - } - - // - // check all potential target certificates - targetIter = targets.iterator(); - while (targetIter.hasNext()) - { - cert = (X509Certificate)targetIter.next(); - certPathList.clear(); - while (cert != null) - { - // add cert to the certpath - certPathList.add(cert); - - // check wether the issuer of <cert> is a TrustAnchor - if (findTrustAnchor(cert, pkixParams.getTrustAnchors()) != null) - { - try - { - certPath = cFact.generateCertPath(certPathList); - - PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult)validator.validate(certPath, pkixParams); - - return new PKIXCertPathBuilderResult(certPath, - result.getTrustAnchor(), - result.getPolicyTree(), - result.getPublicKey()); - } - catch (CertificateException ex) - { - certPathException = ex; - } - catch (CertPathValidatorException ex) - { - certPathException = ex; - } - // if validation failed go to next certificate - cert = null; - } - else - { - // try to get the issuer certificate from one - // of the CertStores - try - { - X509Certificate issuer = findIssuer(cert, pkixParams.getCertStores()); - if (issuer.equals(cert)) - { - cert = null; - } - else - { - cert = issuer; - } - } - catch (CertPathValidatorException ex) - { - certPathException = ex; - cert = null; - } - } - } - } - - if (certPath != null) - { - throw new CertPathBuilderException("found certificate chain, but could not be validated", certPathException); - } - - throw new CertPathBuilderException("unable to find certificate chain"); - } - - /** - * Search the given Set of TrustAnchor's for one that is the - * issuer of the fiven X509 certificate. - * - * @param cert the X509 certificate - * @param trustAnchors a Set of TrustAnchor's - * - * @return the <code>TrustAnchor</code> object if found or - * <code>null</code> if not. - * - * @exception CertPathValidatorException if a TrustAnchor was - * found but the signature verificytion on the given certificate - * has thrown an exception. This Exception can be obtainted with - * <code>getCause()</code> method. - **/ - final TrustAnchor findTrustAnchor( - X509Certificate cert, - Set trustAnchors) - throws CertPathBuilderException - { - Iterator iter = trustAnchors.iterator(); - TrustAnchor trust = null; - PublicKey trustPublicKey = null; - Exception invalidKeyEx = null; - - X509CertSelector certSelectX509 = new X509CertSelector(); - - try - { - certSelectX509.setSubject(PrincipalUtil.getIssuerX509Principal(cert).getEncoded()); - } - catch (CertificateEncodingException ex) - { - throw new CertPathBuilderException("can't get trust anchor principal",null); - } - catch (IOException ex) - { - throw new CertPathBuilderException("can't get trust anchor principal",null); - } - - while (iter.hasNext() && trust == null) - { - trust = (TrustAnchor)iter.next(); - if (trust.getTrustedCert() != null) - { - if (certSelectX509.match(trust.getTrustedCert())) - { - trustPublicKey = trust.getTrustedCert().getPublicKey(); - } - else - { - trust = null; - } - } - else if (trust.getCAName() != null - && trust.getCAPublicKey() != null) - { - try - { - X509Principal certIssuer = PrincipalUtil.getIssuerX509Principal(cert); - X509Principal caName = new X509Principal(trust.getCAName()); - if (certIssuer.equals(caName)) - { - trustPublicKey = trust.getCAPublicKey(); - } - else - { - trust = null; - } - } - catch (CertificateEncodingException ex) - { - trust = null; - } - catch (IllegalArgumentException ex) - { - trust = null; - } - } - else - { - trust = null; - } - - if (trustPublicKey != null) - { - try - { - cert.verify(trustPublicKey); - } - catch (Exception ex) - { - invalidKeyEx = ex; - trust = null; - } - } - } - - if (trust == null && invalidKeyEx != null) - { - throw new CertPathBuilderException("TrustAnchor found put certificate validation failed",invalidKeyEx); - } - - return trust; - } - - /** - * Return a Collection of all certificates found in the - * CertStore's that are matching the certSelect criteriums. - * - * @param certSelector a {@link CertSelector CertSelector} - * object that will be used to select the certificates - * @param certStores a List containing only {@link CertStore - * CertStore} objects. These are used to search for - * certificates - * - * @return a Collection of all found {@link Certificate Certificate} - * objects. May be empty but never <code>null</code>. - **/ - private Collection findCertificates( - CertSelector certSelect, - List certStores) - throws CertStoreException - { - Set certs = new HashSet(); - Iterator iter = certStores.iterator(); - - while (iter.hasNext()) - { - CertStore certStore = (CertStore)iter.next(); - - certs.addAll(certStore.getCertificates(certSelect)); - } - - return certs; - } - - /** - * Find the issuer certificate of the given certificate. - * - * @param cert the certificate hows issuer certificate should - * be found. - * @param certStores a list of <code>CertStore</code> object - * that will be searched - * - * @return then <code>X509Certificate</code> object containing - * the issuer certificate or <code>null</code> if not found - * - * @exception CertPathValidatorException if a TrustAnchor was - * found but the signature verificytion on the given certificate - * has thrown an exception. This Exception can be obtainted with - * <code>getCause()</code> method. - **/ - private X509Certificate findIssuer( - X509Certificate cert, - List certStores) - throws CertPathValidatorException - { - Exception invalidKeyEx = null; - X509CertSelector certSelect = new X509CertSelector(); - try - { - certSelect.setSubject(PrincipalUtil.getIssuerX509Principal(cert).getEncoded()); - } - catch (CertificateEncodingException ex) - { - throw new CertPathValidatorException("Issuer not found", null, null, -1); - } - catch (IOException ex) - { - throw new CertPathValidatorException("Issuer not found", null, null, -1); - } - - Iterator iter; - try - { - iter = findCertificates(certSelect, certStores).iterator(); - } - catch (CertStoreException e) - { - throw new CertPathValidatorException(e); - } - - X509Certificate issuer = null; - while (iter.hasNext() && issuer == null) - { - issuer = (X509Certificate)iter.next(); - try - { - cert.verify(issuer.getPublicKey()); - } - catch (Exception ex) - { - invalidKeyEx = ex; - issuer = null; - } - } - - if (issuer == null && invalidKeyEx == null) - { - throw new CertPathValidatorException("Issuer not found", null, null, -1); - } - - if (issuer == null && invalidKeyEx != null) - { - throw new CertPathValidatorException("issuer found but certificate validation failed",invalidKeyEx,null,-1); - } - - return issuer; - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/PKIXCertPathValidatorSpi.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/PKIXCertPathValidatorSpi.java deleted file mode 100644 index 7d9c612f..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/PKIXCertPathValidatorSpi.java +++ /dev/null @@ -1,2183 +0,0 @@ -package org.bouncycastle.jce.provider; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidAlgorithmParameterException; -import java.security.PublicKey; -import java.security.cert.CRLException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertPath; -import java.security.cert.CertPathParameters; -import java.security.cert.CertPathValidatorSpi; -import java.security.cert.CertPathValidatorException; -import java.security.cert.CertPathValidatorResult; -import java.security.cert.PolicyQualifierInfo; -import java.security.cert.X509Certificate; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import java.security.cert.X509CRLSelector; -import java.security.cert.X509CertSelector; -import java.security.cert.PKIXParameters; -import java.security.cert.PKIXCertPathChecker; -import java.security.cert.PKIXCertPathValidatorResult; -import java.security.cert.TrustAnchor; -import java.security.cert.PKIXParameters; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; -import java.text.SimpleDateFormat; - -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.PrincipalUtil; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.ASN1OutputStream; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1TaggedObject; -import org.bouncycastle.asn1.BERConstructedOctetString; -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Enumerated; -import org.bouncycastle.asn1.DERIA5String; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.BasicConstraints; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.GeneralSubtree; -import org.bouncycastle.asn1.x509.IssuingDistributionPoint; -import org.bouncycastle.asn1.x509.NameConstraints; -import org.bouncycastle.asn1.x509.PolicyInformation; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.asn1.x509.X509Extensions; - -/** - * CertPathValidatorSpi implemenation for X.509 Certificate validation ala rfc 3280<br /> - **/ -public class PKIXCertPathValidatorSpi extends CertPathValidatorSpi -{ - private static final String CERTIFICATE_POLICIES = X509Extensions.CertificatePolicies.getId(); - private static final String POLICY_MAPPINGS = X509Extensions.PolicyMappings.getId(); - private static final String INHIBIT_ANY_POLICY = X509Extensions.InhibitAnyPolicy.getId(); - private static final String ISSUING_DISTRIBUTION_POINT = X509Extensions.IssuingDistributionPoint.getId(); - private static final String DELTA_CRL_INDICATOR = X509Extensions.DeltaCRLIndicator.getId(); - private static final String POLICY_CONSTRAINTS = X509Extensions.PolicyConstraints.getId(); - private static final String BASIC_CONSTRAINTS = X509Extensions.BasicConstraints.getId(); - private static final String SUBJECT_ALTERNATIVE_NAME = X509Extensions.SubjectAlternativeName.getId(); - private static final String NAME_CONSTRAINTS = X509Extensions.NameConstraints.getId(); - private static final String KEY_USAGE = X509Extensions.KeyUsage.getId(); - - private static final String CRL_NUMBER = X509Extensions.CRLNumber.getId(); - - private static final String ANY_POLICY = "2.5.29.32.0"; - - - /* - * key usage bits - */ - private static final int KEY_CERT_SIGN = 5; - private static final int CRL_SIGN = 6; - - private static final String[] crlReasons = new String[] { - "unspecified", - "keyCompromise", - "cACompromise", - "affiliationChanged", - "superseded", - "cessationOfOperation", - "certificateHold", - "unknown", - "removeFromCRL", - "privilegeWithdrawn", - "aACompromise" }; - - /** - * extract the value of the given extension, if it exists. - */ - private ASN1Primitive getExtensionValue( - java.security.cert.X509Extension ext, - String oid) - throws AnnotatedException - { - byte[] bytes = ext.getExtensionValue(oid); - if (bytes == null) - { - return null; - } - - return getObject(oid, bytes); - } - - private ASN1Primitive getObject( - String oid, - byte[] ext) - throws AnnotatedException - { - try - { - ASN1InputStream aIn = new ASN1InputStream(ext); - ASN1OctetString octs = (ASN1OctetString)aIn.readObject(); - - aIn = new ASN1InputStream(octs.getOctets()); - return aIn.readObject(); - } - catch (IOException e) - { - throw new AnnotatedException("exception processing extension " + oid, e); - } - } - - private boolean withinDNSubtree( - ASN1Sequence dns, - ASN1Sequence subtree) - { - if (subtree.size() < 1) - { - return false; - } - - if (subtree.size() > dns.size()) - { - return false; - } - - for (int j = subtree.size() - 1; j >= 0; j--) - { - if (!subtree.getObjectAt(j).equals(dns.getObjectAt(j))) - { - return false; - } - } - - return true; - } - - private void checkPermittedDN( - Set permitted, - ASN1Sequence dns) - throws CertPathValidatorException - { - if (permitted.isEmpty()) - { - return; - } - - Iterator it = permitted.iterator(); - - while (it.hasNext()) - { - ASN1Sequence subtree = (ASN1Sequence)it.next(); - - if (withinDNSubtree(dns, subtree)) - { - return; - } - } - - throw new CertPathValidatorException("Subject distinguished name is not from a permitted subtree"); - } - - private void checkExcludedDN( - Set excluded, - ASN1Sequence dns) - throws CertPathValidatorException - { - if (excluded.isEmpty()) - { - return; - } - - Iterator it = excluded.iterator(); - - while (it.hasNext()) - { - ASN1Sequence subtree = (ASN1Sequence)it.next(); - - if (withinDNSubtree(dns, subtree)) - { - throw new CertPathValidatorException("Subject distinguished name is from an excluded subtree"); - } - } - } - - private Set intersectDN( - Set permitted, - ASN1Sequence dn) - { - if (permitted.isEmpty()) - { - permitted.add(dn); - - return permitted; - } - else - { - Set intersect = new HashSet(); - - Iterator _iter = permitted.iterator(); - while (_iter.hasNext()) - { - ASN1Sequence subtree = (ASN1Sequence)_iter.next(); - - if (withinDNSubtree(dn, subtree)) - { - intersect.add(dn); - } - else if (withinDNSubtree(subtree, dn)) - { - intersect.add(subtree); - } - } - - return intersect; - } - } - - private Set unionDN( - Set excluded, - ASN1Sequence dn) - { - if (excluded.isEmpty()) - { - excluded.add(dn); - - return excluded; - } - else - { - Set intersect = new HashSet(); - - Iterator _iter = excluded.iterator(); - while (_iter.hasNext()) - { - ASN1Sequence subtree = (ASN1Sequence)_iter.next(); - - if (withinDNSubtree(dn, subtree)) - { - intersect.add(subtree); - } - else if (withinDNSubtree(subtree, dn)) - { - intersect.add(dn); - } - else - { - intersect.add(subtree); - intersect.add(dn); - } - } - - return intersect; - } - } - - private Set intersectEmail( - Set permitted, - String email) - { - String _sub = email.substring(email.indexOf('@') + 1); - - if (permitted.isEmpty()) - { - permitted.add(_sub); - - return permitted; - } - else - { - Set intersect = new HashSet(); - - Iterator _iter = permitted.iterator(); - while (_iter.hasNext()) - { - String _permitted = (String)_iter.next(); - - if (_sub.endsWith(_permitted)) - { - intersect.add(_sub); - } - else if (_permitted.endsWith(_sub)) - { - intersect.add(_permitted); - } - } - - return intersect; - } - } - - private Set unionEmail( - Set excluded, - String email) - { - String _sub = email.substring(email.indexOf('@') + 1); - - if (excluded.isEmpty()) - { - excluded.add(_sub); - return excluded; - } - else - { - Set intersect = new HashSet(); - - Iterator _iter = excluded.iterator(); - while (_iter.hasNext()) - { - String _excluded = (String)_iter.next(); - - if (_sub.endsWith(_excluded)) - { - intersect.add(_excluded); - } - else if (_excluded.endsWith(_sub)) - { - intersect.add(_sub); - } - else - { - intersect.add(_excluded); - intersect.add(_sub); - } - } - - return intersect; - } - } - - private Set intersectIP( - Set permitted, - byte[] ip) - { - // TBD - return permitted; - } - - private Set unionIP( - Set excluded, - byte[] ip) - { - // TBD - return excluded; - } - - private void checkPermittedEmail( - Set permitted, - String email) - throws CertPathValidatorException - { - if (permitted.isEmpty()) - { - return; - } - - String sub = email.substring(email.indexOf('@') + 1); - Iterator it = permitted.iterator(); - - while (it.hasNext()) - { - String str = (String)it.next(); - - if (sub.endsWith(str)) - { - return; - } - } - - throw new CertPathValidatorException("Subject email address is not from a permitted subtree"); - } - - private void checkExcludedEmail( - Set excluded, - String email) - throws CertPathValidatorException - { - if (excluded.isEmpty()) - { - return; - } - - String sub = email.substring(email.indexOf('@') + 1); - Iterator it = excluded.iterator(); - - while (it.hasNext()) - { - String str = (String)it.next(); - if (sub.endsWith(str)) - { - throw new CertPathValidatorException("Subject email address is from an excluded subtree"); - } - } - } - - private void checkPermittedIP( - Set permitted, - byte[] ip) - throws CertPathValidatorException - { - if (permitted.isEmpty()) - { - return; - } - - // TODO: ??? Something here - } - - private void checkExcludedIP( - Set excluded, - byte[] ip) - throws CertPathValidatorException - { - if (excluded.isEmpty()) - { - return; - } - - // TODO, check RFC791 and RFC1883 for IP bytes definition. - } - - private PKIXPolicyNode removePolicyNode( - PKIXPolicyNode validPolicyTree, - List [] policyNodes, - PKIXPolicyNode _node) - { - PKIXPolicyNode _parent = (PKIXPolicyNode)_node.getParent(); - - if (validPolicyTree == null) - { - return null; - } - - if (_parent == null) - { - for (int j = 0; j < policyNodes.length; j++) - { - policyNodes[j] = new ArrayList(); - } - - return null; - } - else - { - _parent.removeChild(_node); - removePolicyNodeRecurse(policyNodes, _node); - - return validPolicyTree; - } - } - - private void removePolicyNodeRecurse( - List [] policyNodes, - PKIXPolicyNode _node) - { - policyNodes[_node.getDepth()].remove(_node); - - if (_node.hasChildren()) - { - Iterator _iter = _node.getChildren(); - while (_iter.hasNext()) - { - PKIXPolicyNode _child = (PKIXPolicyNode)_iter.next(); - removePolicyNodeRecurse(policyNodes, _child); - } - } - } - - private boolean isSelfIssued( - X509Certificate cert) - { - return cert.getSubjectDN().equals(cert.getIssuerDN()); - } - - private boolean isAnyPolicy( - Set policySet) - { - return policySet == null || policySet.contains(ANY_POLICY) || policySet.isEmpty(); - } - - private AlgorithmIdentifier getAlgorithmIdentifier( - PublicKey key) - throws CertPathValidatorException - { - try - { - ASN1InputStream aIn = new ASN1InputStream( - new ByteArrayInputStream(key.getEncoded())); - - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); - - return info.getAlgorithmId(); - } - catch (IOException e) - { - throw new CertPathValidatorException("exception processing public key"); - } - } - - private Set getQualifierSet(ASN1Sequence qualifiers) - throws CertPathValidatorException - { - Set pq = new HashSet(); - - if (qualifiers == null) - { - return pq; - } - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - Enumeration e = qualifiers.getObjects(); - - while (e.hasMoreElements()) - { - try - { - aOut.writeObject((ASN1Encodable)e.nextElement()); - - pq.add(new PolicyQualifierInfo(bOut.toByteArray())); - } - catch (IOException ex) - { - throw new CertPathValidatorException("exception building qualifier set: " + ex); - } - - bOut.reset(); - } - - return pq; - } - - private boolean processCertD1i( - int index, - List [] policyNodes, - ASN1ObjectIdentifier pOid, - Set pq) - { - List policyNodeVec = policyNodes[index - 1]; - - for (int j = 0; j < policyNodeVec.size(); j++) - { - PKIXPolicyNode node = (PKIXPolicyNode)policyNodeVec.get(j); - Set expectedPolicies = node.getExpectedPolicies(); - - if (expectedPolicies.contains(pOid.getId())) - { - Set childExpectedPolicies = new HashSet(); - childExpectedPolicies.add(pOid.getId()); - - PKIXPolicyNode child = new PKIXPolicyNode(new ArrayList(), - index, - childExpectedPolicies, - node, - pq, - pOid.getId(), - false); - node.addChild(child); - policyNodes[index].add(child); - - return true; - } - } - - return false; - } - - private void processCertD1ii( - int index, - List [] policyNodes, - ASN1ObjectIdentifier _poid, - Set _pq) - { - List policyNodeVec = policyNodes[index - 1]; - - for (int j = 0; j < policyNodeVec.size(); j++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)policyNodeVec.get(j); - Set _expectedPolicies = _node.getExpectedPolicies(); - - if (ANY_POLICY.equals(_node.getValidPolicy())) - { - Set _childExpectedPolicies = new HashSet(); - _childExpectedPolicies.add(_poid.getId()); - - PKIXPolicyNode _child = new PKIXPolicyNode(new ArrayList(), - index, - _childExpectedPolicies, - _node, - _pq, - _poid.getId(), - false); - _node.addChild(_child); - policyNodes[index].add(_child); - return; - } - } - } - - public CertPathValidatorResult engineValidate( - CertPath certPath, - CertPathParameters params) - throws CertPathValidatorException, InvalidAlgorithmParameterException - { - if (!(params instanceof PKIXParameters)) - { - throw new InvalidAlgorithmParameterException("params must be a PKIXParameters instance"); - } - - PKIXParameters paramsPKIX = (PKIXParameters)params; - if (paramsPKIX.getTrustAnchors() == null) - { - throw new InvalidAlgorithmParameterException("trustAnchors is null, this is not allowed for path validation"); - } - - // - // 6.1.1 - inputs - // - - // - // (a) - // - List certs = certPath.getCertificates(); - int n = certs.size(); - - if (certs.isEmpty()) - { - throw new CertPathValidatorException("CertPath is empty", null, certPath, 0); - } - - // - // (b) - // - Date validDate = getValidDate(paramsPKIX); - - // - // (c) - // - Set userInitialPolicySet = paramsPKIX.getInitialPolicies(); - - // - // (d) - // - TrustAnchor trust = findTrustAnchor((X509Certificate)certs.get(certs.size() - 1), certPath, certs.size() - 1, paramsPKIX.getTrustAnchors()); - - if (trust == null) - { - throw new CertPathValidatorException("TrustAnchor for CertPath not found.", null, certPath, -1); - } - - // - // (e), (f), (g) are part of the paramsPKIX object. - // - - Iterator certIter; - int index = 0; - int i; - //Certificate for each interation of the validation loop - //Signature information for each iteration of the validation loop - Set subTreeContraints = new HashSet(); - Set subTreeExcludes = new HashSet(); - - // - // 6.1.2 - setup - // - - // - // (a) - // - List [] policyNodes = new ArrayList[n + 1]; - for (int j = 0; j < policyNodes.length; j++) - { - policyNodes[j] = new ArrayList(); - } - - Set policySet = new HashSet(); - - policySet.add(ANY_POLICY); - - PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(), ANY_POLICY, false); - - policyNodes[0].add(validPolicyTree); - - // - // (b) - // - Set permittedSubtreesDN = new HashSet(); - Set permittedSubtreesEmail = new HashSet(); - Set permittedSubtreesIP = new HashSet(); - - // - // (c) - // - Set excludedSubtreesDN = new HashSet(); - Set excludedSubtreesEmail = new HashSet(); - Set excludedSubtreesIP = new HashSet(); - - // - // (d) - // - int explicitPolicy; - Set acceptablePolicies = null; - - if (paramsPKIX.isExplicitPolicyRequired()) - { - explicitPolicy = 0; - } - else - { - explicitPolicy = n + 1; - } - - // - // (e) - // - int inhibitAnyPolicy; - - if (paramsPKIX.isAnyPolicyInhibited()) - { - inhibitAnyPolicy = 0; - } - else - { - inhibitAnyPolicy = n + 1; - } - - // - // (f) - // - int policyMapping; - - if (paramsPKIX.isPolicyMappingInhibited()) - { - policyMapping = 0; - } - else - { - policyMapping = n + 1; - } - - // - // (g), (h), (i), (j) - // - PublicKey workingPublicKey; - X509Principal workingIssuerName; - - X509Certificate sign = trust.getTrustedCert(); - try - { - if (sign != null) - { - workingIssuerName = getSubjectPrincipal(sign); - workingPublicKey = sign.getPublicKey(); - } - else - { - workingIssuerName = new X509Principal(trust.getCAName()); - workingPublicKey = trust.getCAPublicKey(); - } - } - catch (IllegalArgumentException ex) - { - throw new CertPathValidatorException("TrustAnchor subjectDN: " + ex.toString()); - } - catch (AnnotatedException ex) - { - throw new CertPathValidatorException(ex.getMessage(), ex.getUnderlyingException(), certPath, index); - } - - AlgorithmIdentifier workingAlgId = getAlgorithmIdentifier(workingPublicKey); - ASN1ObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getObjectId(); - ASN1Encodable workingPublicKeyParameters = workingAlgId.getParameters(); - - // - // (k) - // - int maxPathLength = n; - - // - // 6.1.3 - // - Iterator tmpIter; - int tmpInt; - - if (paramsPKIX.getTargetCertConstraints() != null - && !paramsPKIX.getTargetCertConstraints().match((X509Certificate)certs.get(0))) - { - throw new CertPathValidatorException("target certificate in certpath does not match targetcertconstraints", null, certPath, 0); - } - - - // - // initialise CertPathChecker's - // - List pathCheckers = paramsPKIX.getCertPathCheckers(); - certIter = pathCheckers.iterator(); - while (certIter.hasNext()) - { - ((PKIXCertPathChecker)certIter.next()).init(false); - } - - X509Certificate cert = null; - - for (index = certs.size() - 1; index >= 0 ; index--) - { - try - { - // - // i as defined in the algorithm description - // - i = n - index; - - // - // set certificate to be checked in this round - // sign and workingPublicKey and workingIssuerName are set - // at the end of the for loop and initialied the - // first time from the TrustAnchor - // - cert = (X509Certificate)certs.get(index); - - // - // 6.1.3 - // - - // - // (a) verify - // - try - { - // (a) (1) - // - cert.verify(workingPublicKey, "BC"); - } - catch (Exception e) - { - throw new CertPathValidatorException("Could not validate certificate signature.", e, certPath, index); - } - - try - { - // (a) (2) - // - cert.checkValidity(validDate); - } - catch (CertificateExpiredException e) - { - throw new CertPathValidatorException("Could not validate certificate: " + e.getMessage(), e, certPath, index); - } - catch (CertificateNotYetValidException e) - { - throw new CertPathValidatorException("Could not validate certificate: " + e.getMessage(), e, certPath, index); - } - - // - // (a) (3) - // - if (paramsPKIX.isRevocationEnabled()) - { - checkCRLs(paramsPKIX, cert, validDate, sign, workingPublicKey); - } - - // - // (a) (4) name chaining - // - if (!getEncodedIssuerPrincipal(cert).equals(workingIssuerName)) - { - throw new CertPathValidatorException( - "IssuerName(" + getEncodedIssuerPrincipal(cert) + - ") does not match SubjectName(" + workingIssuerName + - ") of signing certificate", null, certPath, index); - } - - // - // (b), (c) permitted and excluded subtree checking. - // - if (!(isSelfIssued(cert) && (i < n))) - { - X509Principal principal = getSubjectPrincipal(cert); - ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(principal.getEncoded())); - ASN1Sequence dns; - - try - { - dns = (ASN1Sequence)aIn.readObject(); - } - catch (IOException e) - { - throw new CertPathValidatorException("exception extracting subject name when checking subtrees"); - } - - checkPermittedDN(permittedSubtreesDN, dns); - - checkExcludedDN(excludedSubtreesDN, dns); - - ASN1Sequence altName = (ASN1Sequence)getExtensionValue(cert, SUBJECT_ALTERNATIVE_NAME); - if (altName != null) - { - for (int j = 0; j < altName.size(); j++) - { - ASN1TaggedObject o = (ASN1TaggedObject)altName.getObjectAt(j); - - switch(o.getTagNo()) - { - case 1: - String email = DERIA5String.getInstance(o, true).getString(); - - checkPermittedEmail(permittedSubtreesEmail, email); - checkExcludedEmail(excludedSubtreesEmail, email); - break; - case 4: - ASN1Sequence altDN = ASN1Sequence.getInstance(o, true); - - checkPermittedDN(permittedSubtreesDN, altDN); - checkExcludedDN(excludedSubtreesDN, altDN); - break; - case 7: - byte[] ip = ASN1OctetString.getInstance(o, true).getOctets(); - - checkPermittedIP(permittedSubtreesIP, ip); - checkExcludedIP(excludedSubtreesIP, ip); - } - } - } - } - - // - // (d) policy Information checking against initial policy and - // policy mapping - // - ASN1Sequence certPolicies = (ASN1Sequence)getExtensionValue(cert, CERTIFICATE_POLICIES); - if (certPolicies != null && validPolicyTree != null) - { - // - // (d) (1) - // - Enumeration e = certPolicies.getObjects(); - Set pols = new HashSet(); - - while (e.hasMoreElements()) - { - PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement()); - ASN1ObjectIdentifier pOid = pInfo.getPolicyIdentifier(); - - pols.add(pOid.getId()); - - if (!ANY_POLICY.equals(pOid.getId())) - { - Set pq = getQualifierSet(pInfo.getPolicyQualifiers()); - - boolean match = processCertD1i(i, policyNodes, pOid, pq); - - if (!match) - { - processCertD1ii(i, policyNodes, pOid, pq); - } - } - } - - if (acceptablePolicies == null || acceptablePolicies.contains(ANY_POLICY)) - { - acceptablePolicies = pols; - } - else - { - Iterator it = acceptablePolicies.iterator(); - Set t1 = new HashSet(); - - while (it.hasNext()) - { - Object o = it.next(); - - if (pols.contains(o)) - { - t1.add(o); - } - } - - acceptablePolicies = t1; - } - - // - // (d) (2) - // - if ((inhibitAnyPolicy > 0) || ((i < n) && isSelfIssued(cert))) - { - e = certPolicies.getObjects(); - - while (e.hasMoreElements()) - { - PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement()); - - if (ANY_POLICY.equals(pInfo.getPolicyIdentifier().getId())) - { - Set _apq = getQualifierSet(pInfo.getPolicyQualifiers()); - List _nodes = policyNodes[i - 1]; - - for (int k = 0; k < _nodes.size(); k++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_nodes.get(k); - - Iterator _policySetIter = _node.getExpectedPolicies().iterator(); - while (_policySetIter.hasNext()) - { - Object _tmp = _policySetIter.next(); - - String _policy; - if (_tmp instanceof String) - { - _policy = (String)_tmp; - } - else if (_tmp instanceof ASN1ObjectIdentifier) - { - _policy = ((ASN1ObjectIdentifier)_tmp).getId(); - } - else - { - continue; - } - - boolean _found = false; - Iterator _childrenIter = _node.getChildren(); - - while (_childrenIter.hasNext()) - { - PKIXPolicyNode _child = (PKIXPolicyNode)_childrenIter.next(); - - if (_policy.equals(_child.getValidPolicy())) - { - _found = true; - } - } - - if (!_found) - { - Set _newChildExpectedPolicies = new HashSet(); - _newChildExpectedPolicies.add(_policy); - - PKIXPolicyNode _newChild = new PKIXPolicyNode(new ArrayList(), - i, - _newChildExpectedPolicies, - _node, - _apq, - _policy, - false); - _node.addChild(_newChild); - policyNodes[i].add(_newChild); - } - } - } - break; - } - } - } - - // - // (d) (3) - // - for (int j = (i - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node); - if (validPolicyTree == null) - { - break; - } - } - } - } - - // - // d (4) - // - Set criticalExtensionOids = cert.getCriticalExtensionOIDs(); - - if (criticalExtensionOids != null) - { - boolean critical = criticalExtensionOids.contains(CERTIFICATE_POLICIES); - - List nodes = policyNodes[i]; - for (int j = 0; j < nodes.size(); j++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(j); - node.setCritical(critical); - } - } - } - - // - // (e) - // - if (certPolicies == null) - { - validPolicyTree = null; - } - - // - // (f) - // - if (explicitPolicy <= 0 && validPolicyTree == null) - { - throw new CertPathValidatorException("No valid policy tree found when one expected."); - } - - // - // 6.1.4 - // - - if (i != n) - { - if (cert != null && cert.getVersion() == 1) - { - throw new CertPathValidatorException( - "Version 1 certs can't be used as CA ones"); - } - - // - // - // (a) check the policy mappings - // - ASN1Primitive pm = getExtensionValue(cert, POLICY_MAPPINGS); - if (pm != null) - { - ASN1Sequence mappings = (ASN1Sequence)pm; - - for (int j = 0; j < mappings.size(); j++) - { - ASN1Sequence mapping = (ASN1Sequence)mappings.getObjectAt(j); - - ASN1ObjectIdentifier issuerDomainPolicy = (ASN1ObjectIdentifier)mapping.getObjectAt(0); - ASN1ObjectIdentifier subjectDomainPolicy = (ASN1ObjectIdentifier)mapping.getObjectAt(1); - - if (ANY_POLICY.equals(issuerDomainPolicy.getId())) - { - - throw new CertPathValidatorException("IssuerDomainPolicy is anyPolicy"); - } - - if (ANY_POLICY.equals(subjectDomainPolicy.getId())) - { - - throw new CertPathValidatorException("SubjectDomainPolicy is anyPolicy"); - } - } - } - - // (b) - // - if (pm != null) - { - ASN1Sequence mappings = (ASN1Sequence)pm; - Map m_idp = new HashMap(); - Set s_idp = new HashSet(); - - for (int j = 0; j < mappings.size(); j++) - { - ASN1Sequence mapping = (ASN1Sequence)mappings.getObjectAt(j); - String id_p = ((ASN1ObjectIdentifier)mapping.getObjectAt(0)).getId(); - String sd_p = ((ASN1ObjectIdentifier)mapping.getObjectAt(1)).getId(); - Set tmp; - - if (!m_idp.containsKey(id_p)) - { - tmp = new HashSet(); - tmp.add(sd_p); - m_idp.put(id_p, tmp); - s_idp.add(id_p); - } - else - { - tmp = (Set)m_idp.get(id_p); - tmp.add(sd_p); - } - } - - Iterator it_idp = s_idp.iterator(); - while (it_idp.hasNext()) - { - String id_p = (String)it_idp.next(); - - // - // (1) - // - if (policyMapping > 0) - { - boolean idp_found = false; - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - idp_found = true; - node.expectedPolicies = (Set)m_idp.get(id_p); - break; - } - } - - if (!idp_found) - { - nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (ANY_POLICY.equals(node.getValidPolicy())) - { - Set pq = null; - ASN1Sequence policies = (ASN1Sequence)getExtensionValue( - cert, CERTIFICATE_POLICIES); - Enumeration e = policies.getObjects(); - while (e.hasMoreElements()) - { - PolicyInformation pinfo = PolicyInformation.getInstance(e.nextElement()); - if (ANY_POLICY.equals(pinfo.getPolicyIdentifier().getId())) - { - pq = getQualifierSet(pinfo.getPolicyQualifiers()); - break; - } - } - boolean ci = false; - if (cert.getCriticalExtensionOIDs() != null) - { - ci = cert.getCriticalExtensionOIDs().contains(CERTIFICATE_POLICIES); - } - - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - if (ANY_POLICY.equals(p_node.getValidPolicy())) - { - PKIXPolicyNode c_node = new PKIXPolicyNode( - new ArrayList(), i, - (Set)m_idp.get(id_p), - p_node, pq, id_p, ci); - p_node.addChild(c_node); - policyNodes[i].add(c_node); - } - break; - } - } - } - - // - // (2) - // - } - else if (policyMapping <= 0) - { - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - p_node.removeChild(node); - nodes_i.remove(); - for (int k = (i - 1); k >= 0; k--) - { - List nodes = policyNodes[k]; - for (int l = 0; l < nodes.size(); l++) - { - PKIXPolicyNode node2 = (PKIXPolicyNode)nodes.get(l); - if (!node2.hasChildren()) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node2); - if (validPolicyTree == null) - { - break; - } - } - } - } - } - } - } - } - } - - // - // (g) handle the name constraints extension - // - ASN1Sequence ncSeq = (ASN1Sequence)getExtensionValue(cert, NAME_CONSTRAINTS); - if (ncSeq != null) - { - NameConstraints nc = NameConstraints.getInstance(ncSeq); - - // - // (g) (1) permitted subtrees - // - GeneralSubtree[] permitted = nc.getPermittedSubtrees(); - if (permitted != null) - { - for (int indx = 0; indx != permitted.length; indx++) - { - GeneralSubtree subtree = permitted[indx]; - GeneralName base = subtree.getBase(); - - switch(base.getTagNo()) - { - case 1: - permittedSubtreesEmail = intersectEmail(permittedSubtreesEmail, DERIA5String.getInstance(base.getName()).getString()); - break; - case 4: - permittedSubtreesDN = intersectDN(permittedSubtreesDN, (ASN1Sequence)base.getName()); - break; - case 7: - permittedSubtreesIP = intersectIP(permittedSubtreesIP, BERConstructedOctetString.fromSequence((ASN1Sequence)base.getName()).getOctets()); - break; - } - } - } - - // - // (g) (2) excluded subtrees - // - GeneralSubtree[] excluded = nc.getExcludedSubtrees(); - if (excluded != null) - { - for (int indx = 0; indx != excluded.length; indx++) - { - GeneralSubtree subtree = excluded[indx]; - GeneralName base = subtree.getBase(); - - switch(base.getTagNo()) - { - case 1: - excludedSubtreesEmail = unionEmail(excludedSubtreesEmail, DERIA5String.getInstance(base.getName()).getString()); - break; - case 4: - excludedSubtreesDN = unionDN(excludedSubtreesDN, (ASN1Sequence)base.getName()); - break; - case 7: - excludedSubtreesIP = unionIP(excludedSubtreesIP, BERConstructedOctetString.fromSequence((ASN1Sequence)base.getName()).getOctets()); - break; - } - } - } - } - - // - // (h) - // - if (!isSelfIssued(cert)) - { - // - // (1) - // - if (explicitPolicy != 0) - { - explicitPolicy--; - } - - // - // (2) - // - if (policyMapping != 0) - { - policyMapping--; - } - - // - // (3) - // - if (inhibitAnyPolicy != 0) - { - inhibitAnyPolicy--; - } - } - - // - // (i) - // - ASN1Sequence pc = (ASN1Sequence)getExtensionValue(cert, POLICY_CONSTRAINTS); - - if (pc != null) - { - Enumeration policyConstraints = pc.getObjects(); - - while (policyConstraints.hasMoreElements()) - { - ASN1TaggedObject constraint = (ASN1TaggedObject)policyConstraints.nextElement(); - switch (constraint.getTagNo()) - { - case 0: - tmpInt = ASN1Integer.getInstance(constraint).getValue().intValue(); - if (tmpInt < explicitPolicy) - { - explicitPolicy = tmpInt; - } - break; - case 1: - tmpInt = ASN1Integer.getInstance(constraint).getValue().intValue(); - if (tmpInt < policyMapping) - { - policyMapping = tmpInt; - } - break; - } - } - } - - // - // (j) - // - ASN1Integer iap = (ASN1Integer)getExtensionValue(cert, INHIBIT_ANY_POLICY); - - if (iap != null) - { - int _inhibitAnyPolicy = iap.getValue().intValue(); - - if (_inhibitAnyPolicy < inhibitAnyPolicy) - { - inhibitAnyPolicy = _inhibitAnyPolicy; - } - } - - // - // (k) - // - BasicConstraints bc = BasicConstraints.getInstance( - getExtensionValue(cert, BASIC_CONSTRAINTS)); - if (bc != null) - { - if (!(bc.isCA())) - { - throw new CertPathValidatorException("Not a CA certificate"); - } - } - else - { - throw new CertPathValidatorException("Intermediate certificate lacks BasicConstraints"); - } - - // - // (l) - // - if (!isSelfIssued(cert)) - { - if (maxPathLength <= 0) - { - throw new CertPathValidatorException("Max path length not greater than zero"); - } - - maxPathLength--; - } - - // - // (m) - // - if (bc != null) - { - BigInteger _pathLengthConstraint = bc.getPathLenConstraint(); - - if (_pathLengthConstraint != null) - { - int _plc = _pathLengthConstraint.intValue(); - - if (_plc < maxPathLength) - { - maxPathLength = _plc; - } - } - } - - // - // (n) - // - boolean[] _usage = cert.getKeyUsage(); - - if ((_usage != null) && !_usage[5]) - { - throw new CertPathValidatorException( - "Issuer certificate keyusage extension is critical an does not permit key signing.\n", - null, certPath, index); - } - - // - // (o) - // - Set criticalExtensions = new HashSet(cert.getCriticalExtensionOIDs()); - // these extensions are handle by the algorithem - criticalExtensions.remove(KEY_USAGE); - criticalExtensions.remove(CERTIFICATE_POLICIES); - criticalExtensions.remove(POLICY_MAPPINGS); - criticalExtensions.remove(INHIBIT_ANY_POLICY); - criticalExtensions.remove(ISSUING_DISTRIBUTION_POINT); - criticalExtensions.remove(DELTA_CRL_INDICATOR); - criticalExtensions.remove(POLICY_CONSTRAINTS); - criticalExtensions.remove(BASIC_CONSTRAINTS); - criticalExtensions.remove(SUBJECT_ALTERNATIVE_NAME); - criticalExtensions.remove(NAME_CONSTRAINTS); - - tmpIter = pathCheckers.iterator(); - while (tmpIter.hasNext()) - { - try - { - ((PKIXCertPathChecker)tmpIter.next()).check(cert, criticalExtensions); - } - catch (CertPathValidatorException e) - { - throw new CertPathValidatorException(e.getMessage(), e.getCause(), certPath, index); - } - } - if (!criticalExtensions.isEmpty()) - { - throw new CertPathValidatorException( - "Certificate has unsupported critical extension", null, certPath, index); - } - } - - // set signing certificate for next round - sign = cert; - workingPublicKey = sign.getPublicKey(); - try - { - workingIssuerName = getSubjectPrincipal(sign); - } - catch (IllegalArgumentException ex) - { - throw new CertPathValidatorException(sign.getSubjectDN().getName() + " :" + ex.toString()); - } - workingAlgId = getAlgorithmIdentifier(workingPublicKey); - workingPublicKeyAlgorithm = workingAlgId.getObjectId(); - workingPublicKeyParameters = workingAlgId.getParameters(); - } - catch (AnnotatedException e) - { - throw new CertPathValidatorException(e.getMessage(), e.getUnderlyingException(), certPath, index); - } - } - - // - // 6.1.5 Wrap-up procedure - // - - // - // (a) - // - if (!isSelfIssued(cert) && (explicitPolicy != 0)) - { - explicitPolicy--; - } - - // - // (b) - // - try - { - ASN1Sequence pc = (ASN1Sequence)getExtensionValue(cert, POLICY_CONSTRAINTS); - if (pc != null) - { - Enumeration policyConstraints = pc.getObjects(); - - while (policyConstraints.hasMoreElements()) - { - ASN1TaggedObject constraint = (ASN1TaggedObject)policyConstraints.nextElement(); - switch (constraint.getTagNo()) - { - case 0: - tmpInt = ASN1Integer.getInstance(constraint).getValue().intValue(); - if (tmpInt == 0) - { - explicitPolicy = 0; - } - break; - } - } - } - } - catch (AnnotatedException e) - { - throw new CertPathValidatorException(e.getMessage(), e.getUnderlyingException(), certPath, index); - } - - // - // (c) (d) and (e) are already done - // - - // - // (f) - // - Set criticalExtensions = cert.getCriticalExtensionOIDs(); - - if (criticalExtensions != null) - { - criticalExtensions = new HashSet(criticalExtensions); - // these extensions are handle by the algorithm - criticalExtensions.remove(KEY_USAGE); - criticalExtensions.remove(CERTIFICATE_POLICIES); - criticalExtensions.remove(POLICY_MAPPINGS); - criticalExtensions.remove(INHIBIT_ANY_POLICY); - criticalExtensions.remove(ISSUING_DISTRIBUTION_POINT); - criticalExtensions.remove(DELTA_CRL_INDICATOR); - criticalExtensions.remove(POLICY_CONSTRAINTS); - criticalExtensions.remove(BASIC_CONSTRAINTS); - criticalExtensions.remove(SUBJECT_ALTERNATIVE_NAME); - criticalExtensions.remove(NAME_CONSTRAINTS); - } - else - { - criticalExtensions = new HashSet(); - } - - tmpIter = pathCheckers.iterator(); - while (tmpIter.hasNext()) - { - try - { - ((PKIXCertPathChecker)tmpIter.next()).check(cert, criticalExtensions); - } - catch (CertPathValidatorException e) - { - throw new CertPathValidatorException(e.getMessage(), e.getCause(), certPath, index); - } - } - - if (!criticalExtensions.isEmpty()) - { - throw new CertPathValidatorException( - "Certificate has unsupported critical extension", null, certPath, index); - } - - // - // (g) - // - PKIXPolicyNode intersection; - - - // - // (g) (i) - // - if (validPolicyTree == null) - { - if (paramsPKIX.isExplicitPolicyRequired()) - { - throw new CertPathValidatorException("Explicit policy requested but none available."); - } - intersection = null; - } - else if (isAnyPolicy(userInitialPolicySet)) // (g) (ii) - { - if (paramsPKIX.isExplicitPolicyRequired()) - { - if (acceptablePolicies.isEmpty()) - { - throw new CertPathValidatorException("Explicit policy requested but none available."); - } - else - { - Set _validPolicyNodeSet = new HashSet(); - - for (int j = 0; j < policyNodes.length; j++) - { - List _nodeDepth = policyNodes[j]; - - for (int k = 0; k < _nodeDepth.size(); k++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_nodeDepth.get(k); - - if (ANY_POLICY.equals(_node.getValidPolicy())) - { - Iterator _iter = _node.getChildren(); - while (_iter.hasNext()) - { - _validPolicyNodeSet.add(_iter.next()); - } - } - } - } - - Iterator _vpnsIter = _validPolicyNodeSet.iterator(); - while (_vpnsIter.hasNext()) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_vpnsIter.next(); - String _validPolicy = _node.getValidPolicy(); - - if (!acceptablePolicies.contains(_validPolicy)) - { - //validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, _node); - } - } - if (validPolicyTree != null) - { - for (int j = (n - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node); - } - } - } - } - } - } - - intersection = validPolicyTree; - } - else - { - // - // (g) (iii) - // - // This implementation is not exactly same as the one described in RFC3280. - // However, as far as the validation result is concerned, both produce - // adequate result. The only difference is whether AnyPolicy is remain - // in the policy tree or not. - // - // (g) (iii) 1 - // - Set _validPolicyNodeSet = new HashSet(); - - for (int j = 0; j < policyNodes.length; j++) - { - List _nodeDepth = policyNodes[j]; - - for (int k = 0; k < _nodeDepth.size(); k++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_nodeDepth.get(k); - - if (ANY_POLICY.equals(_node.getValidPolicy())) - { - Iterator _iter = _node.getChildren(); - while (_iter.hasNext()) - { - PKIXPolicyNode _c_node = (PKIXPolicyNode)_iter.next(); - if (!ANY_POLICY.equals(_c_node.getValidPolicy())) - { - _validPolicyNodeSet.add(_c_node); - } - } - } - } - } - - // - // (g) (iii) 2 - // - Iterator _vpnsIter = _validPolicyNodeSet.iterator(); - while (_vpnsIter.hasNext()) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_vpnsIter.next(); - String _validPolicy = _node.getValidPolicy(); - - if (!userInitialPolicySet.contains(_validPolicy)) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, _node); - } - } - - // - // (g) (iii) 4 - // - if (validPolicyTree != null) - { - for (int j = (n - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node); - } - } - } - } - - intersection = validPolicyTree; - } - - if ((explicitPolicy > 0) || (intersection != null)) - { - return new PKIXCertPathValidatorResult(trust, intersection, workingPublicKey); - } - - throw new CertPathValidatorException("Path processing failed on policy.", null, certPath, index); - } - - private Date getValidDate( - PKIXParameters paramsPKIX) - { - Date validDate = paramsPKIX.getDate(); - - if (validDate == null) - { - validDate = new Date(); - } - - return validDate; - } - - private void checkCRLs(PKIXParameters paramsPKIX, X509Certificate cert, Date validDate, X509Certificate sign, PublicKey workingPublicKey) - throws AnnotatedException - { - X509CRLSelector crlselect; - crlselect = new X509CRLSelector(); - - try - { - crlselect.addIssuerName(getEncodedIssuerPrincipal(cert).getEncoded()); - } - catch (IOException e) - { - throw new AnnotatedException("Cannot extract issuer from certificate: " + e, e); - } - - crlselect.setCertificateChecking(cert); - - Iterator crl_iter = findCRLs(crlselect, paramsPKIX.getCertStores()).iterator(); - boolean validCrlFound = false; - X509CRLEntry crl_entry; - while (crl_iter.hasNext()) - { - X509CRL crl = (X509CRL)crl_iter.next(); - - if (cert.getNotAfter().after(crl.getThisUpdate())) - { - if (crl.getNextUpdate() == null - || validDate.before(crl.getNextUpdate())) - { - validCrlFound = true; - } - - if (sign != null) - { - boolean[] keyusage = sign.getKeyUsage(); - - if (keyusage != null - && (keyusage.length < 7 || !keyusage[CRL_SIGN])) - { - throw new AnnotatedException( - "Issuer certificate keyusage extension does not permit crl signing.\n" + sign); - } - } - - try - { - crl.verify(workingPublicKey, "BC"); - } - catch (Exception e) - { - throw new AnnotatedException("can't verify CRL: " + e, e); - } - - crl_entry = crl.getRevokedCertificate(cert.getSerialNumber()); - if (crl_entry != null - && !validDate.before(crl_entry.getRevocationDate())) - { - String reason = null; - - if (crl_entry.hasExtensions()) - { - ASN1Enumerated reasonCode = ASN1Enumerated.getInstance(getExtensionValue(crl_entry, X509Extensions.ReasonCode.getId())); - if (reasonCode != null) - { - reason = crlReasons[reasonCode.getValue().intValue()]; - } - } - - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - String message = "Certificate revocation after " + df.format(crl_entry.getRevocationDate()); - - if (reason != null) - { - message += ", reason: " + reason; - } - - throw new AnnotatedException(message); - } - - // - // check the DeltaCRL indicator, base point and the issuing distribution point - // - ASN1Primitive idp = getExtensionValue(crl, ISSUING_DISTRIBUTION_POINT); - ASN1Primitive dci = getExtensionValue(crl, DELTA_CRL_INDICATOR); - - if (dci != null) - { - X509CRLSelector baseSelect = new X509CRLSelector(); - - try - { - baseSelect.addIssuerName(getIssuerPrincipal(crl).getEncoded()); - } - catch (IOException e) - { - throw new AnnotatedException("can't extract issuer from certificate: " + e, e); - } - - baseSelect.setMinCRLNumber(((ASN1Integer)dci).getPositiveValue()); - baseSelect.setMaxCRLNumber(((ASN1Integer)getExtensionValue(crl, CRL_NUMBER)).getPositiveValue().subtract(BigInteger.valueOf(1))); - - boolean foundBase = false; - Iterator it = findCRLs(baseSelect, paramsPKIX.getCertStores()).iterator(); - while (it.hasNext()) - { - X509CRL base = (X509CRL)it.next(); - - ASN1Primitive baseIdp = getExtensionValue(base, ISSUING_DISTRIBUTION_POINT); - - if (idp == null) - { - if (baseIdp == null) - { - foundBase = true; - break; - } - } - else - { - if (idp.equals(baseIdp)) - { - foundBase = true; - break; - } - } - } - - if (!foundBase) - { - throw new AnnotatedException("No base CRL for delta CRL"); - } - } - - if (idp != null) - { - IssuingDistributionPoint p = IssuingDistributionPoint.getInstance(idp); - BasicConstraints bc = BasicConstraints.getInstance(getExtensionValue(cert, BASIC_CONSTRAINTS)); - - if (p.onlyContainsUserCerts() && (bc != null && bc.isCA())) - { - throw new AnnotatedException("CA Cert CRL only contains user certificates"); - } - - if (p.onlyContainsCACerts() && (bc == null || !bc.isCA())) - { - throw new AnnotatedException("End CRL only contains CA certificates"); - } - - if (p.onlyContainsAttributeCerts()) - { - throw new AnnotatedException("onlyContainsAttributeCerts boolean is asserted"); - } - } - } - } - - if (!validCrlFound) - { - throw new AnnotatedException("no valid CRL found"); - } - } - - /** - * Return a Collection of all CRLs found in the - * CertStore's that are matching the crlSelect criteriums. - * - * @param certSelector a {@link CertSelector CertSelector} - * object that will be used to select the certificates - * @param certStores a List containing only {@link CertStore - * CertStore} objects. These are used to search for - * CRLs - * - * @return a Collection of all found {@link CRL CRL} - * objects. May be empty but never <code>null</code>. - */ - private Collection findCRLs( - X509CRLSelector crlSelect, - List crlStores) - throws AnnotatedException - { - Set crls = new HashSet(); - Iterator iter = crlStores.iterator(); - - while (iter.hasNext()) - { - CertStore certStore = (CertStore)iter.next(); - - try - { - crls.addAll(certStore.getCRLs(crlSelect)); - } - catch (CertStoreException e) - { - throw new AnnotatedException("cannot extract crl: " + e, e); - } - } - - return crls; - } - - /** - * Search the given Set of TrustAnchor's for one that is the - * issuer of the fiven X509 certificate. - * - * @param cert the X509 certificate - * @param trustAnchors a Set of TrustAnchor's - * - * @return the <code>TrustAnchor</code> object if found or - * <code>null</code> if not. - * - * @exception CertPathValidatorException if a TrustAnchor was - * found but the signature verification on the given certificate - * has thrown an exception. This Exception can be obtainted with - * <code>getCause()</code> method. - **/ - final TrustAnchor findTrustAnchor( - X509Certificate cert, - CertPath certPath, - int index, - Set trustAnchors) - throws CertPathValidatorException - { - Iterator iter = trustAnchors.iterator(); - TrustAnchor trust = null; - PublicKey trustPublicKey = null; - Exception invalidKeyEx = null; - - X509CertSelector certSelectX509 = new X509CertSelector(); - - try - { - certSelectX509.setSubject(getEncodedIssuerPrincipal(cert).getEncoded()); - } - catch (IOException ex) - { - throw new CertPathValidatorException(ex); - } - catch (AnnotatedException ex) - { - throw new CertPathValidatorException(ex.getUnderlyingException()); - } - - while (iter.hasNext() && trust == null) - { - trust = (TrustAnchor)iter.next(); - if (trust.getTrustedCert() != null) - { - if (certSelectX509.match(trust.getTrustedCert())) - { - trustPublicKey = trust.getTrustedCert().getPublicKey(); - } - else - { - trust = null; - } - } - else if (trust.getCAName() != null - && trust.getCAPublicKey() != null) - { - try - { - X509Principal certIssuer = getEncodedIssuerPrincipal(cert); - X509Principal caName = new X509Principal(trust.getCAName()); - if (certIssuer.equals(caName)) - { - trustPublicKey = trust.getCAPublicKey(); - } - else - { - trust = null; - } - } - catch (AnnotatedException ex) - { - throw new CertPathValidatorException(ex.getMessage(), ex.getUnderlyingException(), certPath, index); - } - catch (IllegalArgumentException ex) - { - trust = null; - } - } - else - { - trust = null; - } - - if (trustPublicKey != null) - { - try - { - cert.verify(trustPublicKey); - } - catch (Exception ex) - { - invalidKeyEx = ex; - trust = null; - } - } - } - - if (trust == null && invalidKeyEx != null) - { - throw new CertPathValidatorException("TrustAnchor found but certificate validation failed.", invalidKeyEx, certPath, index); - } - - return trust; - } - - private X509Principal getIssuerPrincipal(X509CRL crl) - throws AnnotatedException - { - try - { - return PrincipalUtil.getIssuerX509Principal(crl); - } - catch (CRLException e) - { - throw new AnnotatedException("can't get CRL issuer principal", e); - } - } - - private X509Principal getEncodedIssuerPrincipal(X509Certificate cert) - throws AnnotatedException - { - try - { - return PrincipalUtil.getIssuerX509Principal(cert); - } - catch (CertificateEncodingException e) - { - throw new AnnotatedException("can't get issuer principal.", e); - } - } - - private X509Principal getSubjectPrincipal(X509Certificate cert) - throws AnnotatedException - { - try - { - return PrincipalUtil.getSubjectX509Principal(cert); - } - catch (CertificateEncodingException e) - { - throw new AnnotatedException("can't get subject principal.", e); - } - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/PKIXPolicyNode.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/PKIXPolicyNode.java deleted file mode 100644 index 0f27df4e..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/PKIXPolicyNode.java +++ /dev/null @@ -1,167 +0,0 @@ -package org.bouncycastle.jce.provider; - -import java.security.cert.PolicyNode; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -public class PKIXPolicyNode - implements PolicyNode -{ - protected List children; - protected int depth; - protected Set expectedPolicies; - protected PolicyNode parent; - protected Set policyQualifiers; - protected String validPolicy; - protected boolean critical; - - /* - * - * CONSTRUCTORS - * - */ - - public PKIXPolicyNode( - List _children, - int _depth, - Set _expectedPolicies, - PolicyNode _parent, - Set _policyQualifiers, - String _validPolicy, - boolean _critical) - { - children = _children; - depth = _depth; - expectedPolicies = _expectedPolicies; - parent = _parent; - policyQualifiers = _policyQualifiers; - validPolicy = _validPolicy; - critical = _critical; - } - - public void addChild( - PKIXPolicyNode _child) - { - children.add(_child); - _child.setParent(this); - } - - public Iterator getChildren() - { - return children.iterator(); - } - - public int getDepth() - { - return depth; - } - - public Set getExpectedPolicies() - { - return expectedPolicies; - } - - public PolicyNode getParent() - { - return parent; - } - - public Set getPolicyQualifiers() - { - return policyQualifiers; - } - - public String getValidPolicy() - { - return validPolicy; - } - - public boolean hasChildren() - { - return !children.isEmpty(); - } - - public boolean isCritical() - { - return critical; - } - - public void removeChild(PKIXPolicyNode _child) - { - children.remove(_child); - } - - public void setCritical(boolean _critical) - { - critical = _critical; - } - - public void setParent(PKIXPolicyNode _parent) - { - parent = _parent; - } - - public String toString() - { - return toString(""); - } - - public String toString(String _indent) - { - StringBuffer _buf = new StringBuffer(); - _buf.append(_indent); - _buf.append(validPolicy); - _buf.append(" {\n"); - - for(int i = 0; i < children.size(); i++) { - _buf.append(((PKIXPolicyNode)children.get(i)).toString(_indent + " ")); - } - - _buf.append(_indent); - _buf.append("}\n"); - return _buf.toString(); - } - - public Object clone() - { - return copy(); - } - - public PKIXPolicyNode copy() - { - HashSet _expectedPolicies = new HashSet(); - Iterator _iter = expectedPolicies.iterator(); - while (_iter.hasNext()) - { - _expectedPolicies.add(new String((String)_iter.next())); - } - - HashSet _policyQualifiers = new HashSet(); - _iter = policyQualifiers.iterator(); - while (_iter.hasNext()) - { - _policyQualifiers.add(new String((String)_iter.next())); - } - - PKIXPolicyNode _node = new PKIXPolicyNode(new ArrayList(), - depth, - _expectedPolicies, - null, - _policyQualifiers, - new String(validPolicy), - critical); - - _iter = children.iterator(); - while (_iter.hasNext()) - { - PKIXPolicyNode _child = ((PKIXPolicyNode)_iter.next()).copy(); - _child.setParent(_node); - _node.addChild(_child); - } - - return _node; - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/ProviderUtil.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/ProviderUtil.java deleted file mode 100644 index 2a485ecc..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/ProviderUtil.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.bouncycastle.jce.provider; - -import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; -import org.bouncycastle.jce.spec.ECParameterSpec; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -public class ProviderUtil -{ - private static final long MAX_MEMORY = Integer.MAX_VALUE; - - private static volatile ECParameterSpec ecImplicitCaParams; - - static void setParameter(String parameterName, Object parameter) - { - if (parameterName.equals(ConfigurableProvider.EC_IMPLICITLY_CA)) - { - if (parameter instanceof ECParameterSpec || parameter == null) - { - ecImplicitCaParams = (ECParameterSpec)parameter; - } - } - } - - public static ECParameterSpec getEcImplicitlyCa() - { - return ecImplicitCaParams; - } - - static int getReadLimit(InputStream in) - throws IOException - { - if (in instanceof ByteArrayInputStream) - { - return in.available(); - } - - if (MAX_MEMORY > Integer.MAX_VALUE) - { - return Integer.MAX_VALUE; - } - - return (int)MAX_MEMORY; - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java deleted file mode 100644 index 368615f2..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.bouncycastle.jce.provider; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.PublicKey; -import java.security.cert.CertPath; -import java.security.cert.CertPathBuilder; -import java.security.cert.CertPathBuilderException; -import java.security.cert.CertPathValidatorException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.PKIXCertPathChecker; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.security.cert.X509Extension; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Vector; - -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1TaggedObject; -import org.bouncycastle.asn1.x509.BasicConstraints; -import org.bouncycastle.asn1.x509.CRLDistPoint; -import org.bouncycastle.asn1.x509.CRLReason; -import org.bouncycastle.asn1.x509.DistributionPoint; -import org.bouncycastle.asn1.x509.DistributionPointName; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.asn1.x509.GeneralSubtree; -import org.bouncycastle.asn1.x509.IssuingDistributionPoint; -import org.bouncycastle.asn1.x509.NameConstraints; -import org.bouncycastle.asn1.x509.PolicyInformation; -import org.bouncycastle.asn1.x509.X509Extensions; -import org.bouncycastle.asn1.x509.X509Name; -import org.bouncycastle.util.Arrays; - -public class RFC3280CertPathUtilities -{ - public static final String CERTIFICATE_POLICIES = X509Extensions.CertificatePolicies.getId(); - - public static final String POLICY_MAPPINGS = X509Extensions.PolicyMappings.getId(); - - public static final String INHIBIT_ANY_POLICY = X509Extensions.InhibitAnyPolicy.getId(); - - public static final String ISSUING_DISTRIBUTION_POINT = X509Extensions.IssuingDistributionPoint.getId(); - - public static final String FRESHEST_CRL = X509Extensions.FreshestCRL.getId(); - - public static final String DELTA_CRL_INDICATOR = X509Extensions.DeltaCRLIndicator.getId(); - - public static final String POLICY_CONSTRAINTS = X509Extensions.PolicyConstraints.getId(); - - public static final String BASIC_CONSTRAINTS = X509Extensions.BasicConstraints.getId(); - - public static final String CRL_DISTRIBUTION_POINTS = X509Extensions.CRLDistributionPoints.getId(); - - public static final String SUBJECT_ALTERNATIVE_NAME = X509Extensions.SubjectAlternativeName.getId(); - - public static final String NAME_CONSTRAINTS = X509Extensions.NameConstraints.getId(); - - public static final String AUTHORITY_KEY_IDENTIFIER = X509Extensions.AuthorityKeyIdentifier.getId(); - - public static final String KEY_USAGE = X509Extensions.KeyUsage.getId(); - - public static final String CRL_NUMBER = X509Extensions.CRLNumber.getId(); - - public static final String ANY_POLICY = "2.5.29.32.0"; - - /* - * key usage bits - */ - public static final int KEY_CERT_SIGN = 5; - - public static final int CRL_SIGN = 6; - -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CRLObject.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CRLObject.java deleted file mode 100644 index 324cf84a..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CRLObject.java +++ /dev/null @@ -1,554 +0,0 @@ -package org.bouncycastle.jce.provider; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.CRLException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -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.ASN1Integer; -import org.bouncycastle.asn1.util.ASN1Dump; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.CRLDistPoint; -import org.bouncycastle.asn1.x509.CRLNumber; -import org.bouncycastle.asn1.x509.CertificateList; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.Extensions; -import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.asn1.x509.IssuingDistributionPoint; -import org.bouncycastle.asn1.x509.TBSCertList; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.util.encoders.Hex; -import org.bouncycastle.x509.extension.X509ExtensionUtil; - -/** - * The following extensions are listed in RFC 2459 as relevant to CRLs - * - * Authority Key Identifier - * Issuer Alternative Name - * CRL Number - * Delta CRL Indicator (critical) - * Issuing Distribution Point (critical) - */ -public class X509CRLObject - extends X509CRL -{ - private CertificateList c; - private String sigAlgName; - private byte[] sigAlgParams; - private boolean isIndirect; - - static boolean isIndirectCRL(X509CRL crl) - throws CRLException - { - try - { - byte[] idp = crl.getExtensionValue(Extension.issuingDistributionPoint.getId()); - return idp != null - && IssuingDistributionPoint.getInstance(X509ExtensionUtil.fromExtensionValue(idp)).isIndirectCRL(); - } - catch (Exception e) - { - throw new ExtCRLException( - "Exception reading IssuingDistributionPoint", e); - } - } - - public X509CRLObject( - CertificateList c) - throws CRLException - { - this.c = c; - - try - { - this.sigAlgName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - - if (c.getSignatureAlgorithm().getParameters() != null) - { - this.sigAlgParams = ((ASN1Encodable)c.getSignatureAlgorithm().getParameters()).toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - else - { - this.sigAlgParams = null; - } - - this.isIndirect = isIndirectCRL(this); - } - catch (Exception e) - { - throw new CRLException("CRL contents invalid: " + e); - } - } - - /** - * Will return true if any extensions are present and marked - * as critical as we currently dont handle any extensions! - */ - public boolean hasUnsupportedCriticalExtension() - { - Set extns = getCriticalExtensionOIDs(); - - if (extns == null) - { - return false; - } - - extns.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); - extns.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); - - return !extns.isEmpty(); - } - - private Set getExtensionOIDs(boolean critical) - { - if (this.getVersion() == 2) - { - Extensions extensions = c.getTBSCertList().getExtensions(); - - if (extensions != null) - { - Set set = new HashSet(); - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (critical == ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - public Set getCriticalExtensionOIDs() - { - return getExtensionOIDs(true); - } - - public Set getNonCriticalExtensionOIDs() - { - return getExtensionOIDs(false); - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getTBSCertList().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; - } - - public byte[] getEncoded() - throws CRLException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public void verify(PublicKey key) - throws CRLException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - verify(key, BouncyCastleProvider.PROVIDER_NAME); - } - - public void verify(PublicKey key, String sigProvider) - throws CRLException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - if (!c.getSignatureAlgorithm().equals(c.getTBSCertList().getSignature())) - { - throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList."); - } - - Signature sig; - - if (sigProvider != null) - { - sig = Signature.getInstance(getSigAlgName(), sigProvider); - } - else - { - sig = Signature.getInstance(getSigAlgName()); - } - - sig.initVerify(key); - sig.update(this.getTBSCertList()); - - if (!sig.verify(this.getSignature())) - { - throw new SignatureException("CRL does not verify with supplied public key."); - } - } - - public int getVersion() - { - return c.getVersionNumber(); - } - - public Principal getIssuerDN() - { - return new X509Principal(X500Name.getInstance(c.getIssuer().toASN1Primitive())); - } - - public Date getThisUpdate() - { - return c.getThisUpdate().getDate(); - } - - public Date getNextUpdate() - { - if (c.getNextUpdate() != null) - { - return c.getNextUpdate().getDate(); - } - - return null; - } - - private Set loadCRLEntries() - { - Set entrySet = new HashSet(); - Enumeration certs = c.getRevokedCertificateEnumeration(); - - X500Name previousCertificateIssuer = c.getIssuer(); - while (certs.hasMoreElements()) - { - TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); - X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); - entrySet.add(crlEntry); - if (isIndirect && entry.hasExtensions()) - { - Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - } - - return entrySet; - } - - public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) - { - Enumeration certs = c.getRevokedCertificateEnumeration(); - - X500Name previousCertificateIssuer = c.getIssuer(); - while (certs.hasMoreElements()) - { - TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); - - if (serialNumber.equals(entry.getUserCertificate().getValue())) - { - return new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); - } - - if (isIndirect && entry.hasExtensions()) - { - Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - } - - return null; - } - - public Set getRevokedCertificates() - { - Set entrySet = loadCRLEntries(); - - if (!entrySet.isEmpty()) - { - return Collections.unmodifiableSet(entrySet); - } - - return null; - } - - public byte[] getTBSCertList() - throws CRLException - { - try - { - return c.getTBSCertList().getEncoded("DER"); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public byte[] getSignature() - { - return c.getSignature().getBytes(); - } - - public String getSigAlgName() - { - return sigAlgName; - } - - public String getSigAlgOID() - { - return c.getSignatureAlgorithm().getAlgorithm().getId(); - } - - public byte[] getSigAlgParams() - { - if (sigAlgParams != null) - { - byte[] tmp = new byte[sigAlgParams.length]; - - System.arraycopy(sigAlgParams, 0, tmp, 0, tmp.length); - - return tmp; - } - - return null; - } - - /** - * Returns a string representation of this CRL. - * - * @return a string representation of this CRL. - */ - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" Version: ").append(this.getVersion()).append( - nl); - buf.append(" IssuerDN: ").append(this.getIssuerDN()) - .append(nl); - buf.append(" This update: ").append(this.getThisUpdate()) - .append(nl); - buf.append(" Next update: ").append(this.getNextUpdate()) - .append(nl); - buf.append(" Signature Algorithm: ").append(this.getSigAlgName()) - .append(nl); - - byte[] sig = this.getSignature(); - - buf.append(" Signature: ").append( - new String(Hex.encode(sig, 0, 20))).append(nl); - for (int i = 20; i < sig.length; i += 20) - { - if (i < sig.length - 20) - { - buf.append(" ").append( - new String(Hex.encode(sig, i, 20))).append(nl); - } - else - { - buf.append(" ").append( - new String(Hex.encode(sig, i, sig.length - i))).append(nl); - } - } - - Extensions extensions = c.getTBSCertList().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - if (e.hasMoreElements()) - { - buf.append(" Extensions: ").append(nl); - } - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append( - ext.isCritical()).append(") "); - try - { - if (oid.equals(Extension.cRLNumber)) - { - buf.append( - new CRLNumber(ASN1Integer.getInstance( - dIn.readObject()).getPositiveValue())) - .append(nl); - } - else if (oid.equals(Extension.deltaCRLIndicator)) - { - buf.append( - "Base CRL: " - + new CRLNumber(ASN1Integer.getInstance( - dIn.readObject()).getPositiveValue())) - .append(nl); - } - else if (oid - .equals(Extension.issuingDistributionPoint)) - { - buf.append( - IssuingDistributionPoint.getInstance(dIn.readObject())).append(nl); - } - else if (oid - .equals(Extension.cRLDistributionPoints)) - { - buf.append( - CRLDistPoint.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(Extension.freshestCRL)) - { - buf.append( - CRLDistPoint.getInstance(dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append( - ASN1Dump.dumpAsString(dIn.readObject())) - .append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - Set set = getRevokedCertificates(); - if (set != null) - { - Iterator it = set.iterator(); - while (it.hasNext()) - { - buf.append(it.next()); - buf.append(nl); - } - } - return buf.toString(); - } - - /** - * Checks whether the given certificate is on this CRL. - * - * @param cert the certificate to check for. - * @return true if the given certificate is on this CRL, - * false otherwise. - */ - public boolean isRevoked(Certificate cert) - { - if (!cert.getType().equals("X.509")) - { - throw new RuntimeException("X.509 CRL used with non X.509 Cert"); - } - - TBSCertList.CRLEntry[] certs = c.getRevokedCertificates(); - - X500Name caName = c.getIssuer(); - - if (certs != null) - { - BigInteger serial = ((X509Certificate)cert).getSerialNumber(); - - for (int i = 0; i < certs.length; i++) - { - if (isIndirect && certs[i].hasExtensions()) - { - Extension currentCaName = certs[i].getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - caName = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - - if (certs[i].getUserCertificate().getValue().equals(serial)) - { - X500Name issuer; - - try - { - issuer = org.bouncycastle.asn1.x509.Certificate.getInstance(cert.getEncoded()).getIssuer(); - } - catch (CertificateEncodingException e) - { - throw new RuntimeException("Cannot process certificate"); - } - - if (!caName.equals(issuer)) - { - return false; - } - - return true; - } - } - } - - return false; - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CertificateObject.java b/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CertificateObject.java deleted file mode 100644 index d7ec243e..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/jce/provider/X509CertificateObject.java +++ /dev/null @@ -1,856 +0,0 @@ -package org.bouncycastle.jce.provider; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.Provider; -import java.security.PublicKey; -import java.security.Security; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -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.ASN1InputStream; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OutputStream; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1String; -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.DERIA5String; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.misc.MiscObjectIdentifiers; -import org.bouncycastle.asn1.misc.NetscapeCertType; -import org.bouncycastle.asn1.misc.NetscapeRevocationURL; -import org.bouncycastle.asn1.misc.VerisignCzagExtension; -import org.bouncycastle.asn1.util.ASN1Dump; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x500.style.RFC4519Style; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.BasicConstraints; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.Extensions; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.KeyUsage; -import org.bouncycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.Integers; -import org.bouncycastle.util.encoders.Hex; - -public class X509CertificateObject - extends X509Certificate - implements PKCS12BagAttributeCarrier -{ - private org.bouncycastle.asn1.x509.Certificate c; - private BasicConstraints basicConstraints; - private boolean[] keyUsage; - private boolean hashValueSet; - private int hashValue; - - private PKCS12BagAttributeCarrier attrCarrier = new PKCS12BagAttributeCarrierImpl(); - - public X509CertificateObject( - org.bouncycastle.asn1.x509.Certificate c) - throws CertificateParsingException - { - this.c = c; - - try - { - byte[] bytes = this.getExtensionBytes("2.5.29.19"); - - if (bytes != null) - { - basicConstraints = BasicConstraints.getInstance(ASN1Primitive.fromByteArray(bytes)); - } - } - catch (Exception e) - { - throw new CertificateParsingException("cannot construct BasicConstraints: " + e); - } - - try - { - byte[] bytes = this.getExtensionBytes("2.5.29.15"); - if (bytes != null) - { - DERBitString bits = DERBitString.getInstance(ASN1Primitive.fromByteArray(bytes)); - - bytes = bits.getBytes(); - int length = (bytes.length * 8) - bits.getPadBits(); - - keyUsage = new boolean[(length < 9) ? 9 : length]; - - for (int i = 0; i != length; i++) - { - keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - } - else - { - keyUsage = null; - } - } - catch (Exception e) - { - throw new CertificateParsingException("cannot construct KeyUsage: " + e); - } - } - - public void checkValidity() - throws CertificateExpiredException, CertificateNotYetValidException - { - this.checkValidity(new Date()); - } - - public void checkValidity( - Date date) - throws CertificateExpiredException, CertificateNotYetValidException - { - if (date.getTime() > this.getNotAfter().getTime()) // for other VM compatibility - { - throw new CertificateExpiredException("certificate expired on " + c.getEndDate().getTime()); - } - - if (date.getTime() < this.getNotBefore().getTime()) - { - throw new CertificateNotYetValidException("certificate not valid till " + c.getStartDate().getTime()); - } - } - - public int getVersion() - { - return c.getVersionNumber(); - } - - public BigInteger getSerialNumber() - { - return c.getSerialNumber().getValue(); - } - - public Principal getIssuerDN() - { - try - { - return new X509Principal(X500Name.getInstance(c.getIssuer().getEncoded())); - } - catch (IOException e) - { - return null; - } - } - - public Principal getSubjectDN() - { - return new X509Principal(X500Name.getInstance(c.getSubject().toASN1Primitive())); - } - - public Date getNotBefore() - { - return c.getStartDate().getDate(); - } - - public Date getNotAfter() - { - return c.getEndDate().getDate(); - } - - public byte[] getTBSCertificate() - throws CertificateEncodingException - { - try - { - return c.getTBSCertificate().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException(e.toString()); - } - } - - public byte[] getSignature() - { - return c.getSignature().getBytes(); - } - - /** - * return a more "meaningful" representation for the signature algorithm used in - * the certficate. - */ - public String getSigAlgName() - { - Provider prov = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME); - - if (prov != null) - { - String algName = prov.getProperty("Alg.Alias.Signature." + this.getSigAlgOID()); - - if (algName != null) - { - return algName; - } - } - - Provider[] provs = Security.getProviders(); - - // - // search every provider looking for a real algorithm - // - for (int i = 0; i != provs.length; i++) - { - String algName = provs[i].getProperty("Alg.Alias.Signature." + this.getSigAlgOID()); - if (algName != null) - { - return algName; - } - } - - return this.getSigAlgOID(); - } - - /** - * return the object identifier for the signature. - */ - public String getSigAlgOID() - { - return c.getSignatureAlgorithm().getAlgorithm().getId(); - } - - /** - * return the signature parameters, or null if there aren't any. - */ - public byte[] getSigAlgParams() - { - if (c.getSignatureAlgorithm().getParameters() != null) - { - try - { - return c.getSignatureAlgorithm().getParameters().toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - return null; - } - } - else - { - return null; - } - } - - public boolean[] getIssuerUniqueID() - { - DERBitString id = c.getTBSCertificate().getIssuerUniqueId(); - - if (id != null) - { - byte[] bytes = id.getBytes(); - boolean[] boolId = new boolean[bytes.length * 8 - id.getPadBits()]; - - for (int i = 0; i != boolId.length; i++) - { - boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - - return boolId; - } - - return null; - } - - public boolean[] getSubjectUniqueID() - { - DERBitString id = c.getTBSCertificate().getSubjectUniqueId(); - - if (id != null) - { - byte[] bytes = id.getBytes(); - boolean[] boolId = new boolean[bytes.length * 8 - id.getPadBits()]; - - for (int i = 0; i != boolId.length; i++) - { - boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - - return boolId; - } - - return null; - } - - public boolean[] getKeyUsage() - { - return keyUsage; - } - - public List getExtendedKeyUsage() - throws CertificateParsingException - { - byte[] bytes = this.getExtensionBytes("2.5.29.37"); - - if (bytes != null) - { - try - { - ASN1InputStream dIn = new ASN1InputStream(bytes); - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - List list = new ArrayList(); - - for (int i = 0; i != seq.size(); i++) - { - list.add(((ASN1ObjectIdentifier)seq.getObjectAt(i)).getId()); - } - - return Collections.unmodifiableList(list); - } - catch (Exception e) - { - throw new CertificateParsingException("error processing extended key usage extension"); - } - } - - return null; - } - - public int getBasicConstraints() - { - if (basicConstraints != null) - { - if (basicConstraints.isCA()) - { - if (basicConstraints.getPathLenConstraint() == null) - { - return Integer.MAX_VALUE; - } - else - { - return basicConstraints.getPathLenConstraint().intValue(); - } - } - else - { - return -1; - } - } - - return -1; - } - - public Collection getSubjectAlternativeNames() - throws CertificateParsingException - { - return getAlternativeNames(getExtensionBytes(Extension.subjectAlternativeName.getId())); - } - - public Collection getIssuerAlternativeNames() - throws CertificateParsingException - { - return getAlternativeNames(getExtensionBytes(Extension.issuerAlternativeName.getId())); - } - - public Set getCriticalExtensionOIDs() - { - if (this.getVersion() == 3) - { - Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - private byte[] getExtensionBytes(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (ext != null) - { - return ext.getExtnValue().getOctets(); - } - } - - return null; - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; - } - - public Set getNonCriticalExtensionOIDs() - { - if (this.getVersion() == 3) - { - Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (!ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - public boolean hasUnsupportedCriticalExtension() - { - if (this.getVersion() == 3) - { - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - String oidId = oid.getId(); - - if (oidId.equals(RFC3280CertPathUtilities.KEY_USAGE) - || oidId.equals(RFC3280CertPathUtilities.CERTIFICATE_POLICIES) - || oidId.equals(RFC3280CertPathUtilities.POLICY_MAPPINGS) - || oidId.equals(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY) - || oidId.equals(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS) - || oidId.equals(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT) - || oidId.equals(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR) - || oidId.equals(RFC3280CertPathUtilities.POLICY_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.BASIC_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME) - || oidId.equals(RFC3280CertPathUtilities.NAME_CONSTRAINTS)) - { - continue; - } - - Extension ext = extensions.getExtension(oid); - - if (ext.isCritical()) - { - return true; - } - } - } - } - - return false; - } - - public PublicKey getPublicKey() - { - try - { - return BouncyCastleProvider.getPublicKey(c.getSubjectPublicKeyInfo()); - } - catch (IOException e) - { - return null; // should never happen... - } - } - - public byte[] getEncoded() - throws CertificateEncodingException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException(e.toString()); - } - } - - public boolean equals( - Object o) - { - if (o == this) - { - return true; - } - - if (!(o instanceof Certificate)) - { - return false; - } - - Certificate other = (Certificate)o; - - try - { - byte[] b1 = this.getEncoded(); - byte[] b2 = other.getEncoded(); - - return Arrays.areEqual(b1, b2); - } - catch (CertificateEncodingException e) - { - return false; - } - } - - public synchronized int hashCode() - { - if (!hashValueSet) - { - hashValue = calculateHashCode(); - hashValueSet = true; - } - - return hashValue; - } - - private int calculateHashCode() - { - try - { - int hashCode = 0; - byte[] certData = this.getEncoded(); - for (int i = 1; i < certData.length; i++) - { - hashCode += certData[i] * i; - } - return hashCode; - } - catch (CertificateEncodingException e) - { - return 0; - } - } - - public void setBagAttribute( - ASN1ObjectIdentifier oid, - ASN1Encodable attribute) - { - attrCarrier.setBagAttribute(oid, attribute); - } - - public ASN1Encodable getBagAttribute( - ASN1ObjectIdentifier oid) - { - return attrCarrier.getBagAttribute(oid); - } - - public Enumeration getBagAttributeKeys() - { - return attrCarrier.getBagAttributeKeys(); - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" [0] Version: ").append(this.getVersion()).append(nl); - buf.append(" SerialNumber: ").append(this.getSerialNumber()).append(nl); - buf.append(" IssuerDN: ").append(this.getIssuerDN()).append(nl); - buf.append(" Start Date: ").append(this.getNotBefore()).append(nl); - buf.append(" Final Date: ").append(this.getNotAfter()).append(nl); - buf.append(" SubjectDN: ").append(this.getSubjectDN()).append(nl); - buf.append(" Public Key: ").append(this.getPublicKey()).append(nl); - buf.append(" Signature Algorithm: ").append(this.getSigAlgName()).append(nl); - - byte[] sig = this.getSignature(); - - buf.append(" Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl); - for (int i = 20; i < sig.length; i += 20) - { - if (i < sig.length - 20) - { - buf.append(" ").append(new String(Hex.encode(sig, i, 20))).append(nl); - } - else - { - buf.append(" ").append(new String(Hex.encode(sig, i, sig.length - i))).append(nl); - } - } - - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - if (e.hasMoreElements()) - { - buf.append(" Extensions: \n"); - } - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append(ext.isCritical()).append(") "); - try - { - if (oid.equals(Extension.basicConstraints)) - { - buf.append(BasicConstraints.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(Extension.keyUsage)) - { - buf.append(KeyUsage.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.netscapeCertType)) - { - buf.append(new NetscapeCertType((DERBitString)dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)) - { - buf.append(new NetscapeRevocationURL((DERIA5String)dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.verisignCzagExtension)) - { - buf.append(new VerisignCzagExtension((DERIA5String)dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl); - //buf.append(" value = ").append("*****").append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - // buf.append(" value = ").append(new String(Hex.encode(ext.getExtnValue().getOctets()))).append(nl); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - - return buf.toString(); - } - - public final void verify( - PublicKey key) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - Signature signature; - String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - - try - { - signature = Signature.getInstance(sigName, BouncyCastleProvider.PROVIDER_NAME); - } - catch (Exception e) - { - signature = Signature.getInstance(sigName); - } - - checkSignature(key, signature); - } - - public final void verify( - PublicKey key, - String sigProvider) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - Signature signature = Signature.getInstance(sigName, sigProvider); - - checkSignature(key, signature); - } - - private void checkSignature( - PublicKey key, - Signature signature) - throws CertificateException, NoSuchAlgorithmException, - SignatureException, InvalidKeyException - { - if (!isAlgIdEqual(c.getSignatureAlgorithm(), c.getTBSCertificate().getSignature())) - { - throw new CertificateException("signature algorithm in TBS cert not same as outer cert"); - } - - ASN1Encodable params = c.getSignatureAlgorithm().getParameters(); - - // TODO This should go after the initVerify? - X509SignatureUtil.setSignatureParameters(signature, params); - - signature.initVerify(key); - - signature.update(this.getTBSCertificate()); - - if (!signature.verify(this.getSignature())) - { - throw new SignatureException("certificate does not verify with supplied key"); - } - } - - private boolean isAlgIdEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) - { - if (!id1.getAlgorithm().equals(id2.getAlgorithm())) - { - return false; - } - - if (id1.getParameters() == null) - { - if (id2.getParameters() != null && !id2.getParameters().equals(DERNull.INSTANCE)) - { - return false; - } - - return true; - } - - if (id2.getParameters() == null) - { - if (id1.getParameters() != null && !id1.getParameters().equals(DERNull.INSTANCE)) - { - return false; - } - - return true; - } - - return id1.getParameters().equals(id2.getParameters()); - } - - private static Collection getAlternativeNames(byte[] extVal) - throws CertificateParsingException - { - if (extVal == null) - { - return null; - } - try - { - Collection temp = new ArrayList(); - Enumeration it = ASN1Sequence.getInstance(extVal).getObjects(); - while (it.hasMoreElements()) - { - GeneralName genName = GeneralName.getInstance(it.nextElement()); - List list = new ArrayList(); - list.add(Integers.valueOf(genName.getTagNo())); - switch (genName.getTagNo()) - { - case GeneralName.ediPartyName: - case GeneralName.x400Address: - case GeneralName.otherName: - list.add(genName.getEncoded()); - break; - case GeneralName.directoryName: - list.add(X500Name.getInstance(RFC4519Style.INSTANCE, genName.getName()).toString()); - break; - case GeneralName.dNSName: - case GeneralName.rfc822Name: - case GeneralName.uniformResourceIdentifier: - list.add(((ASN1String)genName.getName()).getString()); - break; - case GeneralName.registeredID: - list.add(ASN1ObjectIdentifier.getInstance(genName.getName()).getId()); - break; - case GeneralName.iPAddress: - byte[] addrBytes = DEROctetString.getInstance(genName.getName()).getOctets(); - list.add(addrBytes); - break; - default: - throw new IOException("Bad tag number: " + genName.getTagNo()); - } - - temp.add(list); - } - if (temp.size() == 0) - { - return null; - } - return Collections.unmodifiableCollection(temp); - } - catch (Exception e) - { - throw new CertificateParsingException(e.getMessage()); - } - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/x509/AttributeCertificateHolder.java b/prov/src/main/jdk1.1/org/bouncycastle/x509/AttributeCertificateHolder.java deleted file mode 100644 index ee24f8c8..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/x509/AttributeCertificateHolder.java +++ /dev/null @@ -1,406 +0,0 @@ -package org.bouncycastle.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.Principal; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.asn1.x509.Holder; -import org.bouncycastle.asn1.x509.IssuerSerial; -import org.bouncycastle.asn1.x509.ObjectDigestInfo; -import org.bouncycastle.jce.PrincipalUtil; -import org.bouncycastle.jce.X509Principal; -import java.security.cert.CertSelector; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.Selector; - -/** - * The Holder object. - * - * <pre> - * Holder ::= SEQUENCE { - * baseCertificateID [0] IssuerSerial OPTIONAL, - * -- the issuer and serial number of - * -- the holder's Public Key Certificate - * entityName [1] GeneralNames OPTIONAL, - * -- the name of the claimant or role - * objectDigestInfo [2] ObjectDigestInfo OPTIONAL - * -- used to directly authenticate the holder, - * -- for example, an executable - * } - * </pre> - * @deprecated use org.bouncycastle.cert.AttributeCertificateHolder - */ -public class AttributeCertificateHolder - implements CertSelector, Selector -{ - final Holder holder; - - AttributeCertificateHolder(ASN1Sequence seq) - { - holder = Holder.getInstance(seq); - } - - public AttributeCertificateHolder(X509Principal issuerName, - BigInteger serialNumber) - { - holder = new org.bouncycastle.asn1.x509.Holder(new IssuerSerial( - new GeneralNames(new GeneralName(issuerName)), - new ASN1Integer(serialNumber))); - } - - public AttributeCertificateHolder(X509Certificate cert) - throws CertificateParsingException - { - X509Principal name; - - try - { - name = PrincipalUtil.getIssuerX509Principal(cert); - } - catch (Exception e) - { - throw new CertificateParsingException(e.getMessage()); - } - - holder = new Holder(new IssuerSerial(generateGeneralNames(name), - new ASN1Integer(cert.getSerialNumber()))); - } - - public AttributeCertificateHolder(X509Principal principal) - { - holder = new Holder(generateGeneralNames(principal)); - } - - /** - * Constructs a holder for v2 attribute certificates with a hash value for - * some type of object. - * <p> - * <code>digestedObjectType</code> can be one of the following: - * <ul> - * <li>0 - publicKey - A hash of the public key of the holder must be - * passed. - * <li>1 - publicKeyCert - A hash of the public key certificate of the - * holder must be passed. - * <li>2 - otherObjectDigest - A hash of some other object type must be - * passed. <code>otherObjectTypeID</code> must not be empty. - * </ul> - * <p> - * This cannot be used if a v1 attribute certificate is used. - * - * @param digestedObjectType The digest object type. - * @param digestAlgorithm The algorithm identifier for the hash. - * @param otherObjectTypeID The object type ID if - * <code>digestedObjectType</code> is - * <code>otherObjectDigest</code>. - * @param objectDigest The hash value. - */ - public AttributeCertificateHolder(int digestedObjectType, - String digestAlgorithm, String otherObjectTypeID, byte[] objectDigest) - { - holder = new Holder(new ObjectDigestInfo(digestedObjectType, - new ASN1ObjectIdentifier(otherObjectTypeID), new AlgorithmIdentifier(digestAlgorithm), Arrays - .clone(objectDigest))); - } - - /** - * Returns the digest object type if an object digest info is used. - * <p> - * <ul> - * <li>0 - publicKey - A hash of the public key of the holder must be - * passed. - * <li>1 - publicKeyCert - A hash of the public key certificate of the - * holder must be passed. - * <li>2 - otherObjectDigest - A hash of some other object type must be - * passed. <code>otherObjectTypeID</code> must not be empty. - * </ul> - * - * @return The digest object type or -1 if no object digest info is set. - */ - public int getDigestedObjectType() - { - if (holder.getObjectDigestInfo() != null) - { - return holder.getObjectDigestInfo().getDigestedObjectType() - .getValue().intValue(); - } - return -1; - } - - /** - * Returns the other object type ID if an object digest info is used. - * - * @return The other object type ID or <code>null</code> if no object - * digest info is set. - */ - public String getDigestAlgorithm() - { - if (holder.getObjectDigestInfo() != null) - { - return holder.getObjectDigestInfo().getDigestAlgorithm().getObjectId() - .getId(); - } - return null; - } - - /** - * Returns the hash if an object digest info is used. - * - * @return The hash or <code>null</code> if no object digest info is set. - */ - public byte[] getObjectDigest() - { - if (holder.getObjectDigestInfo() != null) - { - return holder.getObjectDigestInfo().getObjectDigest().getBytes(); - } - return null; - } - - /** - * Returns the digest algorithm ID if an object digest info is used. - * - * @return The digest algorithm ID or <code>null</code> if no object - * digest info is set. - */ - public String getOtherObjectTypeID() - { - if (holder.getObjectDigestInfo() != null) - { - holder.getObjectDigestInfo().getOtherObjectTypeID().getId(); - } - return null; - } - - private GeneralNames generateGeneralNames(X509Principal principal) - { - return new GeneralNames(new GeneralName(principal)); - } - - private boolean matchesDN(X509Principal subject, GeneralNames targets) - { - GeneralName[] names = targets.getNames(); - - for (int i = 0; i != names.length; i++) - { - GeneralName gn = names[i]; - - if (gn.getTagNo() == GeneralName.directoryName) - { - try - { - if (new X509Principal(((ASN1Encodable)gn.getName()).toASN1Primitive() - .getEncoded()).equals(subject)) - { - return true; - } - } - catch (IOException e) - { - } - } - } - - return false; - } - - private Object[] getNames(GeneralName[] names) - { - List l = new ArrayList(names.length); - - for (int i = 0; i != names.length; i++) - { - if (names[i].getTagNo() == GeneralName.directoryName) - { - try - { - l.add(new X509Principal( - ((ASN1Encodable)names[i].getName()).toASN1Primitive().getEncoded())); - } - catch (IOException e) - { - throw new RuntimeException("badly formed Name object"); - } - } - } - - return l.toArray(new Object[l.size()]); - } - - private Principal[] getPrincipals(GeneralNames names) - { - Object[] p = this.getNames(names.getNames()); - List l = new ArrayList(); - - for (int i = 0; i != p.length; i++) - { - if (p[i] instanceof Principal) - { - l.add(p[i]); - } - } - - return (Principal[])l.toArray(new Principal[l.size()]); - } - - /** - * Return any principal objects inside the attribute certificate holder - * entity names field. - * - * @return an array of Principal objects (usually X509Principal), null if no - * entity names field is set. - */ - public Principal[] getEntityNames() - { - if (holder.getEntityName() != null) - { - return getPrincipals(holder.getEntityName()); - } - - return null; - } - - /** - * Return the principals associated with the issuer attached to this holder - * - * @return an array of principals, null if no BaseCertificateID is set. - */ - public Principal[] getIssuer() - { - if (holder.getBaseCertificateID() != null) - { - return getPrincipals(holder.getBaseCertificateID().getIssuer()); - } - - return null; - } - - /** - * Return the serial number associated with the issuer attached to this - * holder. - * - * @return the certificate serial number, null if no BaseCertificateID is - * set. - */ - public BigInteger getSerialNumber() - { - if (holder.getBaseCertificateID() != null) - { - return holder.getBaseCertificateID().getSerial().getValue(); - } - - return null; - } - - public Object clone() - { - return new AttributeCertificateHolder((ASN1Sequence)holder - .toASN1Object()); - } - - public boolean match(Certificate cert) - { - if (!(cert instanceof X509Certificate)) - { - return false; - } - - X509Certificate x509Cert = (X509Certificate)cert; - - try - { - if (holder.getBaseCertificateID() != null) - { - return holder.getBaseCertificateID().getSerial().getValue().equals(x509Cert.getSerialNumber()) - && matchesDN(PrincipalUtil.getIssuerX509Principal(x509Cert), holder.getBaseCertificateID().getIssuer()); - } - - if (holder.getEntityName() != null) - { - if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), - holder.getEntityName())) - { - return true; - } - } - if (holder.getObjectDigestInfo() != null) - { - MessageDigest md = null; - try - { - md = MessageDigest.getInstance(getDigestAlgorithm(), "BC"); - - } - catch (Exception e) - { - return false; - } - switch (getDigestedObjectType()) - { - case ObjectDigestInfo.publicKey: - // TODO: DSA Dss-parms - md.update(cert.getPublicKey().getEncoded()); - break; - case ObjectDigestInfo.publicKeyCert: - md.update(cert.getEncoded()); - break; - } - if (!Arrays.areEqual(md.digest(), getObjectDigest())) - { - return false; - } - } - } - catch (CertificateEncodingException e) - { - return false; - } - - return false; - } - - public boolean equals(Object obj) - { - if (obj == this) - { - return true; - } - - if (!(obj instanceof AttributeCertificateHolder)) - { - return false; - } - - AttributeCertificateHolder other = (AttributeCertificateHolder)obj; - - return this.holder.equals(other.holder); - } - - public int hashCode() - { - return this.holder.hashCode(); - } - - public boolean match(Object obj) - { - if (!(obj instanceof X509Certificate)) - { - return false; - } - - return match((Certificate)obj); - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/x509/AttributeCertificateIssuer.java b/prov/src/main/jdk1.1/org/bouncycastle/x509/AttributeCertificateIssuer.java deleted file mode 100644 index 7e2672dc..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/x509/AttributeCertificateIssuer.java +++ /dev/null @@ -1,212 +0,0 @@ -package org.bouncycastle.x509; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.x509.AttCertIssuer; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.asn1.x509.V2Form; -import org.bouncycastle.jce.PrincipalUtil; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.util.Selector; - -import java.io.IOException; -import java.security.Principal; -import java.security.cert.CertSelector; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -/** - * Carrying class for an attribute certificate issuer. - */ -public class AttributeCertificateIssuer - implements CertSelector, Selector -{ - final ASN1Encodable form; - - /** - * @param issuer - */ - AttributeCertificateIssuer( - AttCertIssuer issuer) - { - form = issuer.getIssuer(); - } - - public AttributeCertificateIssuer( - X509Principal principal) - { - form = new V2Form(new GeneralNames(new GeneralName(principal))); - } - - private Object[] getNames() - { - GeneralNames name; - - if (form instanceof V2Form) - { - name = ((V2Form)form).getIssuerName(); - } - else - { - name = (GeneralNames)form; - } - - GeneralName[] names = name.getNames(); - - List l = new ArrayList(names.length); - - for (int i = 0; i != names.length; i++) - { - if (names[i].getTagNo() == GeneralName.directoryName) - { - try - { - l.add(new X509Principal(((ASN1Encodable)names[i].getName()).toASN1Primitive().getEncoded())); - } - catch (IOException e) - { - throw new RuntimeException("badly formed Name object"); - } - } - } - - return l.toArray(new Object[l.size()]); - } - - /** - * Return any principal objects inside the attribute certificate issuer object. - * - * @return an array of Principal objects (usually X509Principal) - */ - public Principal[] getPrincipals() - { - Object[] p = this.getNames(); - List l = new ArrayList(); - - for (int i = 0; i != p.length; i++) - { - if (p[i] instanceof Principal) - { - l.add(p[i]); - } - } - - return (Principal[])l.toArray(new Principal[l.size()]); - } - - private boolean matchesDN(X509Principal subject, GeneralNames targets) - { - GeneralName[] names = targets.getNames(); - - for (int i = 0; i != names.length; i++) - { - GeneralName gn = names[i]; - - if (gn.getTagNo() == GeneralName.directoryName) - { - try - { - if (new X509Principal(((ASN1Encodable)gn.getName()).toASN1Primitive().getEncoded()).equals(subject)) - { - return true; - } - } - catch (IOException e) - { - } - } - } - - return false; - } - - /* (non-Javadoc) - * @see java.security.cert.CertSelector#clone() - */ - public Object clone() - { - return new AttributeCertificateIssuer(AttCertIssuer.getInstance(form)); - } - - /* (non-Javadoc) - * @see java.security.cert.CertSelector#match(java.security.cert.Certificate) - */ - public boolean match(Certificate cert) - { - if (!(cert instanceof X509Certificate)) - { - return false; - } - - X509Certificate x509Cert = (X509Certificate)cert; - - try - { - if (form instanceof V2Form) - { - V2Form issuer = (V2Form)form; - if (issuer.getBaseCertificateID() != null) - { - return issuer.getBaseCertificateID().getSerial().getValue().equals(x509Cert.getSerialNumber()) - && matchesDN(PrincipalUtil.getIssuerX509Principal(x509Cert), issuer.getBaseCertificateID().getIssuer()); - } - - GeneralNames name = issuer.getIssuerName(); - if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), name)) - { - return true; - } - } - else - { - GeneralNames name = (GeneralNames)form; - if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), name)) - { - return true; - } - } - } - catch (CertificateEncodingException e) - { - return false; - } - - return false; - } - - public boolean equals(Object obj) - { - if (obj == this) - { - return true; - } - - if (!(obj instanceof AttributeCertificateIssuer)) - { - return false; - } - - AttributeCertificateIssuer other = (AttributeCertificateIssuer)obj; - - return this.form.equals(other.form); - } - - public int hashCode() - { - return this.form.hashCode(); - } - - public boolean match(Object obj) - { - if (!(obj instanceof X509Certificate)) - { - return false; - } - - return match((Certificate)obj); - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509AttributeCertStoreSelector.java b/prov/src/main/jdk1.1/org/bouncycastle/x509/X509AttributeCertStoreSelector.java deleted file mode 100644 index 6ff41cbd..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509AttributeCertStoreSelector.java +++ /dev/null @@ -1,488 +0,0 @@ -package org.bouncycastle.x509; - -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Object; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.Target; -import org.bouncycastle.asn1.x509.TargetInformation; -import org.bouncycastle.asn1.x509.Targets; -import org.bouncycastle.asn1.x509.X509Extensions; -import org.bouncycastle.util.Selector; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509CertSelector; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -/** - * This class is an <code>Selector</code> like implementation to select - * attribute certificates from a given set of criteria. - * - * @see org.bouncycastle.x509.X509AttributeCertificate - * @see org.bouncycastle.x509.X509Store - */ -public class X509AttributeCertStoreSelector - implements Selector -{ - - // TODO: name constraints??? - - private AttributeCertificateHolder holder; - - private AttributeCertificateIssuer issuer; - - private BigInteger serialNumber; - - private Date attributeCertificateValid; - - private X509AttributeCertificate attributeCert; - - private Collection targetNames = new HashSet(); - - private Collection targetGroups = new HashSet(); - - public X509AttributeCertStoreSelector() - { - super(); - } - - /** - * Decides if the given attribute certificate should be selected. - * - * @param obj The attribute certificate which should be checked. - * @return <code>true</code> if the attribute certificate can be selected, - * <code>false</code> otherwise. - */ - public boolean match(Object obj) - { - if (!(obj instanceof X509AttributeCertificate)) - { - return false; - } - - X509AttributeCertificate attrCert = (X509AttributeCertificate) obj; - - if (this.attributeCert != null) - { - if (!this.attributeCert.equals(attrCert)) - { - return false; - } - } - if (serialNumber != null) - { - if (!attrCert.getSerialNumber().equals(serialNumber)) - { - return false; - } - } - if (holder != null) - { - if (!attrCert.getHolder().equals(holder)) - { - return false; - } - } - if (issuer != null) - { - if (!attrCert.getIssuer().equals(issuer)) - { - return false; - } - } - - if (attributeCertificateValid != null) - { - try - { - attrCert.checkValidity(attributeCertificateValid); - } - catch (CertificateExpiredException e) - { - return false; - } - catch (CertificateNotYetValidException e) - { - return false; - } - } - if (!targetNames.isEmpty() || !targetGroups.isEmpty()) - { - - byte[] targetInfoExt = attrCert - .getExtensionValue(X509Extensions.TargetInformation.getId()); - if (targetInfoExt != null) - { - TargetInformation targetinfo; - try - { - targetinfo = TargetInformation - .getInstance(new ASN1InputStream( - ((DEROctetString) DEROctetString - .fromByteArray(targetInfoExt)).getOctets()) - .readObject()); - } - catch (IOException e) - { - return false; - } - catch (IllegalArgumentException e) - { - return false; - } - Targets[] targetss = targetinfo.getTargetsObjects(); - if (!targetNames.isEmpty()) - { - boolean found = false; - - for (int i=0; i<targetss.length; i++) - { - Targets t = targetss[i]; - Target[] targets = t.getTargets(); - for (int j=0; j<targets.length; j++) - { - if (targetNames.contains(targets[j] - .getTargetName())) - { - found = true; - break; - } - } - } - if (!found) - { - return false; - } - } - if (!targetGroups.isEmpty()) - { - boolean found = false; - - for (int i=0; i<targetss.length; i++) - { - Targets t = targetss[i]; - Target[] targets = t.getTargets(); - for (int j=0; j<targets.length; j++) - { - if (targetGroups.contains(targets[j] - .getTargetGroup())) - { - found = true; - break; - } - } - } - if (!found) - { - return false; - } - } - } - } - return true; - } - - /** - * Returns a clone of this object. - * - * @return the clone. - */ - public Object clone() - { - X509AttributeCertStoreSelector sel = new X509AttributeCertStoreSelector(); - sel.attributeCert = attributeCert; - sel.attributeCertificateValid = getAttributeCertificateValid(); - sel.holder = holder; - sel.issuer = issuer; - sel.serialNumber = serialNumber; - sel.targetGroups = getTargetGroups(); - sel.targetNames = getTargetNames(); - return sel; - } - - /** - * Returns the attribute certificate which must be matched. - * - * @return Returns the attribute certificate. - */ - public X509AttributeCertificate getAttributeCert() - { - return attributeCert; - } - - /** - * Set the attribute certificate to be matched. If <code>null</code> is - * given any will do. - * - * @param attributeCert The attribute certificate to set. - */ - public void setAttributeCert(X509AttributeCertificate attributeCert) - { - this.attributeCert = attributeCert; - } - - /** - * Get the criteria for the validity. - * - * @return Returns the attributeCertificateValid. - */ - public Date getAttributeCertificateValid() - { - if (attributeCertificateValid != null) - { - return new Date(attributeCertificateValid.getTime()); - } - - return null; - } - - /** - * Set the time, when the certificate must be valid. If <code>null</code> - * is given any will do. - * - * @param attributeCertificateValid The attribute certificate validation - * time to set. - */ - public void setAttributeCertificateValid(Date attributeCertificateValid) - { - if (attributeCertificateValid != null) - { - this.attributeCertificateValid = new Date(attributeCertificateValid - .getTime()); - } - else - { - this.attributeCertificateValid = null; - } - } - - /** - * Gets the holder. - * - * @return Returns the holder. - */ - public AttributeCertificateHolder getHolder() - { - return holder; - } - - /** - * Sets the holder. If <code>null</code> is given any will do. - * - * @param holder The holder to set. - */ - public void setHolder(AttributeCertificateHolder holder) - { - this.holder = holder; - } - - /** - * Returns the issuer criterion. - * - * @return Returns the issuer. - */ - public AttributeCertificateIssuer getIssuer() - { - return issuer; - } - - /** - * Sets the issuer the attribute certificate must have. If <code>null</code> - * is given any will do. - * - * @param issuer The issuer to set. - */ - public void setIssuer(AttributeCertificateIssuer issuer) - { - this.issuer = issuer; - } - - /** - * Gets the serial number the attribute certificate must have. - * - * @return Returns the serialNumber. - */ - public BigInteger getSerialNumber() - { - return serialNumber; - } - - /** - * Sets the serial number the attribute certificate must have. If - * <code>null</code> is given any will do. - * - * @param serialNumber The serialNumber to set. - */ - public void setSerialNumber(BigInteger serialNumber) - { - this.serialNumber = serialNumber; - } - - /** - * Adds a target name criterion for the attribute certificate to the target - * information extension criteria. The <code>X509AttributeCertificate</code> - * must contain at least one of the specified target names. - * <p> - * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param name The name as a GeneralName (not <code>null</code>) - */ - public void addTargetName(GeneralName name) - { - targetNames.add(name); - } - - /** - * Adds a target name criterion for the attribute certificate to the target - * information extension criteria. The <code>X509AttributeCertificate</code> - * must contain at least one of the specified target names. - * <p> - * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param name a byte array containing the name in ASN.1 DER encoded form of a GeneralName - * @throws IOException if a parsing error occurs. - */ - public void addTargetName(byte[] name) throws IOException - { - addTargetName(GeneralName.getInstance(ASN1Primitive.fromByteArray(name))); - } - - /** - * Adds a collection with target names criteria. If <code>null</code> is - * given any will do. - * <p> - * The collection consists of either GeneralName objects or byte[] arrays representing - * DER encoded GeneralName structures. - * - * @param names A collection of target names. - * @throws IOException if a parsing error occurs. - * @see #addTargetName(byte[]) - * @see #addTargetName(GeneralName) - */ - public void setTargetNames(Collection names) throws IOException - { - targetNames = extractGeneralNames(names); - } - - /** - * Gets the target names. The collection consists of <code>List</code>s - * made up of an <code>Integer</code> in the first entry and a DER encoded - * byte array or a <code>String</code> in the second entry. - * <p> - * The returned collection is immutable. - * - * @return The collection of target names - * @see #setTargetNames(Collection) - */ - public Collection getTargetNames() - { - return Collections.unmodifiableCollection(targetNames); - } - - /** - * Adds a target group criterion for the attribute certificate to the target - * information extension criteria. The <code>X509AttributeCertificate</code> - * must contain at least one of the specified target groups. - * <p> - * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param group The group as GeneralName form (not <code>null</code>) - */ - public void addTargetGroup(GeneralName group) - { - targetGroups.add(group); - } - - /** - * Adds a target group criterion for the attribute certificate to the target - * information extension criteria. The <code>X509AttributeCertificate</code> - * must contain at least one of the specified target groups. - * <p> - * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param name a byte array containing the group in ASN.1 DER encoded form of a GeneralName - * @throws IOException if a parsing error occurs. - */ - public void addTargetGroup(byte[] name) throws IOException - { - addTargetGroup(GeneralName.getInstance(ASN1Primitive.fromByteArray(name))); - } - - /** - * Adds a collection with target groups criteria. If <code>null</code> is - * given any will do. - * <p> - * The collection consists of <code>GeneralName</code> objects or <code>byte[]</code representing DER - * encoded GeneralNames. - * - * @param names A collection of target groups. - * @throws IOException if a parsing error occurs. - * @see #addTargetGroup(byte[]) - * @see #addTargetGroup(GeneralName) - */ - public void setTargetGroups(Collection names) throws IOException - { - targetGroups = extractGeneralNames(names); - } - - - - /** - * Gets the target groups. The collection consists of <code>List</code>s - * made up of an <code>Integer</code> in the first entry and a DER encoded - * byte array or a <code>String</code> in the second entry. - * <p> - * The returned collection is immutable. - * - * @return The collection of target groups. - * @see #setTargetGroups(Collection) - */ - public Collection getTargetGroups() - { - return Collections.unmodifiableCollection(targetGroups); - } - - private Set extractGeneralNames(Collection names) - throws IOException - { - if (names == null || names.isEmpty()) - { - return new HashSet(); - } - Set temp = new HashSet(); - for (Iterator it = names.iterator(); it.hasNext();) - { - Object o = it.next(); - if (o instanceof GeneralName) - { - temp.add(o); - } - else - { - temp.add(GeneralName.getInstance(ASN1Primitive.fromByteArray((byte[])o))); - } - } - return temp; - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509CRLStoreSelector.java b/prov/src/main/jdk1.1/org/bouncycastle/x509/X509CRLStoreSelector.java deleted file mode 100644 index 4f0849f0..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509CRLStoreSelector.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bouncycastle.x509; - -import org.bouncycastle.util.Selector; - -import java.security.cert.X509CRLSelector; -import java.security.cert.CRL; - -public class X509CRLStoreSelector - extends X509CRLSelector - implements Selector -{ - public boolean match(Object obj) - { - if (!(obj instanceof CRL)) - { - return false; - } - - return super.match((CRL)obj); - } - - public boolean match(CRL obj) - { - return this.match((Object)obj); - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509CertStoreSelector.java b/prov/src/main/jdk1.1/org/bouncycastle/x509/X509CertStoreSelector.java deleted file mode 100644 index dbb4c556..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509CertStoreSelector.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.bouncycastle.x509; - -import org.bouncycastle.util.Selector; - -import java.security.cert.X509CertSelector; -import java.security.cert.Certificate; - -public class X509CertStoreSelector - extends X509CertSelector - implements Selector -{ - public boolean match(Object obj) - { - if (!(obj instanceof Certificate)) - { - return false; - } - - return super.match((Certificate)obj); - } - - public boolean match(Certificate obj) - { - return this.match((Object)obj); - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509Util.java b/prov/src/main/jdk1.1/org/bouncycastle/x509/X509Util.java deleted file mode 100644 index 21dbcad7..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509Util.java +++ /dev/null @@ -1,397 +0,0 @@ -package org.bouncycastle.x509; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.Security; -import java.security.Signature; -import java.security.SignatureException; -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; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1Integer; -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.oiw.OIWObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.RSASSAPSSparams; -import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.util.Strings; - -class X509Util -{ - private static Hashtable algorithms = new Hashtable(); - private static Hashtable params = 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("SHA1WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - 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("SHA384WITHDSA", NISTObjectIdentifiers.dsa_with_sha384); - algorithms.put("SHA512WITHDSA", NISTObjectIdentifiers.dsa_with_sha512); - 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); - algorithms.put("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - algorithms.put("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - algorithms.put("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - - // - // 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); - noParams.add(NISTObjectIdentifiers.dsa_with_sha384); - noParams.add(NISTObjectIdentifiers.dsa_with_sha512); - - // - // RFC 4491 - // - noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - - // - // explicit params - // - AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, new DERNull()); - params.put("SHA1WITHRSAANDMGF1", creatPSSParams(sha1AlgId, 20)); - - AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, new DERNull()); - params.put("SHA224WITHRSAANDMGF1", creatPSSParams(sha224AlgId, 28)); - - AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, new DERNull()); - params.put("SHA256WITHRSAANDMGF1", creatPSSParams(sha256AlgId, 32)); - - AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, new DERNull()); - params.put("SHA384WITHRSAANDMGF1", creatPSSParams(sha384AlgId, 48)); - - AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, new DERNull()); - params.put("SHA512WITHRSAANDMGF1", creatPSSParams(sha512AlgId, 64)); - } - - private static RSASSAPSSparams creatPSSParams(AlgorithmIdentifier hashAlgId, int saltSize) - { - return new RSASSAPSSparams( - hashAlgId, - new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, hashAlgId), - new ASN1Integer(saltSize), - new ASN1Integer(1)); - } - - static ASN1ObjectIdentifier getAlgorithmOID( - String algorithmName) - { - algorithmName = Strings.toUpperCase(algorithmName); - - if (algorithms.containsKey(algorithmName)) - { - return (ASN1ObjectIdentifier)algorithms.get(algorithmName); - } - - return new ASN1ObjectIdentifier(algorithmName); - } - - static AlgorithmIdentifier getSigAlgID( - ASN1ObjectIdentifier sigOid, - String algorithmName) - { - if (noParams.contains(sigOid)) - { - return new AlgorithmIdentifier(sigOid); - } - - algorithmName = Strings.toUpperCase(algorithmName); - - if (params.containsKey(algorithmName)) - { - return new AlgorithmIdentifier(sigOid, (ASN1Encodable)params.get(algorithmName)); - } - 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 Signature getSignatureInstance( - String algorithm) - throws NoSuchAlgorithmException - { - return Signature.getInstance(algorithm); - } - - static Signature getSignatureInstance( - String algorithm, - String provider) - throws NoSuchProviderException, NoSuchAlgorithmException - { - if (provider != null) - { - return Signature.getInstance(algorithm, provider); - } - else - { - return Signature.getInstance(algorithm); - } - } - - static byte[] calculateSignature( - ASN1ObjectIdentifier sigOid, - String sigName, - PrivateKey key, - SecureRandom random, - ASN1Encodable object) - throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException - { - Signature sig; - - if (sigOid == null) - { - throw new IllegalStateException("no signature algorithm specified"); - } - - sig = X509Util.getSignatureInstance(sigName); - - if (random != null) - { - sig.initSign(key); - } - else - { - sig.initSign(key); - } - - sig.update(object.toASN1Primitive().getEncoded(ASN1Encoding.DER)); - - return sig.sign(); - } - - static byte[] calculateSignature( - ASN1ObjectIdentifier sigOid, - String sigName, - String provider, - PrivateKey key, - SecureRandom random, - ASN1Encodable object) - throws IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException - { - Signature sig; - - if (sigOid == null) - { - throw new IllegalStateException("no signature algorithm specified"); - } - - sig = X509Util.getSignatureInstance(sigName, provider); - - if (random != null) - { - sig.initSign(key); - } - else - { - sig.initSign(key); - } - - sig.update(object.toASN1Primitive().getEncoded(ASN1Encoding.DER)); - - return sig.sign(); - } - - static class Implementation - { - Object engine; - Provider provider; - - Implementation( - Object engine, - Provider provider) - { - this.engine = engine; - this.provider = provider; - } - - Object getEngine() - { - return engine; - } - - Provider getProvider() - { - return provider; - } - } - - /** - * see if we can find an algorithm (or its alias and what it represents) in - * the property table for the given provider. - */ - static Implementation getImplementation( - String baseName, - String algorithm, - Provider prov) - throws NoSuchAlgorithmException - { - algorithm = Strings.toUpperCase(algorithm); - - String alias; - - while ((alias = prov.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) - { - algorithm = alias; - } - - String className = prov.getProperty(baseName + "." + algorithm); - - if (className != null) - { - try - { - Class cls; - ClassLoader clsLoader = prov.getClass().getClassLoader(); - - if (clsLoader != null) - { - cls = clsLoader.loadClass(className); - } - else - { - cls = Class.forName(className); - } - - return new Implementation(cls.newInstance(), prov); - } - catch (ClassNotFoundException e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but no class \"" + className + "\" found!"); - } - catch (Exception e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but class \"" + className + "\" inaccessible!"); - } - } - - throw new NoSuchAlgorithmException("cannot find implementation " + algorithm + " for provider " + prov.getName()); - } - - /** - * return an implementation for a given algorithm/provider. - * If the provider is null, we grab the first avalaible who has the required algorithm. - */ - static Implementation getImplementation( - String baseName, - String algorithm) - throws NoSuchAlgorithmException - { - Provider[] prov = Security.getProviders(); - - // - // search every provider looking for the algorithm we want. - // - for (int i = 0; i != prov.length; i++) - { - // - // try case insensitive - // - Implementation imp = getImplementation(baseName, Strings.toUpperCase(algorithm), prov[i]); - if (imp != null) - { - return imp; - } - - try - { - imp = getImplementation(baseName, algorithm, prov[i]); - } - catch (NoSuchAlgorithmException e) - { - // continue - } - } - - throw new NoSuchAlgorithmException("cannot find implementation " + algorithm); - } - - static Provider getProvider(String provider) - throws NoSuchProviderException - { - Provider prov = Security.getProvider(provider); - - if (prov == null) - { - throw new NoSuchProviderException("Provider " + provider + " not found"); - } - - return prov; - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V1CertificateGenerator.java b/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V1CertificateGenerator.java deleted file mode 100644 index 20f24bb9..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V1CertificateGenerator.java +++ /dev/null @@ -1,345 +0,0 @@ -package org.bouncycastle.x509; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.Iterator; - -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.asn1.x509.TBSCertificate; -import org.bouncycastle.asn1.x509.Time; -import org.bouncycastle.asn1.x509.V1TBSCertificateGenerator; -import org.bouncycastle.asn1.x509.Certificate; -import org.bouncycastle.asn1.x509.X509Name; -import org.bouncycastle.jce.provider.X509CertificateObject; - -/** - * class to produce an X.509 Version 1 certificate. - * @deprecated use org.bouncycastle.cert.X509v1CertificateBuilder. - */ -public class X509V1CertificateGenerator -{ - private V1TBSCertificateGenerator tbsGen; - private ASN1ObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private String signatureAlgorithm; - - public X509V1CertificateGenerator() - { - tbsGen = new V1TBSCertificateGenerator(); - } - - /** - * reset the generator - */ - public void reset() - { - tbsGen = new V1TBSCertificateGenerator(); - } - - /** - * set the serial number for the certificate. - */ - public void setSerialNumber( - BigInteger serialNumber) - { - if (serialNumber.compareTo(BigInteger.valueOf(0)) <= 0) - { - throw new IllegalArgumentException("serial number must be a positive integer"); - } - - tbsGen.setSerialNumber(new ASN1Integer(serialNumber)); - } - - /** - * Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the - * certificate. - */ - public void setIssuerDN( - X509Name issuer) - { - tbsGen.setIssuer(issuer); - } - - public void setNotBefore( - Date date) - { - tbsGen.setStartDate(new Time(date)); - } - - public void setNotAfter( - Date date) - { - tbsGen.setEndDate(new Time(date)); - } - - /** - * Set the subject distinguished name. The subject describes the entity associated with the public key. - */ - public void setSubjectDN( - X509Name subject) - { - tbsGen.setSubject(subject); - } - - public void setPublicKey( - PublicKey key) - { - try - { - tbsGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream( - new ByteArrayInputStream(key.getEncoded())).readObject())); - } - catch (Exception e) - { - throw new IllegalArgumentException("unable to process key - " + e.toString()); - } - } - - /** - * Set the signature algorithm. This can be either a name or an OID, names - * are treated as case insensitive. - * - * @param signatureAlgorithm string representation of the algorithm name. - */ - public void setSignatureAlgorithm( - String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - - try - { - sigOID = X509Util.getAlgorithmOID(signatureAlgorithm); - } - catch (Exception e) - { - throw new IllegalArgumentException("Unknown signature type requested"); - } - - sigAlgId = X509Util.getSigAlgID(sigOID, signatureAlgorithm); - - tbsGen.setSignature(sigAlgId); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "BC". - * @deprecated use generate(key, "BC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "BC", null); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "BC" and the passed in source of randomness - * @deprecated use generate(key, random, "BC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - SecureRandom random) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "BC", random); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - return generateX509Certificate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider, - SecureRandom random) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - try - { - return generate(key, provider, random); - } - catch (NoSuchProviderException e) - { - throw e; - } - catch (SignatureException e) - { - throw e; - } - catch (InvalidKeyException e) - { - throw e; - } - catch (NoSuchAlgorithmException e) - { - throw new SecurityException("exception: " + e); - } - catch (GeneralSecurityException e) - { - throw new SecurityException("exception: " + e); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider. - * <p> - * <b>Note:</b> this differs from the deprecated method in that the default provider is - * used - not "BC". - * </p> - */ - public X509Certificate generate( - PrivateKey key) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, (SecureRandom)null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider and the passed in source of randomness - * <p> - * <b>Note:</b> this differs from the deprecated method in that the default provider is - * used - not "BC". - * </p> - */ - public X509Certificate generate( - PrivateKey key, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = tbsGen.generateTBSCertificate(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - return generateJcaObject(tbsCert, signature); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - */ - public X509Certificate generate( - PrivateKey key, - String provider) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - */ - public X509Certificate generate( - PrivateKey key, - String provider, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = tbsGen.generateTBSCertificate(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - return generateJcaObject(tbsCert, signature); - } - - private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature) - throws CertificateEncodingException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(tbsCert); - v.add(sigAlgId); - v.add(new DERBitString(signature)); - - try - { - return new X509CertificateObject(Certificate.getInstance((new DERSequence(v)))); - } - catch (CertificateParsingException e) - { - throw new ExtCertificateEncodingException("exception producing certificate object", e); - } - } - - /** - * Return an iterator of the signature names supported by the generator. - * - * @return an iterator containing recognised names. - */ - public Iterator getSignatureAlgNames() - { - return X509Util.getAlgNames(); - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V2AttributeCertificateGenerator.java b/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V2AttributeCertificateGenerator.java deleted file mode 100644 index 7e2a3f8f..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V2AttributeCertificateGenerator.java +++ /dev/null @@ -1,281 +0,0 @@ -package org.bouncycastle.x509; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; -import java.util.Date; -import java.util.Hashtable; -import java.util.Vector; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.ASN1GeneralizedTime; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DEROutputStream; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.AttCertIssuer; -import org.bouncycastle.asn1.x509.Attribute; -import org.bouncycastle.asn1.x509.AttributeCertificate; -import org.bouncycastle.asn1.x509.V2AttributeCertificateInfoGenerator; -import org.bouncycastle.asn1.x509.AttributeCertificateInfo; -import org.bouncycastle.asn1.x509.X509Extension; -import org.bouncycastle.asn1.x509.X509Extensions; -import org.bouncycastle.util.Strings; - -/** - * class to produce an X.509 Version 2 AttributeCertificate. - */ -public class X509V2AttributeCertificateGenerator -{ - private V2AttributeCertificateInfoGenerator acInfoGen; - private ASN1ObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private String signatureAlgorithm; - private Hashtable extensions = null; - private Vector extOrdering = null; - private static Hashtable algorithms = new Hashtable(); - - static - { - algorithms.put("MD2WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.2")); - algorithms.put("MD2WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.2")); - algorithms.put("MD5WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.4")); - algorithms.put("MD5WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.4")); - algorithms.put("SHA1WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.5")); - algorithms.put("SHA1WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.5")); - algorithms.put("RIPEMD160WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.3.36.3.3.1.2")); - algorithms.put("RIPEMD160WITHRSA", new ASN1ObjectIdentifier("1.3.36.3.3.1.2")); - algorithms.put("SHA1WITHDSA", new ASN1ObjectIdentifier("1.2.840.10040.4.3")); - algorithms.put("DSAWITHSHA1", new ASN1ObjectIdentifier("1.2.840.10040.4.3")); - algorithms.put("SHA1WITHECDSA", new ASN1ObjectIdentifier("1.2.840.10045.4.1")); - algorithms.put("ECDSAWITHSHA1", new ASN1ObjectIdentifier("1.2.840.10045.4.1")); - } - - public X509V2AttributeCertificateGenerator() - { - acInfoGen = new V2AttributeCertificateInfoGenerator(); - } - - /** - * reset the generator - */ - public void reset() - { - acInfoGen = new V2AttributeCertificateInfoGenerator(); - extensions = null; - extOrdering = null; - } - - /** - * Set the Holder of this Attribute Certificate - */ - public void setHolder( - AttributeCertificateHolder holder) - { - acInfoGen.setHolder(holder.holder); - } - - /** - * Set the issuer - */ - public void setIssuer( - AttributeCertificateIssuer issuer) - { - acInfoGen.setIssuer(AttCertIssuer.getInstance(issuer.form)); - } - - /** - * Set the Signature inside the AttributeCertificateInfo - */ - public void setSignature( - AlgorithmIdentifier sig) - { - acInfoGen.setSignature(sig); - } - - /** - * set the serial number for the certificate. - */ - public void setSerialNumber( - BigInteger serialNumber) - { - acInfoGen.setSerialNumber(new ASN1Integer(serialNumber)); - } - - public void setNotBefore( - Date date) - { - acInfoGen.setStartDate(new ASN1GeneralizedTime(date)); - } - - public void setNotAfter( - Date date) - { - acInfoGen.setEndDate(new ASN1GeneralizedTime(date)); - } - - public void setSignatureAlgorithm( - String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - - sigOID = (ASN1ObjectIdentifier)algorithms.get(Strings.toUpperCase(signatureAlgorithm)); - - if (sigOID == null) - { - throw new IllegalArgumentException("Unknown signature type requested"); - } - - sigAlgId = new AlgorithmIdentifier(this.sigOID, new DERNull()); - - acInfoGen.setSignature(sigAlgId); - } - - /** - * add an attribute - */ - public void addAttribute( - X509Attribute attribute) - { - acInfoGen.addAttribute(Attribute.getInstance(attribute.toASN1Object())); - } - - public void setIssuerUniqueId( - boolean[] iui) - { - // [TODO] convert boolean array to bit string - //acInfoGen.setIssuerUniqueID(iui); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * @throws IOException - */ - public void addExtension( - String OID, - boolean critical, - ASN1Encodable value) - throws IOException - { - this.addExtension(OID, critical, value.toASN1Primitive().getEncoded()); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * The value parameter becomes the contents of the octet string associated - * with the extension. - */ - public void addExtension( - String OID, - boolean critical, - byte[] value) - { - if (extensions == null) - { - extensions = new Hashtable(); - extOrdering = new Vector(); - } - - ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(OID); - - extensions.put(oid, new X509Extension(critical, new DEROctetString(value))); - extOrdering.addElement(oid); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing. - */ - public X509AttributeCertificate generateCertificate( - PrivateKey key, - String provider) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - return generateCertificate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing and the supplied source - * of randomness, if required. - */ - public X509AttributeCertificate generateCertificate( - PrivateKey key, - String provider, - SecureRandom random) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - Signature sig = null; - - if (sigOID == null) - { - throw new IllegalStateException("no signature algorithm specified"); - } - - try - { - sig = Signature.getInstance(sigOID.getId(), provider); - } - catch (NoSuchAlgorithmException ex) - { - try - { - sig = Signature.getInstance(signatureAlgorithm, provider); - } - catch (NoSuchAlgorithmException e) - { - throw new SecurityException("exception creating signature: " + e.toString()); - } - } - - sig.initSign(key); - - if (extensions != null) - { - acInfoGen.setExtensions(new X509Extensions(extOrdering, extensions)); - } - - AttributeCertificateInfo acInfo = acInfoGen.generateAttributeCertificateInfo(); - - try - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - - dOut.writeObject(acInfo); - - sig.update(bOut.toByteArray()); - } - catch (Exception e) - { - throw new SecurityException("exception encoding Attribute cert - " + e); - } - - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(acInfo); - v.add(sigAlgId); - v.add(new DERBitString(sig.sign())); - - try - { - return new X509V2AttributeCertificate(new AttributeCertificate(new DERSequence(v))); - } - catch (IOException e) - { - throw new RuntimeException("constructed invalid certificate!"); - } - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V2CRLGenerator.java b/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V2CRLGenerator.java deleted file mode 100644 index cac67093..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V2CRLGenerator.java +++ /dev/null @@ -1,434 +0,0 @@ -package org.bouncycastle.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.cert.CRLException; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import java.util.Date; -import java.util.Iterator; -import java.util.Set; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.ASN1GeneralizedTime; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.CertificateList; -import org.bouncycastle.asn1.x509.TBSCertList; -import org.bouncycastle.asn1.x509.Time; -import org.bouncycastle.asn1.x509.V2TBSCertListGenerator; -import org.bouncycastle.asn1.x509.X509Extensions; -import org.bouncycastle.asn1.x509.Extensions; -import org.bouncycastle.asn1.x509.X509ExtensionsGenerator; -import org.bouncycastle.asn1.x509.X509Name; -import org.bouncycastle.jce.provider.X509CRLObject; - -/** - * class to produce an X.509 Version 2 CRL. - * @deprecated use org.bouncycastle.cert.X509v2CRLBuilder. - */ -public class X509V2CRLGenerator -{ - private V2TBSCertListGenerator tbsGen; - private ASN1ObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private String signatureAlgorithm; - private X509ExtensionsGenerator extGenerator; - - public X509V2CRLGenerator() - { - tbsGen = new V2TBSCertListGenerator(); - extGenerator = new X509ExtensionsGenerator(); - } - - /** - * reset the generator - */ - public void reset() - { - tbsGen = new V2TBSCertListGenerator(); - extGenerator.reset(); - } - - /** - * Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the - * certificate. - */ - public void setIssuerDN( - X509Name issuer) - { - tbsGen.setIssuer(issuer); - } - - public void setThisUpdate( - Date date) - { - tbsGen.setThisUpdate(new Time(date)); - } - - public void setNextUpdate( - Date date) - { - tbsGen.setNextUpdate(new Time(date)); - } - - /** - * Reason being as indicated by CRLReason, i.e. CRLReason.keyCompromise - * or 0 if CRLReason is not to be used - **/ - public void addCRLEntry(BigInteger userCertificate, Date revocationDate, int reason) - { - tbsGen.addCRLEntry(new ASN1Integer(userCertificate), new Time(revocationDate), reason); - } - - /** - * Add a CRL entry with an Invalidity Date extension as well as a CRLReason extension. - * Reason being as indicated by CRLReason, i.e. CRLReason.keyCompromise - * or 0 if CRLReason is not to be used - **/ - public void addCRLEntry(BigInteger userCertificate, Date revocationDate, int reason, Date invalidityDate) - { - tbsGen.addCRLEntry(new ASN1Integer(userCertificate), new Time(revocationDate), reason, new ASN1GeneralizedTime(invalidityDate)); - } - - /** - * Add a CRL entry with extensions. - **/ - public void addCRLEntry(BigInteger userCertificate, Date revocationDate, X509Extensions extensions) - { - tbsGen.addCRLEntry(new ASN1Integer(userCertificate), new Time(revocationDate), Extensions.getInstance(extensions)); - } - - /** - * Add the CRLEntry objects contained in a previous CRL. - * - * @param other the X509CRL to source the other entries from. - */ - public void addCRL(X509CRL other) - throws CRLException - { - Set revocations = other.getRevokedCertificates(); - - if (revocations != null) - { - Iterator it = revocations.iterator(); - while (it.hasNext()) - { - X509CRLEntry entry = (X509CRLEntry)it.next(); - - ASN1InputStream aIn = new ASN1InputStream(entry.getEncoded()); - - try - { - tbsGen.addCRLEntry(ASN1Sequence.getInstance(aIn.readObject())); - } - catch (IOException e) - { - throw new CRLException("exception processing encoding of CRL: " + e.toString()); - } - } - } - } - - /** - * Set the signature algorithm. This can be either a name or an OID, names - * are treated as case insensitive. - * - * @param signatureAlgorithm string representation of the algorithm name. - */ - public void setSignatureAlgorithm( - String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - - try - { - sigOID = X509Util.getAlgorithmOID(signatureAlgorithm); - } - catch (Exception e) - { - throw new IllegalArgumentException("Unknown signature type requested"); - } - - sigAlgId = X509Util.getSigAlgID(sigOID, signatureAlgorithm); - - tbsGen.setSignature(sigAlgId); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - String oid, - boolean critical, - ASN1Encodable value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - ASN1Encodable value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - String oid, - boolean critical, - byte[] value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - byte[] value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider "BC". - * @deprecated use generate(key, "BC") - */ - public X509CRL generateX509CRL( - PrivateKey key) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509CRL(key, "BC", null); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider "BC" and an user defined SecureRandom object as - * source of randomness. - * @deprecated use generate(key, random, "BC") - */ - public X509CRL generateX509CRL( - PrivateKey key, - SecureRandom random) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509CRL(key, "BC", random); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the passed in provider for the signing. - * @deprecated use generate() - */ - public X509CRL generateX509CRL( - PrivateKey key, - String provider) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - return generateX509CRL(key, provider, null); - } - - /** - * generate an X509 CRL, based on the current issuer and subject, - * using the passed in provider for the signing. - * @deprecated use generate() - */ - public X509CRL generateX509CRL( - PrivateKey key, - String provider, - SecureRandom random) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - try - { - return generate(key, provider, random); - } - catch (NoSuchProviderException e) - { - throw e; - } - catch (SignatureException e) - { - throw e; - } - catch (InvalidKeyException e) - { - throw e; - } - catch (NoSuchAlgorithmException e) - { - throw new SecurityException("exception: " + e); - } - catch (GeneralSecurityException e) - { - throw new SecurityException("exception: " + e); - } - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider. - * <p> - * <b>Note:</b> this differs from the deprecated method in that the default provider is - * used - not "BC". - * </p> - */ - public X509CRL generate( - PrivateKey key) - throws CRLException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, (SecureRandom)null); - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider and an user defined SecureRandom object as - * source of randomness. - * <p> - * <b>Note:</b> this differs from the deprecated method in that the default provider is - * used - not "BC". - * </p> - */ - public X509CRL generate( - PrivateKey key, - SecureRandom random) - throws CRLException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertList tbsCrl = generateCertList(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCrl); - } - catch (IOException e) - { - throw new ExtCRLException("cannot generate CRL encoding", e); - } - - return generateJcaObject(tbsCrl, signature); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the passed in provider for the signing. - */ - public X509CRL generate( - PrivateKey key, - String provider) - throws CRLException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, provider, null); - } - - /** - * generate an X509 CRL, based on the current issuer and subject, - * using the passed in provider for the signing. - */ - public X509CRL generate( - PrivateKey key, - String provider, - SecureRandom random) - throws CRLException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertList tbsCrl = generateCertList(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCrl); - } - catch (IOException e) - { - throw new ExtCRLException("cannot generate CRL encoding", e); - } - - return generateJcaObject(tbsCrl, signature); - } - - private TBSCertList generateCertList() - { - if (!extGenerator.isEmpty()) - { - tbsGen.setExtensions(extGenerator.generate()); - } - - return tbsGen.generateTBSCertList(); - } - - private X509CRL generateJcaObject(TBSCertList tbsCrl, byte[] signature) - throws CRLException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(tbsCrl); - v.add(sigAlgId); - v.add(new DERBitString(signature)); - - return new X509CRLObject(new CertificateList(new DERSequence(v))); - } - - /** - * Return an iterator of the signature names supported by the generator. - * - * @return an iterator containing recognised names. - */ - public Iterator getSignatureAlgNames() - { - return X509Util.getAlgNames(); - } - - private static class ExtCRLException - extends CRLException - { - Throwable cause; - - ExtCRLException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } - } -} diff --git a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V3CertificateGenerator.java b/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V3CertificateGenerator.java deleted file mode 100644 index 60135972..00000000 --- a/prov/src/main/jdk1.1/org/bouncycastle/x509/X509V3CertificateGenerator.java +++ /dev/null @@ -1,495 +0,0 @@ -package org.bouncycastle.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.Iterator; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.asn1.x509.TBSCertificate; -import org.bouncycastle.asn1.x509.Time; -import org.bouncycastle.asn1.x509.V3TBSCertificateGenerator; -import org.bouncycastle.asn1.x509.Certificate; -import org.bouncycastle.asn1.x509.X509ExtensionsGenerator; -import org.bouncycastle.asn1.x509.X509Name; -import org.bouncycastle.jce.provider.X509CertificateObject; -import org.bouncycastle.x509.extension.X509ExtensionUtil; - -/** - * class to produce an X.509 Version 3 certificate. - * @deprecated use org.bouncycastle.cert.X509v3CertificateBuilder. - */ -public class X509V3CertificateGenerator -{ - private V3TBSCertificateGenerator tbsGen; - private ASN1ObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private String signatureAlgorithm; - private X509ExtensionsGenerator extGenerator; - - public X509V3CertificateGenerator() - { - tbsGen = new V3TBSCertificateGenerator(); - extGenerator = new X509ExtensionsGenerator(); - } - - /** - * reset the generator - */ - public void reset() - { - tbsGen = new V3TBSCertificateGenerator(); - extGenerator.reset(); - } - - /** - * set the serial number for the certificate. - */ - public void setSerialNumber( - BigInteger serialNumber) - { - if (serialNumber.compareTo(BigInteger.valueOf(0)) <= 0) - { - throw new IllegalArgumentException("serial number must be a positive integer"); - } - - tbsGen.setSerialNumber(new ASN1Integer(serialNumber)); - } - - /** - * Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the - * certificate. - */ - public void setIssuerDN( - X509Name issuer) - { - tbsGen.setIssuer(issuer); - } - - public void setNotBefore( - Date date) - { - tbsGen.setStartDate(new Time(date)); - } - - public void setNotAfter( - Date date) - { - tbsGen.setEndDate(new Time(date)); - } - - /** - * Set the subject distinguished name. The subject describes the entity associated with the public key. - */ - public void setSubjectDN( - X509Name subject) - { - tbsGen.setSubject(subject); - } - - public void setPublicKey( - PublicKey key) - throws IllegalArgumentException - { - try - { - tbsGen.setSubjectPublicKeyInfo( - SubjectPublicKeyInfo.getInstance(new ASN1InputStream(key.getEncoded()).readObject())); - } - catch (Exception e) - { - throw new IllegalArgumentException("unable to process key - " + e.toString()); - } - } - - /** - * Set the signature algorithm. This can be either a name or an OID, names - * are treated as case insensitive. - * - * @param signatureAlgorithm string representation of the algorithm name. - */ - public void setSignatureAlgorithm( - String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - - try - { - sigOID = X509Util.getAlgorithmOID(signatureAlgorithm); - } - catch (Exception e) - { - throw new IllegalArgumentException("Unknown signature type requested: " + signatureAlgorithm); - } - - sigAlgId = X509Util.getSigAlgID(sigOID, signatureAlgorithm); - - tbsGen.setSignature(sigAlgId); - } - - /** - * Set the subject unique ID - note: it is very rare that it is correct to do this. - */ - public void setSubjectUniqueID(boolean[] uniqueID) - { - tbsGen.setSubjectUniqueID(booleanToBitString(uniqueID)); - } - - /** - * Set the issuer unique ID - note: it is very rare that it is correct to do this. - */ - public void setIssuerUniqueID(boolean[] uniqueID) - { - tbsGen.setIssuerUniqueID(booleanToBitString(uniqueID)); - } - - private DERBitString booleanToBitString(boolean[] id) - { - byte[] bytes = new byte[(id.length + 7) / 8]; - - for (int i = 0; i != id.length; i++) - { - bytes[i / 8] |= (id[i]) ? (1 << ((7 - (i % 8)))) : 0; - } - - int pad = id.length % 8; - - if (pad == 0) - { - return new DERBitString(bytes); - } - else - { - return new DERBitString(bytes, 8 - pad); - } - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - */ - public void addExtension( - String oid, - boolean critical, - ASN1Encodable value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - ASN1Encodable value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * The value parameter becomes the contents of the octet string associated - * with the extension. - */ - public void addExtension( - String oid, - boolean critical, - byte[] value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - byte[] value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * copying the extension value from another certificate. - * @throws CertificateParsingException if the extension cannot be extracted. - */ - public void copyAndAddExtension( - String oid, - boolean critical, - X509Certificate cert) - throws CertificateParsingException - { - byte[] extValue = cert.getExtensionValue(oid); - - if (extValue == null) - { - throw new CertificateParsingException("extension " + oid + " not present"); - } - - try - { - ASN1Encodable value = X509ExtensionUtil.fromExtensionValue(extValue); - - this.addExtension(oid, critical, value); - } - catch (IOException e) - { - throw new CertificateParsingException(e.toString()); - } - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * copying the extension value from another certificate. - * @throws CertificateParsingException if the extension cannot be extracted. - */ - public void copyAndAddExtension( - ASN1ObjectIdentifier oid, - boolean critical, - X509Certificate cert) - throws CertificateParsingException - { - this.copyAndAddExtension(oid.getId(), critical, cert); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "BC". - * @deprecated use generate(key, "BC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "BC", null); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "BC", and the passed in source of randomness - * (if required). - * @deprecated use generate(key, random, "BC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - SecureRandom random) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "BC", random); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing. - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - return generateX509Certificate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing and the supplied source - * of randomness, if required. - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider, - SecureRandom random) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - try - { - return generate(key, provider, random); - } - catch (NoSuchProviderException e) - { - throw e; - } - catch (SignatureException e) - { - throw e; - } - catch (InvalidKeyException e) - { - throw e; - } - catch (NoSuchAlgorithmException e) - { - throw new SecurityException("exception: " + e); - } - catch (GeneralSecurityException e) - { - throw new SecurityException("exception: " + e); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider. - * <p> - * <b>Note:</b> this differs from the deprecated method in that the default provider is - * used - not "BC". - * </p> - */ - public X509Certificate generate( - PrivateKey key) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, (SecureRandom)null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider, and the passed in source of randomness - * (if required). - * <p> - * <b>Note:</b> this differs from the deprecated method in that the default provider is - * used - not "BC". - * </p> - */ - public X509Certificate generate( - PrivateKey key, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = generateTbsCert(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - try - { - return generateJcaObject(tbsCert, signature); - } - catch (CertificateParsingException e) - { - throw new ExtCertificateEncodingException("exception producing certificate object", e); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing. - */ - public X509Certificate generate( - PrivateKey key, - String provider) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing and the supplied source - * of randomness, if required. - */ - public X509Certificate generate( - PrivateKey key, - String provider, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = generateTbsCert(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - try - { - return generateJcaObject(tbsCert, signature); - } - catch (CertificateParsingException e) - { - throw new ExtCertificateEncodingException("exception producing certificate object", e); - } - } - - private TBSCertificate generateTbsCert() - { - if (!extGenerator.isEmpty()) - { - tbsGen.setExtensions(extGenerator.generate()); - } - - return tbsGen.generateTBSCertificate(); - } - - private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature) - throws CertificateParsingException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(tbsCert); - v.add(sigAlgId); - v.add(new DERBitString(signature)); - - return new X509CertificateObject(Certificate.getInstance(new DERSequence(v))); - } - - /** - * Return an iterator of the signature names supported by the generator. - * - * @return an iterator containing recognised names. - */ - public Iterator getSignatureAlgNames() - { - return X509Util.getAlgNames(); - } -} |