diff options
author | Sergio Giro <sgiro@google.com> | 2016-02-01 10:41:58 +0000 |
---|---|---|
committer | Sergio Giro <sgiro@google.com> | 2016-02-01 10:41:58 +0000 |
commit | 53b61f9fe9d58034fcc7021137e92460f91b70ce (patch) | |
tree | 90632062175928181977c1ab3ab59951bc1146c3 /bcprov/src/main/java/org/bouncycastle/jce | |
parent | 3eebc2629986481f9fc77ab101c0c9b8ff2f2660 (diff) | |
download | bouncycastle-53b61f9fe9d58034fcc7021137e92460f91b70ce.tar.gz |
bouncycastle: Android tree with upstream code for version 1.52
Android tree as of
1af9aad12fedf1d93333e19f5ed0ab86f1cc4e2a
Change-Id: I714fa0954a5d000cd88d1fb78b0b7fe28246d404
Diffstat (limited to 'bcprov/src/main/java/org/bouncycastle/jce')
73 files changed, 2071 insertions, 4316 deletions
diff --git a/bcprov/src/main/java/org/bouncycastle/jce/ECNamedCurveTable.java b/bcprov/src/main/java/org/bouncycastle/jce/ECNamedCurveTable.java index 941f4763..5ad207ac 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/ECNamedCurveTable.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/ECNamedCurveTable.java @@ -21,19 +21,35 @@ public class ECNamedCurveTable public static ECNamedCurveParameterSpec getParameterSpec( String name) { - X9ECParameters ecP = org.bouncycastle.asn1.x9.ECNamedCurveTable.getByName(name); + X9ECParameters ecP = org.bouncycastle.crypto.ec.CustomNamedCurves.getByName(name); if (ecP == null) { try { - ecP = org.bouncycastle.asn1.x9.ECNamedCurveTable.getByOID(new ASN1ObjectIdentifier(name)); + ecP = org.bouncycastle.crypto.ec.CustomNamedCurves.getByOID(new ASN1ObjectIdentifier(name)); } catch (IllegalArgumentException e) { // ignore - not an oid } + + if (ecP == null) + { + ecP = org.bouncycastle.asn1.x9.ECNamedCurveTable.getByName(name); + if (ecP == null) + { + try + { + ecP = org.bouncycastle.asn1.x9.ECNamedCurveTable.getByOID(new ASN1ObjectIdentifier(name)); + } + catch (IllegalArgumentException e) + { + // ignore - not an oid + } + } + } } - + if (ecP == null) { return null; diff --git a/bcprov/src/main/java/org/bouncycastle/jce/PKCS10CertificationRequest.java b/bcprov/src/main/java/org/bouncycastle/jce/PKCS10CertificationRequest.java index 2a611e30..13bed1a9 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/PKCS10CertificationRequest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/PKCS10CertificationRequest.java @@ -24,12 +24,12 @@ import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; @@ -81,13 +81,13 @@ public class PKCS10CertificationRequest static { - algorithms.put("MD2WITHRSAENCRYPTION", new DERObjectIdentifier("1.2.840.113549.1.1.2")); - algorithms.put("MD2WITHRSA", new DERObjectIdentifier("1.2.840.113549.1.1.2")); - algorithms.put("MD5WITHRSAENCRYPTION", new DERObjectIdentifier("1.2.840.113549.1.1.4")); - algorithms.put("MD5WITHRSA", new DERObjectIdentifier("1.2.840.113549.1.1.4")); - algorithms.put("RSAWITHMD5", new DERObjectIdentifier("1.2.840.113549.1.1.4")); - algorithms.put("SHA1WITHRSAENCRYPTION", new DERObjectIdentifier("1.2.840.113549.1.1.5")); - algorithms.put("SHA1WITHRSA", new DERObjectIdentifier("1.2.840.113549.1.1.5")); + 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("RSAWITHMD5", 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("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption); algorithms.put("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption); algorithms.put("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption); @@ -101,15 +101,15 @@ public class PKCS10CertificationRequest algorithms.put("SHA256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("SHA384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("SHA512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("RSAWITHSHA1", new DERObjectIdentifier("1.2.840.113549.1.1.5")); + algorithms.put("RSAWITHSHA1", new ASN1ObjectIdentifier("1.2.840.113549.1.1.5")); algorithms.put("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); algorithms.put("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); algorithms.put("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); algorithms.put("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); algorithms.put("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); algorithms.put("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("SHA1WITHDSA", new DERObjectIdentifier("1.2.840.10040.4.3")); - algorithms.put("DSAWITHSHA1", new DERObjectIdentifier("1.2.840.10040.4.3")); + algorithms.put("SHA1WITHDSA", new ASN1ObjectIdentifier("1.2.840.10040.4.3")); + algorithms.put("DSAWITHSHA1", new ASN1ObjectIdentifier("1.2.840.10040.4.3")); algorithms.put("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224); algorithms.put("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256); algorithms.put("SHA384WITHDSA", NISTObjectIdentifiers.dsa_with_sha384); @@ -129,7 +129,7 @@ public class PKCS10CertificationRequest // // reverse mappings // - oids.put(new DERObjectIdentifier("1.2.840.113549.1.1.5"), "SHA1WITHRSA"); + oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.5"), "SHA1WITHRSA"); oids.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); oids.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); oids.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); @@ -137,9 +137,9 @@ public class PKCS10CertificationRequest oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410"); oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "GOST3411WITHECGOST3410"); - oids.put(new DERObjectIdentifier("1.2.840.113549.1.1.4"), "MD5WITHRSA"); - oids.put(new DERObjectIdentifier("1.2.840.113549.1.1.2"), "MD2WITHRSA"); - oids.put(new DERObjectIdentifier("1.2.840.10040.4.3"), "SHA1WITHDSA"); + oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.4"), "MD5WITHRSA"); + oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.2"), "MD2WITHRSA"); + oids.put(new ASN1ObjectIdentifier("1.2.840.10040.4.3"), "SHA1WITHDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA1, "SHA1WITHECDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); @@ -306,13 +306,13 @@ public class PKCS10CertificationRequest InvalidKeyException, SignatureException { String algorithmName = Strings.toUpperCase(signatureAlgorithm); - DERObjectIdentifier sigOID = (DERObjectIdentifier)algorithms.get(algorithmName); + ASN1ObjectIdentifier sigOID = (ASN1ObjectIdentifier)algorithms.get(algorithmName); if (sigOID == null) { try { - sigOID = new DERObjectIdentifier(algorithmName); + sigOID = new ASN1ObjectIdentifier(algorithmName); } catch (Exception e) { @@ -590,7 +590,7 @@ public class PKCS10CertificationRequest } private static String getDigestAlgName( - DERObjectIdentifier digestAlgOID) + ASN1ObjectIdentifier digestAlgOID) { if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/PKCS12Util.java b/bcprov/src/main/java/org/bouncycastle/jce/PKCS12Util.java index c780ed6b..c7059b26 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/PKCS12Util.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/PKCS12Util.java @@ -10,10 +10,10 @@ import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DEROutputStream; import org.bouncycastle.asn1.pkcs.ContentInfo; @@ -104,7 +104,7 @@ public class PKCS12Util } private static byte[] calculatePbeMac( - DERObjectIdentifier oid, + ASN1ObjectIdentifier oid, byte[] salt, int itCount, char[] password, diff --git a/bcprov/src/main/java/org/bouncycastle/jce/X509Principal.java b/bcprov/src/main/java/org/bouncycastle/jce/X509Principal.java index ddd38e87..b1daa98e 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/X509Principal.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/X509Principal.java @@ -129,7 +129,7 @@ public class X509Principal * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. lookUp * should provide a table of lookups, indexed by lowercase only strings and - * yielding a DERObjectIdentifier, other than that OID. and numeric oids + * yielding a ASN1ObjectIdentifier, other than that OID. and numeric oids * will be processed automatically. * <p> * If reverse is true, create the encoded version of the sequence starting diff --git a/bcprov/src/main/java/org/bouncycastle/jce/examples/PKCS12Example.java b/bcprov/src/main/java/org/bouncycastle/jce/examples/PKCS12Example.java deleted file mode 100644 index fe613df7..00000000 --- a/bcprov/src/main/java/org/bouncycastle/jce/examples/PKCS12Example.java +++ /dev/null @@ -1,379 +0,0 @@ -package org.bouncycastle.jce.examples; - -import java.io.FileOutputStream; -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Security; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.security.spec.RSAPrivateCrtKeySpec; -import java.security.spec.RSAPublicKeySpec; -import java.util.Date; -import java.util.Hashtable; -import java.util.Vector; - -import org.bouncycastle.asn1.DERBMPString; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x509.BasicConstraints; -import org.bouncycastle.asn1.x509.X509Extensions; -import org.bouncycastle.jce.PrincipalUtil; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.x509.X509V1CertificateGenerator; -import org.bouncycastle.x509.X509V3CertificateGenerator; -import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure; -import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure; - -/** - * Example of how to set up a certificiate chain and a PKCS 12 store for - * a private individual - obviously you'll need to generate your own keys, - * and you may need to add a NetscapeCertType extension or add a key - * usage extension depending on your application, but you should get the - * idea! As always this is just an example... - */ -public class PKCS12Example -{ - static char[] passwd = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' }; - - static X509V1CertificateGenerator v1CertGen = new X509V1CertificateGenerator(); - static X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); - - /** - * we generate the CA's certificate - */ - public static Certificate createMasterCert( - PublicKey pubKey, - PrivateKey privKey) - throws Exception - { - // - // signers name - // - String issuer = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate"; - - // - // subjects name - the same as we are self signed. - // - String subject = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate"; - - // - // create the certificate - version 1 - // - - v1CertGen.setSerialNumber(BigInteger.valueOf(1)); - v1CertGen.setIssuerDN(new X509Principal(issuer)); - v1CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); - v1CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30))); - v1CertGen.setSubjectDN(new X509Principal(subject)); - v1CertGen.setPublicKey(pubKey); - v1CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); - - X509Certificate cert = v1CertGen.generate(privKey); - - cert.checkValidity(new Date()); - - cert.verify(pubKey); - - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)cert; - - // - // this is actually optional - but if you want to have control - // over setting the friendly name this is the way to do it... - // - bagAttr.setBagAttribute( - PKCSObjectIdentifiers.pkcs_9_at_friendlyName, - new DERBMPString("Bouncy Primary Certificate")); - - return cert; - } - - /** - * we generate an intermediate certificate signed by our CA - */ - public static Certificate createIntermediateCert( - PublicKey pubKey, - PrivateKey caPrivKey, - X509Certificate caCert) - throws Exception - { - // - // subject name table. - // - Hashtable attrs = new Hashtable(); - Vector order = new Vector(); - - attrs.put(X509Principal.C, "AU"); - attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); - attrs.put(X509Principal.OU, "Bouncy Intermediate Certificate"); - attrs.put(X509Principal.EmailAddress, "feedback-crypto@bouncycastle.org"); - - order.addElement(X509Principal.C); - order.addElement(X509Principal.O); - order.addElement(X509Principal.OU); - order.addElement(X509Principal.EmailAddress); - - // - // create the certificate - version 3 - // - v3CertGen.reset(); - - v3CertGen.setSerialNumber(BigInteger.valueOf(2)); - v3CertGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert)); - v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); - v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30))); - v3CertGen.setSubjectDN(new X509Principal(order, attrs)); - v3CertGen.setPublicKey(pubKey); - v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); - - // - // extensions - // - v3CertGen.addExtension( - X509Extensions.SubjectKeyIdentifier, - false, - new SubjectKeyIdentifierStructure(pubKey)); - - v3CertGen.addExtension( - X509Extensions.AuthorityKeyIdentifier, - false, - new AuthorityKeyIdentifierStructure(caCert)); - - v3CertGen.addExtension( - X509Extensions.BasicConstraints, - true, - new BasicConstraints(0)); - - X509Certificate cert = v3CertGen.generate(caPrivKey); - - cert.checkValidity(new Date()); - - cert.verify(caCert.getPublicKey()); - - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)cert; - - // - // this is actually optional - but if you want to have control - // over setting the friendly name this is the way to do it... - // - bagAttr.setBagAttribute( - PKCSObjectIdentifiers.pkcs_9_at_friendlyName, - new DERBMPString("Bouncy Intermediate Certificate")); - - return cert; - } - - /** - * we generate a certificate signed by our CA's intermediate certficate - */ - public static Certificate createCert( - PublicKey pubKey, - PrivateKey caPrivKey, - PublicKey caPubKey) - throws Exception - { - // - // signers name table. - // - Hashtable sAttrs = new Hashtable(); - Vector sOrder = new Vector(); - - sAttrs.put(X509Principal.C, "AU"); - sAttrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); - sAttrs.put(X509Principal.OU, "Bouncy Intermediate Certificate"); - sAttrs.put(X509Principal.EmailAddress, "feedback-crypto@bouncycastle.org"); - - sOrder.addElement(X509Principal.C); - sOrder.addElement(X509Principal.O); - sOrder.addElement(X509Principal.OU); - sOrder.addElement(X509Principal.EmailAddress); - - // - // subjects name table. - // - Hashtable attrs = new Hashtable(); - Vector order = new Vector(); - - attrs.put(X509Principal.C, "AU"); - attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); - attrs.put(X509Principal.L, "Melbourne"); - attrs.put(X509Principal.CN, "Eric H. Echidna"); - attrs.put(X509Principal.EmailAddress, "feedback-crypto@bouncycastle.org"); - - order.addElement(X509Principal.C); - order.addElement(X509Principal.O); - order.addElement(X509Principal.L); - order.addElement(X509Principal.CN); - order.addElement(X509Principal.EmailAddress); - - // - // create the certificate - version 3 - // - v3CertGen.reset(); - - v3CertGen.setSerialNumber(BigInteger.valueOf(3)); - v3CertGen.setIssuerDN(new X509Principal(sOrder, sAttrs)); - v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); - v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30))); - v3CertGen.setSubjectDN(new X509Principal(order, attrs)); - v3CertGen.setPublicKey(pubKey); - v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); - - // - // add the extensions - // - v3CertGen.addExtension( - X509Extensions.SubjectKeyIdentifier, - false, - new SubjectKeyIdentifierStructure(pubKey)); - - v3CertGen.addExtension( - X509Extensions.AuthorityKeyIdentifier, - false, - new AuthorityKeyIdentifierStructure(caPubKey)); - - X509Certificate cert = v3CertGen.generate(caPrivKey); - - cert.checkValidity(new Date()); - - cert.verify(caPubKey); - - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)cert; - - // - // this is also optional - in the sense that if you leave this - // out the keystore will add it automatically, note though that - // for the browser to recognise the associated private key this - // you should at least use the pkcs_9_localKeyId OID and set it - // to the same as you do for the private key's localKeyId. - // - bagAttr.setBagAttribute( - PKCSObjectIdentifiers.pkcs_9_at_friendlyName, - new DERBMPString("Eric's Key")); - bagAttr.setBagAttribute( - PKCSObjectIdentifiers.pkcs_9_at_localKeyId, - new SubjectKeyIdentifierStructure(pubKey)); - - return cert; - } - - public static void main( - String[] args) - throws Exception - { - Security.addProvider(new BouncyCastleProvider()); - - // - // personal keys - // - RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( - new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), - new BigInteger("11", 16)); - - RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( - new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), - new BigInteger("11", 16), - new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), - new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), - new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), - new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), - new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), - new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); - - // - // intermediate keys. - // - RSAPublicKeySpec intPubKeySpec = new RSAPublicKeySpec( - new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), - new BigInteger("ffff", 16)); - - - RSAPrivateCrtKeySpec intPrivKeySpec = new RSAPrivateCrtKeySpec( - new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), - new BigInteger("ffff", 16), - new BigInteger("7deb1b194a85bcfd29cf871411468adbc987650903e3bacc8338c449ca7b32efd39ffc33bc84412fcd7df18d23ce9d7c25ea910b1ae9985373e0273b4dca7f2e0db3b7314056ac67fd277f8f89cf2fd73c34c6ca69f9ba477143d2b0e2445548aa0b4a8473095182631da46844c356f5e5c7522eb54b5a33f11d730ead9c0cff", 16), - new BigInteger("ef4cede573cea47f83699b814de4302edb60eefe426c52e17bd7870ec7c6b7a24fe55282ebb73775f369157726fcfb988def2b40350bdca9e5b418340288f649", 16), - new BigInteger("97c7737d1b9a0088c3c7b528539247fd2a1593e7e01cef18848755be82f4a45aa093276cb0cbf118cb41117540a78f3fc471ba5d69f0042274defc9161265721", 16), - new BigInteger("6c641094e24d172728b8da3c2777e69adfd0839085be7e38c7c4a2dd00b1ae969f2ec9d23e7e37090fcd449a40af0ed463fe1c612d6810d6b4f58b7bfa31eb5f", 16), - new BigInteger("70b7123e8e69dfa76feb1236d0a686144b00e9232ed52b73847e74ef3af71fb45ccb24261f40d27f98101e230cf27b977a5d5f1f15f6cf48d5cb1da2a3a3b87f", 16), - new BigInteger("e38f5750d97e270996a286df2e653fd26c242106436f5bab0f4c7a9e654ce02665d5a281f2c412456f2d1fa26586ef04a9adac9004ca7f913162cb28e13bf40d", 16)); - - // - // ca keys - // - RSAPublicKeySpec caPubKeySpec = new RSAPublicKeySpec( - new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), - new BigInteger("11", 16)); - - RSAPrivateCrtKeySpec caPrivKeySpec = new RSAPrivateCrtKeySpec( - new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), - new BigInteger("11", 16), - new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16), - new BigInteger("f75e80839b9b9379f1cf1128f321639757dba514642c206bbbd99f9a4846208b3e93fbbe5e0527cc59b1d4b929d9555853004c7c8b30ee6a213c3d1bb7415d03", 16), - new BigInteger("b892d9ebdbfc37e397256dd8a5d3123534d1f03726284743ddc6be3a709edb696fc40c7d902ed804c6eee730eee3d5b20bf6bd8d87a296813c87d3b3cc9d7947", 16), - new BigInteger("1d1a2d3ca8e52068b3094d501c9a842fec37f54db16e9a67070a8b3f53cc03d4257ad252a1a640eadd603724d7bf3737914b544ae332eedf4f34436cac25ceb5", 16), - new BigInteger("6c929e4e81672fef49d9c825163fec97c4b7ba7acb26c0824638ac22605d7201c94625770984f78a56e6e25904fe7db407099cad9b14588841b94f5ab498dded", 16), - new BigInteger("dae7651ee69ad1d081ec5e7188ae126f6004ff39556bde90e0b870962fa7b926d070686d8244fe5a9aa709a95686a104614834b0ada4b10f53197a5cb4c97339", 16)); - - - - // - // set up the keys - // - KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); - PrivateKey caPrivKey = fact.generatePrivate(caPrivKeySpec); - PublicKey caPubKey = fact.generatePublic(caPubKeySpec); - PrivateKey intPrivKey = fact.generatePrivate(intPrivKeySpec); - PublicKey intPubKey = fact.generatePublic(intPubKeySpec); - PrivateKey privKey = fact.generatePrivate(privKeySpec); - PublicKey pubKey = fact.generatePublic(pubKeySpec); - - Certificate[] chain = new Certificate[3]; - - chain[2] = createMasterCert(caPubKey, caPrivKey); - chain[1] = createIntermediateCert(intPubKey, caPrivKey, (X509Certificate)chain[2]); - chain[0] = createCert(pubKey, intPrivKey, intPubKey); - - // - // add the friendly name for the private key - // - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; - - // - // this is also optional - in the sense that if you leave this - // out the keystore will add it automatically, note though that - // for the browser to recognise which certificate the private key - // is associated with you should at least use the pkcs_9_localKeyId - // OID and set it to the same as you do for the private key's - // corresponding certificate. - // - bagAttr.setBagAttribute( - PKCSObjectIdentifiers.pkcs_9_at_friendlyName, - new DERBMPString("Eric's Key")); - bagAttr.setBagAttribute( - PKCSObjectIdentifiers.pkcs_9_at_localKeyId, - new SubjectKeyIdentifierStructure(pubKey)); - - // - // store the key and the certificate chain - // - KeyStore store = KeyStore.getInstance("PKCS12", "BC"); - - store.load(null, null); - - // - // if you haven't set the friendly name and local key id above - // the name below will be the name of the key - // - store.setKeyEntry("Eric's Key", privKey, null, chain); - - FileOutputStream fOut = new FileOutputStream("id.p12"); - - store.store(fOut, passwd); - - fOut.close(); - } -} diff --git a/bcprov/src/main/java/org/bouncycastle/jce/examples/package.html b/bcprov/src/main/java/org/bouncycastle/jce/examples/package.html new file mode 100644 index 00000000..96b31939 --- /dev/null +++ b/bcprov/src/main/java/org/bouncycastle/jce/examples/package.html @@ -0,0 +1,5 @@ +<html> +<body bgcolor="#ffffff"> +Example classes for use with the JCE. +</body> +</html> diff --git a/bcprov/src/main/java/org/bouncycastle/jce/interfaces/package.html b/bcprov/src/main/java/org/bouncycastle/jce/interfaces/package.html new file mode 100644 index 00000000..bacde6c8 --- /dev/null +++ b/bcprov/src/main/java/org/bouncycastle/jce/interfaces/package.html @@ -0,0 +1,5 @@ +<html> +<body bgcolor="#ffffff"> +Interfaces for supporting Elliptic Curve Keys, El Gamal, and PKCS12 attributes. +</body> +</html> diff --git a/bcprov/src/main/java/org/bouncycastle/jce/package.html b/bcprov/src/main/java/org/bouncycastle/jce/package.html new file mode 100644 index 00000000..52ef3bf6 --- /dev/null +++ b/bcprov/src/main/java/org/bouncycastle/jce/package.html @@ -0,0 +1,10 @@ +<html> +<body bgcolor="#ffffff"> +Utility classes for use with the JCE. +<p> +The classes in this package support the generation of certificates and PKCS10 signing requests. +<p> +Note: the PKCS7 class is deprecated, for a fuller version of CMS see the cms package distributed +with the BC mail API. +</body> +</html> diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/AnnotatedException.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/AnnotatedException.java index c9ac46ef..e8a8abe4 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/AnnotatedException.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/AnnotatedException.java @@ -8,14 +8,14 @@ public class AnnotatedException { private Throwable _underlyingException; - AnnotatedException(String string, Throwable e) + public AnnotatedException(String string, Throwable e) { super(string); _underlyingException = e; } - AnnotatedException(String string) + public AnnotatedException(String string) { this(string, null); } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/BouncyCastleProvider.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/BouncyCastleProvider.java index dc7db18e..a02ca15a 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/BouncyCastleProvider.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/BouncyCastleProvider.java @@ -44,7 +44,7 @@ import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; public final class BouncyCastleProvider extends Provider implements ConfigurableProvider { - private static String info = "BouncyCastle Security Provider v1.50"; + private static String info = "BouncyCastle Security Provider v1.52"; public static final String PROVIDER_NAME = "BC"; @@ -117,7 +117,7 @@ public final class BouncyCastleProvider extends Provider */ public BouncyCastleProvider() { - super(PROVIDER_NAME, 1.50, info); + super(PROVIDER_NAME, 1.52, info); AccessController.doPrivileged(new PrivilegedAction() { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/CertPathValidatorUtilities.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/CertPathValidatorUtilities.java index 9200fdae..1807aa87 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/CertPathValidatorUtilities.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/CertPathValidatorUtilities.java @@ -13,7 +13,6 @@ import java.security.cert.CertStore; import java.security.cert.CertStoreException; import java.security.cert.Certificate; import java.security.cert.CertificateParsingException; -import java.security.cert.PKIXParameters; import java.security.cert.PolicyQualifierInfo; import java.security.cert.TrustAnchor; import java.security.cert.X509CRL; @@ -27,30 +26,33 @@ import java.security.spec.DSAPublicKeySpec; import java.text.ParseException; 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.Iterator; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; -import javax.security.auth.x500.X500Principal; - import org.bouncycastle.asn1.ASN1Encodable; +import org.bouncycastle.asn1.ASN1Enumerated; +import org.bouncycastle.asn1.ASN1GeneralizedTime; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DEREnumerated; -import org.bouncycastle.asn1.DERGeneralizedTime; -import org.bouncycastle.asn1.DERIA5String; -import org.bouncycastle.asn1.DERObjectIdentifier; +import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.isismtt.ISISMTTObjectIdentifiers; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x500.style.RFC4519Style; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; import org.bouncycastle.asn1.x509.CRLDistPoint; import org.bouncycastle.asn1.x509.CRLReason; import org.bouncycastle.asn1.x509.DistributionPoint; @@ -60,21 +62,20 @@ import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.PolicyInformation; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.asn1.x509.X509Extension; -import org.bouncycastle.jce.X509LDAPCertStoreParameters; +import org.bouncycastle.jcajce.PKIXCRLStore; +import org.bouncycastle.jcajce.PKIXCRLStoreSelector; +import org.bouncycastle.jcajce.PKIXCertStore; +import org.bouncycastle.jcajce.PKIXCertStoreSelector; +import org.bouncycastle.jcajce.PKIXExtendedParameters; +import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.exception.ExtCertPathValidatorException; -import org.bouncycastle.util.Integers; import org.bouncycastle.util.Selector; +import org.bouncycastle.util.Store; import org.bouncycastle.util.StoreException; -import org.bouncycastle.x509.ExtendedPKIXBuilderParameters; -import org.bouncycastle.x509.ExtendedPKIXParameters; -import org.bouncycastle.x509.X509AttributeCertStoreSelector; import org.bouncycastle.x509.X509AttributeCertificate; -import org.bouncycastle.x509.X509CRLStoreSelector; -import org.bouncycastle.x509.X509CertStoreSelector; -import org.bouncycastle.x509.X509Store; +import org.bouncycastle.x509.extension.X509ExtensionUtil; -public class CertPathValidatorUtilities +class CertPathValidatorUtilities { protected static final PKIXCRLUtil CRL_UTIL = new PKIXCRLUtil(); @@ -160,7 +161,7 @@ public class CertPathValidatorUtilities Exception invalidKeyEx = null; X509CertSelector certSelectX509 = new X509CertSelector(); - X500Principal certIssuer = getEncodedIssuerPrincipal(cert); + X500Name certIssuer = PrincipalUtils.getEncodedIssuerPrincipal(cert); try { @@ -191,7 +192,7 @@ public class CertPathValidatorUtilities { try { - X500Principal caName = new X500Principal(trust.getCAName()); + X500Name caName = PrincipalUtils.getCA(trust); if (certIssuer.equals(caName)) { trustPublicKey = trust.getCAPublicKey(); @@ -234,50 +235,41 @@ public class CertPathValidatorUtilities return trust; } - protected static void addAdditionalStoresFromAltNames( - X509Certificate cert, - ExtendedPKIXParameters pkixParams) + static List<PKIXCertStore> getAdditionalStoresFromAltNames( + byte[] issuerAlternativeName, + Map<GeneralName, PKIXCertStore> altNameCertStoreMap) throws CertificateParsingException { // if in the IssuerAltName extension an URI - // is given, add an additinal X.509 store - if (cert.getIssuerAlternativeNames() != null) + // is given, add an additional X.509 store + if (issuerAlternativeName != null) { - Iterator it = cert.getIssuerAlternativeNames().iterator(); - while (it.hasNext()) + GeneralNames issuerAltName = GeneralNames.getInstance(ASN1OctetString.getInstance(issuerAlternativeName).getOctets()); + + GeneralName[] names = issuerAltName.getNames(); + List<PKIXCertStore> stores = new ArrayList<PKIXCertStore>(); + + for (int i = 0; i != names.length; i++) { - // look for URI - List list = (List)it.next(); - if (list.get(0).equals(Integers.valueOf(GeneralName.uniformResourceIdentifier))) + GeneralName altName = names[i]; + + PKIXCertStore altStore = altNameCertStoreMap.get(altName); + + if (altStore != null) { - // found - String temp = (String)list.get(1); - CertPathValidatorUtilities.addAdditionalStoreFromLocation(temp, pkixParams); + stores.add(altStore); } } - } - } - /** - * Returns the issuer of an attribute certificate or certificate. - * - * @param cert The attribute certificate or certificate. - * @return The issuer as <code>X500Principal</code>. - */ - protected static X500Principal getEncodedIssuerPrincipal( - Object cert) - { - if (cert instanceof X509Certificate) - { - return ((X509Certificate)cert).getIssuerX500Principal(); + return stores; } else { - return (X500Principal)((X509AttributeCertificate)cert).getIssuer().getPrincipals()[0]; + return Collections.EMPTY_LIST; } } - protected static Date getValidDate(PKIXParameters paramsPKIX) + protected static Date getValidDate(PKIXExtendedParameters paramsPKIX) { Date validDate = paramsPKIX.getDate(); @@ -289,11 +281,6 @@ public class CertPathValidatorUtilities return validDate; } - protected static X500Principal getSubjectPrincipal(X509Certificate cert) - { - return cert.getSubjectX500Principal(); - } - protected static boolean isSelfIssued(X509Certificate cert) { return cert.getSubjectDN().equals(cert.getIssuerDN()); @@ -340,11 +327,6 @@ public class CertPathValidatorUtilities } } - protected static X500Principal getIssuerPrincipal(X509CRL crl) - { - return crl.getIssuerX500Principal(); - } - protected static AlgorithmIdentifier getAlgorithmIdentifier( PublicKey key) throws CertPathValidatorException @@ -355,7 +337,7 @@ public class CertPathValidatorUtilities SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); - return info.getAlgorithmId(); + return info.getAlgorithm(); } catch (Exception e) { @@ -455,7 +437,7 @@ public class CertPathValidatorUtilities protected static boolean processCertD1i( int index, List[] policyNodes, - DERObjectIdentifier pOid, + ASN1ObjectIdentifier pOid, Set pq) { List policyNodeVec = policyNodes[index - 1]; @@ -490,7 +472,7 @@ public class CertPathValidatorUtilities protected static void processCertD1ii( int index, List[] policyNodes, - DERObjectIdentifier _poid, + ASN1ObjectIdentifier _poid, Set _pq) { List policyNodeVec = policyNodes[index - 1]; @@ -649,80 +631,31 @@ public class CertPathValidatorUtilities return policySet == null || policySet.contains(ANY_POLICY) || policySet.isEmpty(); } - protected static void addAdditionalStoreFromLocation(String location, - ExtendedPKIXParameters pkixParams) - { - if (pkixParams.isAdditionalLocationsEnabled()) - { - try - { - if (location.startsWith("ldap://")) - { - // ldap://directory.d-trust.net/CN=D-TRUST - // Qualified CA 2003 1:PN,O=D-Trust GmbH,C=DE - // skip "ldap://" - location = location.substring(7); - // after first / baseDN starts - String base = null; - String url = null; - if (location.indexOf("/") != -1) - { - base = location.substring(location.indexOf("/")); - // URL - url = "ldap://" - + location.substring(0, location.indexOf("/")); - } - else - { - url = "ldap://" + location; - } - // use all purpose parameters - X509LDAPCertStoreParameters params = new X509LDAPCertStoreParameters.Builder( - url, base).build(); - pkixParams.addAdditionalStore(X509Store.getInstance( - "CERTIFICATE/LDAP", params, BouncyCastleProvider.PROVIDER_NAME)); - pkixParams.addAdditionalStore(X509Store.getInstance( - "CRL/LDAP", params, BouncyCastleProvider.PROVIDER_NAME)); - pkixParams.addAdditionalStore(X509Store.getInstance( - "ATTRIBUTECERTIFICATE/LDAP", params, BouncyCastleProvider.PROVIDER_NAME)); - pkixParams.addAdditionalStore(X509Store.getInstance( - "CERTIFICATEPAIR/LDAP", params, BouncyCastleProvider.PROVIDER_NAME)); - } - } - catch (Exception e) - { - // cannot happen - throw new RuntimeException("Exception adding X.509 stores."); - } - } - } - /** * Return a Collection of all certificates or attribute certificates found * in the X509Store's that are matching the certSelect criteriums. * * @param certSelect a {@link Selector} object that will be used to select * the certificates - * @param certStores a List containing only {@link X509Store} objects. These + * @param certStores a List containing only {@link Store} objects. These * are used to search for certificates. - * @return a Collection of all found {@link X509Certificate} or - * {@link org.bouncycastle.x509.X509AttributeCertificate} objects. + * @return a Collection of all found {@link X509Certificate} * May be empty but never <code>null</code>. */ - protected static Collection findCertificates(X509CertStoreSelector certSelect, + protected static Collection findCertificates(PKIXCertStoreSelector certSelect, List certStores) throws AnnotatedException { - Set certs = new HashSet(); + Set certs = new LinkedHashSet(); Iterator iter = certStores.iterator(); while (iter.hasNext()) { Object obj = iter.next(); - if (obj instanceof X509Store) + if (obj instanceof Store) { - X509Store certStore = (X509Store)obj; + Store certStore = (Store)obj; try { certs.addAll(certStore.getMatches(certSelect)); @@ -739,7 +672,7 @@ public class CertPathValidatorUtilities try { - certs.addAll(certStore.getCertificates(certSelect)); + certs.addAll(PKIXCertStoreSelector.getCertificates(certSelect, certStore)); } catch (CertStoreException e) { @@ -752,36 +685,7 @@ public class CertPathValidatorUtilities return certs; } - protected static Collection findCertificates(X509AttributeCertStoreSelector certSelect, - List certStores) - throws AnnotatedException - { - Set certs = new HashSet(); - Iterator iter = certStores.iterator(); - - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof X509Store) - { - X509Store certStore = (X509Store)obj; - try - { - certs.addAll(certStore.getMatches(certSelect)); - } - catch (StoreException e) - { - throw new AnnotatedException( - "Problem while picking certificates from X.509 store.", e); - } - } - } - return certs; - } - - protected static void addAdditionalStoresFromCRLDistributionPoint( - CRLDistPoint crldp, ExtendedPKIXParameters pkixParams) + static List<PKIXCRLStore> getAdditionalStoresFromCRLDistributionPoint(CRLDistPoint crldp, Map<GeneralName, PKIXCRLStore> namedCRLStoreMap) throws AnnotatedException { if (crldp != null) @@ -796,6 +700,8 @@ public class CertPathValidatorUtilities throw new AnnotatedException( "Distribution points could not be read.", e); } + List<PKIXCRLStore> stores = new ArrayList<PKIXCRLStore>(); + for (int i = 0; i < dps.length; i++) { DistributionPointName dpn = dps[i].getDistributionPoint(); @@ -806,21 +712,24 @@ public class CertPathValidatorUtilities { GeneralName[] genNames = GeneralNames.getInstance( dpn.getName()).getNames(); - // look for an URI + for (int j = 0; j < genNames.length; j++) { - if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) + PKIXCRLStore store = namedCRLStoreMap.get(genNames[i]); + if (store != null) { - String location = DERIA5String.getInstance( - genNames[j].getName()).getString(); - CertPathValidatorUtilities - .addAdditionalStoreFromLocation(location, - pkixParams); + stores.add(store); } } } } } + + return stores; + } + else + { + return Collections.EMPTY_LIST; } } @@ -828,26 +737,22 @@ public class CertPathValidatorUtilities * Add the CRL issuers from the cRLIssuer field of the distribution point or * from the certificate if not given to the issuer criterion of the * <code>selector</code>. - * <p/> + * <p> * The <code>issuerPrincipals</code> are a collection with a single - * <code>X500Principal</code> for <code>X509Certificate</code>s. For - * {@link X509AttributeCertificate}s the issuer may contain more than one - * <code>X500Principal</code>. - * + * <code>X500Name</code> for <code>X509Certificate</code>s. + * </p> * @param dp The distribution point. * @param issuerPrincipals The issuers of the certificate or attribute * certificate which contains the distribution point. * @param selector The CRL selector. - * @param pkixParams The PKIX parameters containing the cert stores. * @throws AnnotatedException if an exception occurs while processing. * @throws ClassCastException if <code>issuerPrincipals</code> does not - * contain only <code>X500Principal</code>s. + * contain only <code>X500Name</code>s. */ protected static void getCRLIssuersFromDistributionPoint( DistributionPoint dp, Collection issuerPrincipals, - X509CRLSelector selector, - ExtendedPKIXParameters pkixParams) + X509CRLSelector selector) throws AnnotatedException { List issuers = new ArrayList(); @@ -862,7 +767,7 @@ public class CertPathValidatorUtilities { try { - issuers.add(new X500Principal(genNames[j].getName() + issuers.add(X500Name.getInstance(genNames[j].getName() .toASN1Primitive().getEncoded())); } catch (IOException e) @@ -888,7 +793,7 @@ public class CertPathValidatorUtilities // add and check issuer principals for (Iterator it = issuerPrincipals.iterator(); it.hasNext(); ) { - issuers.add((X500Principal)it.next()); + issuers.add(it.next()); } } // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid @@ -940,7 +845,7 @@ public class CertPathValidatorUtilities { try { - selector.addIssuerName(((X500Principal)it.next()).getEncoded()); + selector.addIssuerName(((X500Name)it.next()).getEncoded()); } catch (IOException ex) { @@ -953,14 +858,7 @@ public class CertPathValidatorUtilities private static BigInteger getSerialNumber( Object cert) { - if (cert instanceof X509Certificate) - { - return ((X509Certificate)cert).getSerialNumber(); - } - else - { - return ((X509AttributeCertificate)cert).getSerialNumber(); - } + return ((X509Certificate)cert).getSerialNumber(); } protected static void getCertStatus( @@ -991,19 +889,19 @@ public class CertPathValidatorUtilities return; } - X500Principal certIssuer = crl_entry.getCertificateIssuer(); + X500Name certIssuer = X500Name.getInstance(crl_entry.getCertificateIssuer().getEncoded()); if (certIssuer == null) { - certIssuer = getIssuerPrincipal(crl); + certIssuer = PrincipalUtils.getIssuerPrincipal(crl); } - if (!getEncodedIssuerPrincipal(cert).equals(certIssuer)) + if (! PrincipalUtils.getEncodedIssuerPrincipal(cert).equals(certIssuer)) { return; } } - else if (!getEncodedIssuerPrincipal(cert).equals(getIssuerPrincipal(crl))) + else if (! PrincipalUtils.getEncodedIssuerPrincipal(cert).equals(PrincipalUtils.getIssuerPrincipal(crl))) { return; // not for our issuer, ignore } @@ -1017,15 +915,15 @@ public class CertPathValidatorUtilities } } - DEREnumerated reasonCode = null; + ASN1Enumerated reasonCode = null; if (crl_entry.hasExtensions()) { try { - reasonCode = DEREnumerated + reasonCode = ASN1Enumerated .getInstance(CertPathValidatorUtilities .getExtensionValue(crl_entry, - X509Extension.reasonCode.getId())); + Extension.reasonCode.getId())); } catch (Exception e) { @@ -1062,31 +960,29 @@ public class CertPathValidatorUtilities /** * Fetches delta CRLs according to RFC 3280 section 5.2.4. * - * @param currentDate The date for which the delta CRLs must be valid. - * @param paramsPKIX The extended PKIX parameters. + * @param validityDate The date for which the delta CRLs must be valid. * @param completeCRL The complete CRL the delta CRL is for. * @return A <code>Set</code> of <code>X509CRL</code>s with delta CRLs. * @throws AnnotatedException if an exception occurs while picking the delta * CRLs. */ - protected static Set getDeltaCRLs(Date currentDate, - ExtendedPKIXParameters paramsPKIX, X509CRL completeCRL) + protected static Set getDeltaCRLs(Date validityDate, + X509CRL completeCRL, List<CertStore> certStores, List<PKIXCRLStore> pkixCrlStores) throws AnnotatedException { - - X509CRLStoreSelector deltaSelect = new X509CRLStoreSelector(); - + X509CRLSelector baseDeltaSelect = new X509CRLSelector(); // 5.2.4 (a) try { - deltaSelect.addIssuerName(CertPathValidatorUtilities - .getIssuerPrincipal(completeCRL).getEncoded()); + baseDeltaSelect.addIssuerName(PrincipalUtils.getIssuerPrincipal(completeCRL).getEncoded()); } catch (IOException e) { throw new AnnotatedException("Cannot extract issuer from CRL.", e); } + + BigInteger completeCRLNumber = null; try { @@ -1118,17 +1014,21 @@ public class CertPathValidatorUtilities // 5.2.4 (d) - deltaSelect.setMinCRLNumber(completeCRLNumber == null ? null : completeCRLNumber + baseDeltaSelect.setMinCRLNumber(completeCRLNumber == null ? null : completeCRLNumber .add(BigInteger.valueOf(1))); - deltaSelect.setIssuingDistributionPoint(idp); - deltaSelect.setIssuingDistributionPointEnabled(true); + PKIXCRLStoreSelector.Builder selBuilder = new PKIXCRLStoreSelector.Builder(baseDeltaSelect); + + selBuilder.setIssuingDistributionPoint(idp); + selBuilder.setIssuingDistributionPointEnabled(true); // 5.2.4 (c) - deltaSelect.setMaxBaseCRLNumber(completeCRLNumber); + selBuilder.setMaxBaseCRLNumber(completeCRLNumber); + + PKIXCRLStoreSelector deltaSelect = selBuilder.build(); // find delta CRLs - Set temp = CRL_UTIL.findCRLs(deltaSelect, paramsPKIX, currentDate); + Set temp = CRL_UTIL.findCRLs(deltaSelect, validityDate, certStores, pkixCrlStores); Set result = new HashSet(); @@ -1161,8 +1061,7 @@ public class CertPathValidatorUtilities * Fetches complete CRLs according to RFC 3280. * * @param dp The distribution point for which the complete CRL - * @param cert The <code>X509Certificate</code> or - * {@link org.bouncycastle.x509.X509AttributeCertificate} for + * @param cert The <code>X509Certificate</code> for * which the CRL should be searched. * @param currentDate The date for which the delta CRLs must be valid. * @param paramsPKIX The extended PKIX parameters. @@ -1172,66 +1071,51 @@ public class CertPathValidatorUtilities * or no CRLs are found. */ protected static Set getCompleteCRLs(DistributionPoint dp, Object cert, - Date currentDate, ExtendedPKIXParameters paramsPKIX) + Date currentDate, PKIXExtendedParameters paramsPKIX) throws AnnotatedException { - X509CRLStoreSelector crlselect = new X509CRLStoreSelector(); + X509CRLSelector baseCrlSelect = new X509CRLSelector(); + try { Set issuers = new HashSet(); - if (cert instanceof X509AttributeCertificate) - { - issuers.add(((X509AttributeCertificate)cert) - .getIssuer().getPrincipals()[0]); - } - else - { - issuers.add(getEncodedIssuerPrincipal(cert)); - } - CertPathValidatorUtilities.getCRLIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX); + + issuers.add(PrincipalUtils.getEncodedIssuerPrincipal(cert)); + + CertPathValidatorUtilities.getCRLIssuersFromDistributionPoint(dp, issuers, baseCrlSelect); } catch (AnnotatedException e) { throw new AnnotatedException( "Could not get issuer information from distribution point.", e); } + if (cert instanceof X509Certificate) { - crlselect.setCertificateChecking((X509Certificate)cert); - } - else if (cert instanceof X509AttributeCertificate) - { - crlselect.setAttrCertificateChecking((X509AttributeCertificate)cert); + baseCrlSelect.setCertificateChecking((X509Certificate)cert); } + PKIXCRLStoreSelector crlSelect = new PKIXCRLStoreSelector.Builder(baseCrlSelect).setCompleteCRLEnabled(true).build(); - crlselect.setCompleteCRLEnabled(true); + Date validityDate = currentDate; - Set crls = CRL_UTIL.findCRLs(crlselect, paramsPKIX, currentDate); - - if (crls.isEmpty()) + if (paramsPKIX.getDate() != null) { - if (cert instanceof X509AttributeCertificate) - { - X509AttributeCertificate aCert = (X509AttributeCertificate)cert; + validityDate = paramsPKIX.getDate(); + } - throw new AnnotatedException("No CRLs found for issuer \"" + aCert.getIssuer().getPrincipals()[0] + "\""); - } - else - { - X509Certificate xCert = (X509Certificate)cert; + Set crls = CRL_UTIL.findCRLs(crlSelect, validityDate, paramsPKIX.getCertStores(), paramsPKIX.getCRLStores()); + + checkCRLsNotEmpty(crls, cert); - throw new AnnotatedException("No CRLs found for issuer \"" + xCert.getIssuerX500Principal() + "\""); - } - } return crls; } protected static Date getValidCertDateFromValidityModel( - ExtendedPKIXParameters paramsPKIX, CertPath certPath, int index) + PKIXExtendedParameters paramsPKIX, CertPath certPath, int index) throws AnnotatedException { - if (paramsPKIX.getValidityModel() == ExtendedPKIXParameters.CHAIN_VALIDITY_MODEL) + if (paramsPKIX.getValidityModel() == PKIXExtendedParameters.CHAIN_VALIDITY_MODEL) { // if end cert use given signing/encryption/... time if (index <= 0) @@ -1243,13 +1127,13 @@ public class CertPathValidatorUtilities { if (index - 1 == 0) { - DERGeneralizedTime dateOfCertgen = null; + ASN1GeneralizedTime dateOfCertgen = null; try { byte[] extBytes = ((X509Certificate)certPath.getCertificates().get(index - 1)).getExtensionValue(ISISMTTObjectIdentifiers.id_isismtt_at_dateOfCertGen.getId()); if (extBytes != null) { - dateOfCertgen = DERGeneralizedTime.getInstance(ASN1Primitive.fromByteArray(extBytes)); + dateOfCertgen = ASN1GeneralizedTime.getInstance(ASN1Primitive.fromByteArray(extBytes)); } } catch (IOException e) @@ -1312,7 +1196,7 @@ public class CertPathValidatorUtilities * <code>index</code> extended with DSA parameters if applicable. * @throws AnnotatedException if DSA parameters cannot be inherited. */ - protected static PublicKey getNextWorkingKey(List certs, int index) + protected static PublicKey getNextWorkingKey(List certs, int index, JcaJceHelper helper) throws CertPathValidatorException { Certificate cert = (Certificate)certs.get(index); @@ -1345,7 +1229,7 @@ public class CertPathValidatorUtilities dsaPubKey.getY(), dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); try { - KeyFactory keyFactory = KeyFactory.getInstance("DSA", BouncyCastleProvider.PROVIDER_NAME); + KeyFactory keyFactory = helper.createKeyFactory("DSA"); return keyFactory.generatePublic(dsaPubKeySpec); } catch (Exception exception) @@ -1360,27 +1244,48 @@ public class CertPathValidatorUtilities * Find the issuer certificates of a given certificate. * * @param cert The certificate for which an issuer should be found. - * @param pkixParams * @return A <code>Collection</code> object containing the issuer * <code>X509Certificate</code>s. Never <code>null</code>. * @throws AnnotatedException if an error occurs. */ - protected static Collection findIssuerCerts( + static Collection findIssuerCerts( X509Certificate cert, - ExtendedPKIXBuilderParameters pkixParams) + List<CertStore> certStores, + List<PKIXCertStore> pkixCertStores) throws AnnotatedException { - X509CertStoreSelector certSelect = new X509CertStoreSelector(); - Set certs = new HashSet(); + X509CertSelector selector = new X509CertSelector(); + try { - certSelect.setSubject(cert.getIssuerX500Principal().getEncoded()); + selector.setSubject(PrincipalUtils.getIssuerPrincipal(cert).getEncoded()); } - catch (IOException ex) + catch (IOException e) { throw new AnnotatedException( - "Subject criteria for certificate selector to find issuer certificate could not be set.", ex); + "Subject criteria for certificate selector to find issuer certificate could not be set.", e); + } + + try + { + byte[] akiExtensionValue = cert.getExtensionValue(AUTHORITY_KEY_IDENTIFIER); + if (akiExtensionValue != null) + { + ASN1OctetString aki = ASN1OctetString.getInstance(akiExtensionValue); + byte[] authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(aki.getOctets()).getKeyIdentifier(); + if (authorityKeyIdentifier != null) + { + selector.setSubjectKeyIdentifier(new DEROctetString(authorityKeyIdentifier).getEncoded()); + } + } } + catch (Exception e) + { + // authority key identifier could not be retrieved from target cert, just search without it + } + + PKIXCertStoreSelector certSelect = new PKIXCertStoreSelector.Builder(selector).build(); + Set certs = new LinkedHashSet(); Iterator iter; @@ -1388,9 +1293,8 @@ public class CertPathValidatorUtilities { List matches = new ArrayList(); - matches.addAll(CertPathValidatorUtilities.findCertificates(certSelect, pkixParams.getCertStores())); - matches.addAll(CertPathValidatorUtilities.findCertificates(certSelect, pkixParams.getStores())); - matches.addAll(CertPathValidatorUtilities.findCertificates(certSelect, pkixParams.getAdditionalStores())); + matches.addAll(CertPathValidatorUtilities.findCertificates(certSelect, certStores)); + matches.addAll(CertPathValidatorUtilities.findCertificates(certSelect, pkixCertStores)); iter = matches.iterator(); } @@ -1423,4 +1327,24 @@ public class CertPathValidatorUtilities cert.verify(publicKey, sigProvider); } } + + static void checkCRLsNotEmpty(Set crls, Object cert) + throws AnnotatedException + { + if (crls.isEmpty()) + { + if (cert instanceof X509AttributeCertificate) + { + X509AttributeCertificate aCert = (X509AttributeCertificate)cert; + + throw new AnnotatedException("No CRLs found for issuer \"" + aCert.getIssuer().getPrincipals()[0] + "\""); + } + else + { + X509Certificate xCert = (X509Certificate)cert; + + throw new AnnotatedException("No CRLs found for issuer \"" + RFC4519Style.INSTANCE.toString(PrincipalUtils.getIssuerPrincipal(xCert)) + "\""); + } + } + } } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEDHPrivateKey.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEDHPrivateKey.java index b38f60bb..a30b2df7 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEDHPrivateKey.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEDHPrivateKey.java @@ -12,10 +12,9 @@ import javax.crypto.spec.DHPrivateKeySpec; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; +import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERInteger; -import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.pkcs.DHParameter; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; @@ -61,8 +60,8 @@ public class JCEDHPrivateKey throws IOException { ASN1Sequence seq = ASN1Sequence.getInstance(info.getAlgorithmId().getParameters()); - DERInteger derX = DERInteger.getInstance(info.parsePrivateKey()); - DERObjectIdentifier id = info.getAlgorithmId().getAlgorithm(); + ASN1Integer derX = ASN1Integer.getInstance(info.parsePrivateKey()); + ASN1ObjectIdentifier id = info.getAlgorithmId().getAlgorithm(); this.info = info; this.x = derX.getValue(); @@ -129,7 +128,7 @@ public class JCEDHPrivateKey return info.getEncoded(ASN1Encoding.DER); } - PrivateKeyInfo info = new PrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.dhKeyAgreement, new DHParameter(dhSpec.getP(), dhSpec.getG(), dhSpec.getL())), new DERInteger(getX())); + PrivateKeyInfo info = new PrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.dhKeyAgreement, new DHParameter(dhSpec.getP(), dhSpec.getG(), dhSpec.getL())), new ASN1Integer(getX())); return info.getEncoded(ASN1Encoding.DER); } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEDHPublicKey.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEDHPublicKey.java index 6ff1e083..3e6a09a6 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEDHPublicKey.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEDHPublicKey.java @@ -9,9 +9,9 @@ import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import javax.crypto.spec.DHPublicKeySpec; +import org.bouncycastle.asn1.ASN1Integer; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERInteger; -import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.pkcs.DHParameter; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -64,10 +64,10 @@ public class JCEDHPublicKey { this.info = info; - DERInteger derY; + ASN1Integer derY; try { - derY = (DERInteger)info.parsePublicKey(); + derY = (ASN1Integer)info.parsePublicKey(); } catch (IOException e) { @@ -77,7 +77,7 @@ public class JCEDHPublicKey this.y = derY.getValue(); ASN1Sequence seq = ASN1Sequence.getInstance(info.getAlgorithmId().getParameters()); - DERObjectIdentifier id = info.getAlgorithmId().getAlgorithm(); + ASN1ObjectIdentifier id = info.getAlgorithmId().getAlgorithm(); // we need the PKCS check to handle older keys marked with the X9 oid. if (id.equals(PKCSObjectIdentifiers.dhKeyAgreement) || isPKCSParam(seq)) @@ -122,7 +122,7 @@ public class JCEDHPublicKey return KeyUtil.getEncodedSubjectPublicKeyInfo(info); } - return KeyUtil.getEncodedSubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.dhKeyAgreement, new DHParameter(dhSpec.getP(), dhSpec.getG(), dhSpec.getL())), new DERInteger(y)); + return KeyUtil.getEncodedSubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.dhKeyAgreement, new DHParameter(dhSpec.getP(), dhSpec.getG(), dhSpec.getL())), new ASN1Integer(y)); } public DHParameterSpec getParams() @@ -147,8 +147,8 @@ public class JCEDHPublicKey return false; } - DERInteger l = DERInteger.getInstance(seq.getObjectAt(2)); - DERInteger p = DERInteger.getInstance(seq.getObjectAt(0)); + ASN1Integer l = ASN1Integer.getInstance(seq.getObjectAt(2)); + ASN1Integer p = ASN1Integer.getInstance(seq.getObjectAt(0)); if (l.getValue().compareTo(BigInteger.valueOf(p.getValue().bitLength())) > 0) { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEECPrivateKey.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEECPrivateKey.java index 63bb6d89..67e40b40 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEECPrivateKey.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEECPrivateKey.java @@ -13,13 +13,12 @@ import java.util.Enumeration; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; +import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.cryptopro.ECGOST3410NamedCurves; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; @@ -250,9 +249,9 @@ public class JCEECPrivateKey } ASN1Encodable privKey = info.parsePrivateKey(); - if (privKey instanceof DERInteger) + if (privKey instanceof ASN1Integer) { - DERInteger derD = DERInteger.getInstance(privKey); + ASN1Integer derD = ASN1Integer.getInstance(privKey); this.d = derD.getValue(); } @@ -292,10 +291,10 @@ public class JCEECPrivateKey if (ecSpec instanceof ECNamedCurveSpec) { - DERObjectIdentifier curveOid = ECUtil.getNamedCurveOid(((ECNamedCurveSpec)ecSpec).getName()); + ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(((ECNamedCurveSpec)ecSpec).getName()); if (curveOid == null) // guess it's the OID { - curveOid = new DERObjectIdentifier(((ECNamedCurveSpec)ecSpec).getName()); + curveOid = new ASN1ObjectIdentifier(((ECNamedCurveSpec)ecSpec).getName()); } params = new X962Parameters(curveOid); } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEECPublicKey.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEECPublicKey.java index 4bf2e68b..c82be8ca 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEECPublicKey.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEECPublicKey.java @@ -38,6 +38,8 @@ import org.bouncycastle.jce.interfaces.ECPointEncoder; import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; import org.bouncycastle.jce.spec.ECNamedCurveSpec; import org.bouncycastle.math.ec.ECCurve; +import org.bouncycastle.math.ec.custom.sec.SecP256K1Point; +import org.bouncycastle.math.ec.custom.sec.SecP256R1Point; public class JCEECPublicKey implements ECPublicKey, org.bouncycastle.jce.interfaces.ECPublicKey, ECPointEncoder @@ -439,14 +441,7 @@ public class JCEECPublicKey { if (ecSpec == null) { - if (q instanceof org.bouncycastle.math.ec.ECPoint.Fp) - { - return new org.bouncycastle.math.ec.ECPoint.Fp(null, q.getAffineXCoord(), q.getAffineYCoord()); - } - else - { - return new org.bouncycastle.math.ec.ECPoint.F2m(null, q.getAffineXCoord(), q.getAffineYCoord()); - } + return q.getDetachedPoint(); } return q; diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPrivateKey.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPrivateKey.java index afaddfa0..6c21f876 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPrivateKey.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPrivateKey.java @@ -13,8 +13,6 @@ import javax.crypto.spec.DHPrivateKeySpec; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.asn1.oiw.ElGamalParameter; import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; @@ -74,8 +72,8 @@ public class JCEElGamalPrivateKey PrivateKeyInfo info) throws IOException { - ElGamalParameter params = new ElGamalParameter((ASN1Sequence)info.getAlgorithmId().getParameters()); - DERInteger derX = ASN1Integer.getInstance(info.parsePrivateKey()); + ElGamalParameter params = ElGamalParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters()); + ASN1Integer derX = ASN1Integer.getInstance(info.parsePrivateKey()); this.x = derX.getValue(); this.elSpec = new ElGamalParameterSpec(params.getP(), params.getG()); @@ -111,7 +109,7 @@ public class JCEElGamalPrivateKey */ public byte[] getEncoded() { - return KeyUtil.getEncodedPrivateKeyInfo(new AlgorithmIdentifier(OIWObjectIdentifiers.elGamalAlgorithm, new ElGamalParameter(elSpec.getP(), elSpec.getG())), new DERInteger(getX())); + return KeyUtil.getEncodedPrivateKeyInfo(new AlgorithmIdentifier(OIWObjectIdentifiers.elGamalAlgorithm, new ElGamalParameter(elSpec.getP(), elSpec.getG())), new ASN1Integer(getX())); } public ElGamalParameterSpec getParameters() diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPublicKey.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPublicKey.java index cb7a0abf..30780c85 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPublicKey.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEElGamalPublicKey.java @@ -9,8 +9,7 @@ import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import javax.crypto.spec.DHPublicKeySpec; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERInteger; +import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.oiw.ElGamalParameter; import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -75,12 +74,12 @@ public class JCEElGamalPublicKey JCEElGamalPublicKey( SubjectPublicKeyInfo info) { - ElGamalParameter params = new ElGamalParameter((ASN1Sequence)info.getAlgorithmId().getParameters()); - DERInteger derY = null; + ElGamalParameter params = ElGamalParameter.getInstance(info.getAlgorithm().getParameters()); + ASN1Integer derY = null; try { - derY = (DERInteger)info.parsePublicKey(); + derY = (ASN1Integer)info.parsePublicKey(); } catch (IOException e) { @@ -103,7 +102,7 @@ public class JCEElGamalPublicKey public byte[] getEncoded() { - return KeyUtil.getEncodedSubjectPublicKeyInfo(new AlgorithmIdentifier(OIWObjectIdentifiers.elGamalAlgorithm, new ElGamalParameter(elSpec.getP(), elSpec.getG())), new DERInteger(y)); + return KeyUtil.getEncodedSubjectPublicKeyInfo(new AlgorithmIdentifier(OIWObjectIdentifiers.elGamalAlgorithm, new ElGamalParameter(elSpec.getP(), elSpec.getG())), new ASN1Integer(y)); } public ElGamalParameterSpec getParameters() diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEStreamCipher.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEStreamCipher.java deleted file mode 100644 index 46104b27..00000000 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/JCEStreamCipher.java +++ /dev/null @@ -1,613 +0,0 @@ -package org.bouncycastle.jce.provider; - -import java.security.AlgorithmParameters; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.CipherSpi; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.ShortBufferException; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.PBEParameterSpec; -import javax.crypto.spec.RC2ParameterSpec; -import javax.crypto.spec.RC5ParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; -import org.bouncycastle.crypto.BlockCipher; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.DataLengthException; -import org.bouncycastle.crypto.StreamBlockCipher; -import org.bouncycastle.crypto.StreamCipher; -import org.bouncycastle.crypto.engines.BlowfishEngine; -import org.bouncycastle.crypto.engines.DESEngine; -import org.bouncycastle.crypto.engines.DESedeEngine; -import org.bouncycastle.crypto.engines.RC4Engine; -import org.bouncycastle.crypto.engines.SkipjackEngine; -import org.bouncycastle.crypto.engines.TwofishEngine; -import org.bouncycastle.crypto.modes.CFBBlockCipher; -import org.bouncycastle.crypto.modes.OFBBlockCipher; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; -import org.bouncycastle.jcajce.provider.symmetric.util.BCPBEKey; -import org.bouncycastle.jcajce.provider.symmetric.util.PBE; - -public class JCEStreamCipher - extends CipherSpi - implements PBE -{ - // - // specs we can handle. - // - private Class[] availableSpecs = - { - RC2ParameterSpec.class, - RC5ParameterSpec.class, - IvParameterSpec.class, - PBEParameterSpec.class - }; - - private StreamCipher cipher; - private ParametersWithIV ivParam; - - private int ivLength = 0; - - private PBEParameterSpec pbeSpec = null; - private String pbeAlgorithm = null; - - private AlgorithmParameters engineParams; - - protected JCEStreamCipher( - StreamCipher engine, - int ivLength) - { - cipher = engine; - this.ivLength = ivLength; - } - - protected JCEStreamCipher( - BlockCipher engine, - int ivLength) - { - this.ivLength = ivLength; - - cipher = new StreamBlockCipher(engine); - } - - protected int engineGetBlockSize() - { - return 0; - } - - protected byte[] engineGetIV() - { - return (ivParam != null) ? ivParam.getIV() : null; - } - - protected int engineGetKeySize( - Key key) - { - return key.getEncoded().length * 8; - } - - protected int engineGetOutputSize( - int inputLen) - { - return inputLen; - } - - protected AlgorithmParameters engineGetParameters() - { - if (engineParams == null) - { - if (pbeSpec != null) - { - try - { - AlgorithmParameters engineParams = AlgorithmParameters.getInstance(pbeAlgorithm, BouncyCastleProvider.PROVIDER_NAME); - engineParams.init(pbeSpec); - - return engineParams; - } - catch (Exception e) - { - return null; - } - } - } - - return engineParams; - } - - /** - * should never be called. - */ - protected void engineSetMode( - String mode) - { - if (!mode.equalsIgnoreCase("ECB")) - { - throw new IllegalArgumentException("can't support mode " + mode); - } - } - - /** - * should never be called. - */ - protected void engineSetPadding( - String padding) - throws NoSuchPaddingException - { - if (!padding.equalsIgnoreCase("NoPadding")) - { - throw new NoSuchPaddingException("Padding " + padding + " unknown."); - } - } - - protected void engineInit( - int opmode, - Key key, - AlgorithmParameterSpec params, - SecureRandom random) - throws InvalidKeyException, InvalidAlgorithmParameterException - { - CipherParameters param; - - this.pbeSpec = null; - this.pbeAlgorithm = null; - - this.engineParams = null; - - // - // basic key check - // - if (!(key instanceof SecretKey)) - { - throw new InvalidKeyException("Key for algorithm " + key.getAlgorithm() + " not suitable for symmetric enryption."); - } - - if (key instanceof BCPBEKey) - { - BCPBEKey k = (BCPBEKey)key; - - if (k.getOID() != null) - { - pbeAlgorithm = k.getOID().getId(); - } - else - { - pbeAlgorithm = k.getAlgorithm(); - } - - if (k.getParam() != null) - { - param = k.getParam(); - pbeSpec = new PBEParameterSpec(k.getSalt(), k.getIterationCount()); - } - else if (params instanceof PBEParameterSpec) - { - param = PBE.Util.makePBEParameters(k, params, cipher.getAlgorithmName()); - pbeSpec = (PBEParameterSpec)params; - } - else - { - throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set."); - } - - if (k.getIvSize() != 0) - { - ivParam = (ParametersWithIV)param; - } - } - else if (params == null) - { - param = new KeyParameter(key.getEncoded()); - } - else if (params instanceof IvParameterSpec) - { - param = new ParametersWithIV(new KeyParameter(key.getEncoded()), ((IvParameterSpec)params).getIV()); - ivParam = (ParametersWithIV)param; - } - else - { - throw new IllegalArgumentException("unknown parameter type."); - } - - if ((ivLength != 0) && !(param instanceof ParametersWithIV)) - { - SecureRandom ivRandom = random; - - if (ivRandom == null) - { - ivRandom = new SecureRandom(); - } - - if ((opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher.WRAP_MODE)) - { - byte[] iv = new byte[ivLength]; - - ivRandom.nextBytes(iv); - param = new ParametersWithIV(param, iv); - ivParam = (ParametersWithIV)param; - } - else - { - throw new InvalidAlgorithmParameterException("no IV set when one expected"); - } - } - - switch (opmode) - { - case Cipher.ENCRYPT_MODE: - case Cipher.WRAP_MODE: - cipher.init(true, param); - break; - case Cipher.DECRYPT_MODE: - case Cipher.UNWRAP_MODE: - cipher.init(false, param); - break; - default: - System.out.println("eeek!"); - } - } - - protected void engineInit( - int opmode, - Key key, - AlgorithmParameters params, - SecureRandom random) - throws InvalidKeyException, InvalidAlgorithmParameterException - { - AlgorithmParameterSpec paramSpec = null; - - if (params != null) - { - for (int i = 0; i != availableSpecs.length; i++) - { - try - { - paramSpec = params.getParameterSpec(availableSpecs[i]); - break; - } - catch (Exception e) - { - continue; - } - } - - if (paramSpec == null) - { - throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString()); - } - } - - engineInit(opmode, key, paramSpec, random); - engineParams = params; - } - - protected void engineInit( - int opmode, - Key key, - SecureRandom random) - throws InvalidKeyException - { - try - { - engineInit(opmode, key, (AlgorithmParameterSpec)null, random); - } - catch (InvalidAlgorithmParameterException e) - { - throw new InvalidKeyException(e.getMessage()); - } - } - - protected byte[] engineUpdate( - byte[] input, - int inputOffset, - int inputLen) - { - byte[] out = new byte[inputLen]; - - cipher.processBytes(input, inputOffset, inputLen, out, 0); - - return out; - } - - protected int engineUpdate( - byte[] input, - int inputOffset, - int inputLen, - byte[] output, - int outputOffset) - throws ShortBufferException - { - try - { - cipher.processBytes(input, inputOffset, inputLen, output, outputOffset); - - return inputLen; - } - catch (DataLengthException e) - { - throw new ShortBufferException(e.getMessage()); - } - } - - protected byte[] engineDoFinal( - byte[] input, - int inputOffset, - int inputLen) - throws BadPaddingException, IllegalBlockSizeException - { - if (inputLen != 0) - { - byte[] out = engineUpdate(input, inputOffset, inputLen); - - cipher.reset(); - - return out; - } - - cipher.reset(); - - return new byte[0]; - } - - protected int engineDoFinal( - byte[] input, - int inputOffset, - int inputLen, - byte[] output, - int outputOffset) - throws BadPaddingException - { - if (inputLen != 0) - { - cipher.processBytes(input, inputOffset, inputLen, output, outputOffset); - } - - cipher.reset(); - - return inputLen; - } - - protected byte[] engineWrap( - Key key) - throws IllegalBlockSizeException, InvalidKeyException - { - byte[] encoded = key.getEncoded(); - if (encoded == null) - { - throw new InvalidKeyException("Cannot wrap key, null encoding."); - } - - try - { - return engineDoFinal(encoded, 0, encoded.length); - } - catch (BadPaddingException e) - { - throw new IllegalBlockSizeException(e.getMessage()); - } - } - - protected Key engineUnwrap( - byte[] wrappedKey, - String wrappedKeyAlgorithm, - int wrappedKeyType) - throws InvalidKeyException - { - byte[] encoded; - try - { - encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length); - } - catch (BadPaddingException e) - { - throw new InvalidKeyException(e.getMessage()); - } - catch (IllegalBlockSizeException e2) - { - throw new InvalidKeyException(e2.getMessage()); - } - - if (wrappedKeyType == Cipher.SECRET_KEY) - { - return new SecretKeySpec(encoded, wrappedKeyAlgorithm); - } - else if (wrappedKeyAlgorithm.equals("") && wrappedKeyType == Cipher.PRIVATE_KEY) - { - /* - * The caller doesn't know the algorithm as it is part of - * the encrypted data. - */ - try - { - PrivateKeyInfo in = PrivateKeyInfo.getInstance(encoded); - - PrivateKey privKey = BouncyCastleProvider.getPrivateKey(in); - - if (privKey != null) - { - return privKey; - } - else - { - throw new InvalidKeyException("algorithm " + in.getPrivateKeyAlgorithm().getAlgorithm() + " not supported"); - } - } - catch (Exception e) - { - throw new InvalidKeyException("Invalid key encoding."); - } - } - else - { - try - { - KeyFactory kf = KeyFactory.getInstance(wrappedKeyAlgorithm, BouncyCastleProvider.PROVIDER_NAME); - - if (wrappedKeyType == Cipher.PUBLIC_KEY) - { - return kf.generatePublic(new X509EncodedKeySpec(encoded)); - } - else if (wrappedKeyType == Cipher.PRIVATE_KEY) - { - return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded)); - } - } - catch (NoSuchProviderException e) - { - throw new InvalidKeyException("Unknown key type " + e.getMessage()); - } - catch (NoSuchAlgorithmException e) - { - throw new InvalidKeyException("Unknown key type " + e.getMessage()); - } - catch (InvalidKeySpecException e2) - { - throw new InvalidKeyException("Unknown key type " + e2.getMessage()); - } - - throw new InvalidKeyException("Unknown key type " + wrappedKeyType); - } - } - - /* - * The ciphers that inherit from us. - */ - - /** - * DES - */ - static public class DES_CFB8 - extends JCEStreamCipher - { - public DES_CFB8() - { - super(new CFBBlockCipher(new DESEngine(), 8), 64); - } - } - - /** - * DESede - */ - static public class DESede_CFB8 - extends JCEStreamCipher - { - public DESede_CFB8() - { - super(new CFBBlockCipher(new DESedeEngine(), 8), 64); - } - } - - /** - * SKIPJACK - */ - static public class Skipjack_CFB8 - extends JCEStreamCipher - { - public Skipjack_CFB8() - { - super(new CFBBlockCipher(new SkipjackEngine(), 8), 64); - } - } - - /** - * Blowfish - */ - static public class Blowfish_CFB8 - extends JCEStreamCipher - { - public Blowfish_CFB8() - { - super(new CFBBlockCipher(new BlowfishEngine(), 8), 64); - } - } - - /** - * Twofish - */ - static public class Twofish_CFB8 - extends JCEStreamCipher - { - public Twofish_CFB8() - { - super(new CFBBlockCipher(new TwofishEngine(), 8), 128); - } - } - - /** - * DES - */ - static public class DES_OFB8 - extends JCEStreamCipher - { - public DES_OFB8() - { - super(new OFBBlockCipher(new DESEngine(), 8), 64); - } - } - - /** - * DESede - */ - static public class DESede_OFB8 - extends JCEStreamCipher - { - public DESede_OFB8() - { - super(new OFBBlockCipher(new DESedeEngine(), 8), 64); - } - } - - /** - * SKIPJACK - */ - static public class Skipjack_OFB8 - extends JCEStreamCipher - { - public Skipjack_OFB8() - { - super(new OFBBlockCipher(new SkipjackEngine(), 8), 64); - } - } - - /** - * Blowfish - */ - static public class Blowfish_OFB8 - extends JCEStreamCipher - { - public Blowfish_OFB8() - { - super(new OFBBlockCipher(new BlowfishEngine(), 8), 64); - } - } - - /** - * Twofish - */ - static public class Twofish_OFB8 - extends JCEStreamCipher - { - public Twofish_OFB8() - { - super(new OFBBlockCipher(new TwofishEngine(), 8), 128); - } - } -} diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPrivateKey.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPrivateKey.java index 50a714c8..3bd6d307 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPrivateKey.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPrivateKey.java @@ -14,8 +14,6 @@ import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.DSAParameter; @@ -57,7 +55,7 @@ public class JDKDSAPrivateKey throws IOException { DSAParameter params = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters()); - DERInteger derX = ASN1Integer.getInstance(info.parsePrivateKey()); + ASN1Integer derX = ASN1Integer.getInstance(info.parsePrivateKey()); this.x = derX.getValue(); this.dsaSpec = new DSAParameterSpec(params.getP(), params.getQ(), params.getG()); @@ -95,7 +93,7 @@ public class JDKDSAPrivateKey { try { - PrivateKeyInfo info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(dsaSpec.getP(), dsaSpec.getQ(), dsaSpec.getG())), new DERInteger(getX())); + PrivateKeyInfo info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(dsaSpec.getP(), dsaSpec.getQ(), dsaSpec.getG())), new ASN1Integer(getX())); return info.getEncoded(ASN1Encoding.DER); } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPublicKey.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPublicKey.java index 85a39a46..80bbf3c5 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPublicKey.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/JDKDSAPublicKey.java @@ -11,8 +11,7 @@ import java.security.spec.DSAPublicKeySpec; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERInteger; +import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.DSAParameter; @@ -61,11 +60,11 @@ public class JDKDSAPublicKey SubjectPublicKeyInfo info) { - DERInteger derY; + ASN1Integer derY; try { - derY = (DERInteger)info.parsePublicKey(); + derY = (ASN1Integer)info.parsePublicKey(); } catch (IOException e) { @@ -103,10 +102,10 @@ public class JDKDSAPublicKey { if (dsaSpec == null) { - return new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new DERInteger(y)).getEncoded(ASN1Encoding.DER); + return new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new ASN1Integer(y)).getEncoded(ASN1Encoding.DER); } - return new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(dsaSpec.getP(), dsaSpec.getQ(), dsaSpec.getG())), new DERInteger(y)).getEncoded(ASN1Encoding.DER); + return new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(dsaSpec.getP(), dsaSpec.getQ(), dsaSpec.getG())), new ASN1Integer(y)).getEncoded(ASN1Encoding.DER); } catch (IOException e) { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXAttrCertPathBuilderSpi.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXAttrCertPathBuilderSpi.java index 14aef43e..115c198c 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXAttrCertPathBuilderSpi.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXAttrCertPathBuilderSpi.java @@ -1,5 +1,6 @@ package org.bouncycastle.jce.provider; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.Principal; @@ -9,6 +10,10 @@ import java.security.cert.CertPathBuilderResult; import java.security.cert.CertPathBuilderSpi; import java.security.cert.CertPathParameters; import java.security.cert.CertPathValidator; +import java.security.cert.CertStore; +import java.security.cert.CertStoreException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateParsingException; import java.security.cert.PKIXBuilderParameters; @@ -24,12 +29,20 @@ import java.util.Set; import javax.security.auth.x500.X500Principal; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.jcajce.PKIXCertStoreSelector; +import org.bouncycastle.jcajce.PKIXExtendedBuilderParameters; import org.bouncycastle.jce.exception.ExtCertPathBuilderException; +import org.bouncycastle.util.Encodable; import org.bouncycastle.util.Selector; +import org.bouncycastle.util.Store; +import org.bouncycastle.util.StoreException; import org.bouncycastle.x509.ExtendedPKIXBuilderParameters; +import org.bouncycastle.x509.ExtendedPKIXParameters; import org.bouncycastle.x509.X509AttributeCertStoreSelector; import org.bouncycastle.x509.X509AttributeCertificate; import org.bouncycastle.x509.X509CertStoreSelector; +import org.bouncycastle.x509.X509Store; public class PKIXAttrCertPathBuilderSpi extends CertPathBuilderSpi @@ -45,24 +58,37 @@ public class PKIXAttrCertPathBuilderSpi throws CertPathBuilderException, InvalidAlgorithmParameterException { if (!(params instanceof PKIXBuilderParameters) - && !(params instanceof ExtendedPKIXBuilderParameters)) + && !(params instanceof ExtendedPKIXBuilderParameters) + && !(params instanceof PKIXExtendedBuilderParameters)) { throw new InvalidAlgorithmParameterException( "Parameters must be an instance of " + PKIXBuilderParameters.class.getName() + " or " - + ExtendedPKIXBuilderParameters.class.getName() + + PKIXExtendedBuilderParameters.class.getName() + "."); } - ExtendedPKIXBuilderParameters pkixParams; - if (params instanceof ExtendedPKIXBuilderParameters) + List targetStores = new ArrayList(); + + PKIXExtendedBuilderParameters paramsPKIX; + if (params instanceof PKIXBuilderParameters) { - pkixParams = (ExtendedPKIXBuilderParameters) params; + PKIXExtendedBuilderParameters.Builder paramsPKIXBldr = new PKIXExtendedBuilderParameters.Builder((PKIXBuilderParameters)params); + + if (params instanceof ExtendedPKIXParameters) + { + ExtendedPKIXBuilderParameters extPKIX = (ExtendedPKIXBuilderParameters)params; + + paramsPKIXBldr.addExcludedCerts(extPKIX.getExcludedCerts()); + paramsPKIXBldr.setMaxPathLength(extPKIX.getMaxPathLength()); + targetStores = extPKIX.getStores(); + } + + paramsPKIX = paramsPKIXBldr.build(); } else { - pkixParams = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters - .getInstance((PKIXBuilderParameters) params); + paramsPKIX = (PKIXExtendedBuilderParameters)params; } Collection targets; @@ -72,7 +98,7 @@ public class PKIXAttrCertPathBuilderSpi // search target certificates - Selector certSelect = pkixParams.getTargetConstraints(); + Selector certSelect = paramsPKIX.getBaseParameters().getTargetConstraints(); if (!(certSelect instanceof X509AttributeCertStoreSelector)) { throw new CertPathBuilderException( @@ -81,9 +107,10 @@ public class PKIXAttrCertPathBuilderSpi + " for "+this.getClass().getName()+" class."); } + try { - targets = CertPathValidatorUtilities.findCertificates((X509AttributeCertStoreSelector)certSelect, pkixParams.getStores()); + targets = findCertificates((X509AttributeCertStoreSelector)certSelect, targetStores); } catch (AnnotatedException e) { @@ -115,8 +142,9 @@ public class PKIXAttrCertPathBuilderSpi { selector.setSubject(((X500Principal)principals[i]).getEncoded()); } - issuers.addAll(CertPathValidatorUtilities.findCertificates(selector, pkixParams.getStores())); - issuers.addAll(CertPathValidatorUtilities.findCertificates(selector, pkixParams.getCertStores())); + PKIXCertStoreSelector certStoreSelector = new PKIXCertStoreSelector.Builder(selector).build(); + issuers.addAll(CertPathValidatorUtilities.findCertificates(certStoreSelector, paramsPKIX.getBaseParameters().getCertStores())); + issuers.addAll(CertPathValidatorUtilities.findCertificates(certStoreSelector, paramsPKIX.getBaseParameters().getCertificateStores())); } catch (AnnotatedException e) { @@ -139,7 +167,7 @@ public class PKIXAttrCertPathBuilderSpi Iterator it = issuers.iterator(); while (it.hasNext() && result == null) { - result = build(cert, (X509Certificate)it.next(), pkixParams, certPathList); + result = build(cert, (X509Certificate)it.next(), paramsPKIX, certPathList); } } @@ -162,7 +190,7 @@ public class PKIXAttrCertPathBuilderSpi private Exception certPathException; private CertPathBuilderResult build(X509AttributeCertificate attrCert, X509Certificate tbvCert, - ExtendedPKIXBuilderParameters pkixParams, List tbvPath) + PKIXExtendedBuilderParameters pkixParams, List tbvPath) { // If tbvCert is readily present in tbvPath, it indicates having run @@ -208,8 +236,8 @@ public class PKIXAttrCertPathBuilderSpi try { // check whether the issuer of <tbvCert> is a TrustAnchor - if (CertPathValidatorUtilities.findTrustAnchor(tbvCert, pkixParams.getTrustAnchors(), - pkixParams.getSigProvider()) != null) + if (CertPathValidatorUtilities.findTrustAnchor(tbvCert, pkixParams.getBaseParameters().getTrustAnchors(), + pkixParams.getBaseParameters().getSigProvider()) != null) { CertPath certPath; PKIXCertPathValidatorResult result; @@ -243,10 +271,13 @@ public class PKIXAttrCertPathBuilderSpi } else { + List stores = new ArrayList(); + + stores.addAll(pkixParams.getBaseParameters().getCertificateStores()); // add additional X.509 stores from locations in certificate try { - CertPathValidatorUtilities.addAdditionalStoresFromAltNames(tbvCert, pkixParams); + stores.addAll(CertPathValidatorUtilities.getAdditionalStoresFromAltNames(tbvCert.getExtensionValue(Extension.issuerAlternativeName.getId()), pkixParams.getBaseParameters().getNamedCertificateStoreMap())); } catch (CertificateParsingException e) { @@ -259,7 +290,7 @@ public class PKIXAttrCertPathBuilderSpi // of the stores try { - issuers.addAll(CertPathValidatorUtilities.findIssuerCerts(tbvCert, pkixParams)); + issuers.addAll(CertPathValidatorUtilities.findIssuerCerts(tbvCert, pkixParams.getBaseParameters().getCertStores(), stores)); } catch (AnnotatedException e) { @@ -300,4 +331,31 @@ public class PKIXAttrCertPathBuilderSpi return builderResult; } + protected static Collection findCertificates(X509AttributeCertStoreSelector certSelect, + List certStores) + throws AnnotatedException + { + Set certs = new HashSet(); + Iterator iter = certStores.iterator(); + + while (iter.hasNext()) + { + Object obj = iter.next(); + + if (obj instanceof Store) + { + Store certStore = (Store)obj; + try + { + certs.addAll(certStore.getMatches(certSelect)); + } + catch (StoreException e) + { + throw new AnnotatedException( + "Problem while picking certificates from X.509 store.", e); + } + } + } + return certs; + } } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXAttrCertPathValidatorSpi.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXAttrCertPathValidatorSpi.java index c1759bac..ee727038 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXAttrCertPathValidatorSpi.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXAttrCertPathValidatorSpi.java @@ -1,15 +1,22 @@ package org.bouncycastle.jce.provider; import java.security.InvalidAlgorithmParameterException; +import java.security.Provider; +import java.security.Security; import java.security.cert.CertPath; import java.security.cert.CertPathParameters; import java.security.cert.CertPathValidatorException; import java.security.cert.CertPathValidatorResult; import java.security.cert.CertPathValidatorSpi; +import java.security.cert.PKIXParameters; import java.security.cert.X509Certificate; import java.util.Date; +import java.util.HashSet; import java.util.Set; +import org.bouncycastle.jcajce.PKIXExtendedParameters; +import org.bouncycastle.jcajce.util.BCJcaJceHelper; +import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.exception.ExtCertPathValidatorException; import org.bouncycastle.util.Selector; import org.bouncycastle.x509.ExtendedPKIXParameters; @@ -24,6 +31,11 @@ import org.bouncycastle.x509.X509AttributeCertificate; public class PKIXAttrCertPathValidatorSpi extends CertPathValidatorSpi { + private final JcaJceHelper helper = new BCJcaJceHelper(); + + public PKIXAttrCertPathValidatorSpi() + { + } /** * Validates an attribute certificate with the given certificate path. @@ -38,30 +50,56 @@ public class PKIXAttrCertPathValidatorSpi * necessary to correctly validate this attribute certificate. * <p> * The attribute certificate issuer must be added to the trusted attribute - * issuers with {@link ExtendedPKIXParameters#setTrustedACIssuers(Set)}. + * issuers with {@link org.bouncycastle.x509.ExtendedPKIXParameters#setTrustedACIssuers(java.util.Set)}. * * @param certPath The certificate path which belongs to the attribute * certificate issuer public key certificate. * @param params The PKIX parameters. * @return A <code>PKIXCertPathValidatorResult</code> of the result of * validating the <code>certPath</code>. - * @throws InvalidAlgorithmParameterException if <code>params</code> is + * @throws java.security.InvalidAlgorithmParameterException if <code>params</code> is * inappropriate for this validator. - * @throws CertPathValidatorException if the verification fails. + * @throws java.security.cert.CertPathValidatorException if the verification fails. */ public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException { - if (!(params instanceof ExtendedPKIXParameters)) + if (!(params instanceof ExtendedPKIXParameters || params instanceof PKIXExtendedParameters)) { throw new InvalidAlgorithmParameterException( "Parameters must be a " + ExtendedPKIXParameters.class.getName() + " instance."); } - ExtendedPKIXParameters pkixParams = (ExtendedPKIXParameters) params; + Set attrCertCheckers = new HashSet(); + Set prohibitedACAttrbiutes = new HashSet(); + Set necessaryACAttributes = new HashSet(); + Set trustedACIssuers = new HashSet(); + + PKIXExtendedParameters paramsPKIX; + if (params instanceof PKIXParameters) + { + PKIXExtendedParameters.Builder paramsPKIXBldr = new PKIXExtendedParameters.Builder((PKIXParameters)params); + + if (params instanceof ExtendedPKIXParameters) + { + ExtendedPKIXParameters extPKIX = (ExtendedPKIXParameters)params; + + paramsPKIXBldr.setUseDeltasEnabled(extPKIX.isUseDeltasEnabled()); + paramsPKIXBldr.setValidityModel(extPKIX.getValidityModel()); + attrCertCheckers = extPKIX.getAttrCertCheckers(); + prohibitedACAttrbiutes = extPKIX.getProhibitedACAttributes(); + necessaryACAttributes = extPKIX.getNecessaryACAttributes(); + } + + paramsPKIX = paramsPKIXBldr.build(); + } + else + { + paramsPKIX = (PKIXExtendedParameters)params; + } - Selector certSelect = pkixParams.getTargetConstraints(); + Selector certSelect = paramsPKIX.getTargetConstraints(); if (!(certSelect instanceof X509AttributeCertStoreSelector)) { throw new InvalidAlgorithmParameterException( @@ -69,31 +107,31 @@ public class PKIXAttrCertPathValidatorSpi + X509AttributeCertStoreSelector.class.getName() + " for " + this.getClass().getName() + " class."); } + X509AttributeCertificate attrCert = ((X509AttributeCertStoreSelector) certSelect) .getAttributeCert(); - CertPath holderCertPath = RFC3281CertPathUtilities.processAttrCert1(attrCert, pkixParams); - CertPathValidatorResult result = RFC3281CertPathUtilities.processAttrCert2(certPath, pkixParams); + CertPath holderCertPath = RFC3281CertPathUtilities.processAttrCert1(attrCert, paramsPKIX); + CertPathValidatorResult result = RFC3281CertPathUtilities.processAttrCert2(certPath, paramsPKIX); X509Certificate issuerCert = (X509Certificate) certPath .getCertificates().get(0); - RFC3281CertPathUtilities.processAttrCert3(issuerCert, pkixParams); - RFC3281CertPathUtilities.processAttrCert4(issuerCert, pkixParams); - RFC3281CertPathUtilities.processAttrCert5(attrCert, pkixParams); + RFC3281CertPathUtilities.processAttrCert3(issuerCert, paramsPKIX); + RFC3281CertPathUtilities.processAttrCert4(issuerCert, trustedACIssuers); + RFC3281CertPathUtilities.processAttrCert5(attrCert, paramsPKIX); // 6 already done in X509AttributeCertStoreSelector - RFC3281CertPathUtilities.processAttrCert7(attrCert, certPath, holderCertPath, pkixParams); - RFC3281CertPathUtilities.additionalChecks(attrCert, pkixParams); + RFC3281CertPathUtilities.processAttrCert7(attrCert, certPath, holderCertPath, paramsPKIX, attrCertCheckers); + RFC3281CertPathUtilities.additionalChecks(attrCert, prohibitedACAttrbiutes, necessaryACAttributes); Date date = null; try { - date = CertPathValidatorUtilities - .getValidCertDateFromValidityModel(pkixParams, null, -1); + date = CertPathValidatorUtilities.getValidCertDateFromValidityModel(paramsPKIX, null, -1); } catch (AnnotatedException e) { throw new ExtCertPathValidatorException( "Could not get validity date from attribute certificate.", e); } - RFC3281CertPathUtilities.checkCRLs(attrCert, pkixParams, issuerCert, date, certPath.getCertificates()); + RFC3281CertPathUtilities.checkCRLs(attrCert, paramsPKIX, issuerCert, date, certPath.getCertificates(), helper); return result; } } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCRLUtil.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCRLUtil.java index c94016d7..f43e185d 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCRLUtil.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCRLUtil.java @@ -2,7 +2,6 @@ package org.bouncycastle.jce.provider; import java.security.cert.CertStore; import java.security.cert.CertStoreException; -import java.security.cert.PKIXParameters; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.util.Collection; @@ -12,14 +11,14 @@ import java.util.Iterator; import java.util.List; import java.util.Set; +import org.bouncycastle.jcajce.PKIXCRLStore; +import org.bouncycastle.jcajce.PKIXCRLStoreSelector; +import org.bouncycastle.util.Store; import org.bouncycastle.util.StoreException; -import org.bouncycastle.x509.ExtendedPKIXParameters; -import org.bouncycastle.x509.X509CRLStoreSelector; -import org.bouncycastle.x509.X509Store; -public class PKIXCRLUtil +class PKIXCRLUtil { - public Set findCRLs(X509CRLStoreSelector crlselect, ExtendedPKIXParameters paramsPKIX, Date currentDate) + public Set findCRLs(PKIXCRLStoreSelector crlselect, Date validityDate, List certStores, List pkixCrlStores) throws AnnotatedException { Set initialSet = new HashSet(); @@ -27,9 +26,8 @@ public class PKIXCRLUtil // get complete CRL(s) try { - initialSet.addAll(findCRLs(crlselect, paramsPKIX.getAdditionalStores())); - initialSet.addAll(findCRLs(crlselect, paramsPKIX.getStores())); - initialSet.addAll(findCRLs(crlselect, paramsPKIX.getCertStores())); + initialSet.addAll(findCRLs(crlselect, pkixCrlStores)); + initialSet.addAll(findCRLs(crlselect, certStores)); } catch (AnnotatedException e) { @@ -37,12 +35,6 @@ public class PKIXCRLUtil } Set finalSet = new HashSet(); - Date validityDate = currentDate; - - if (paramsPKIX.getDate() != null) - { - validityDate = paramsPKIX.getDate(); - } // based on RFC 5280 6.3.3 for (Iterator it = initialSet.iterator(); it.hasNext();) @@ -70,38 +62,20 @@ public class PKIXCRLUtil return finalSet; } - public Set findCRLs(X509CRLStoreSelector crlselect, PKIXParameters paramsPKIX) - throws AnnotatedException - { - Set completeSet = new HashSet(); - - // get complete CRL(s) - try - { - completeSet.addAll(findCRLs(crlselect, paramsPKIX.getCertStores())); - } - catch (AnnotatedException e) - { - throw new AnnotatedException("Exception obtaining complete CRLs.", e); - } - - return completeSet; - } - -/** + /** * Return a Collection of all CRLs found in the X509Store's that are * matching the crlSelect criteriums. * - * @param crlSelect a {@link X509CRLStoreSelector} object that will be used + * @param crlSelect a {@link org.bouncycastle.jcajce.PKIXCRLStoreSelector} object that will be used * to select the CRLs * @param crlStores a List containing only - * {@link org.bouncycastle.x509.X509Store X509Store} objects. + * {@link Store} objects. * These are used to search for CRLs * * @return a Collection of all found {@link java.security.cert.X509CRL X509CRL} objects. May be * empty but never <code>null</code>. */ - private final Collection findCRLs(X509CRLStoreSelector crlSelect, + private final Collection findCRLs(PKIXCRLStoreSelector crlSelect, List crlStores) throws AnnotatedException { Set crls = new HashSet(); @@ -114,9 +88,9 @@ public class PKIXCRLUtil { Object obj = iter.next(); - if (obj instanceof X509Store) + if (obj instanceof Store) { - X509Store store = (X509Store)obj; + Store store = (Store)obj; try { @@ -135,7 +109,7 @@ public class PKIXCRLUtil try { - crls.addAll(store.getCRLs(crlSelect)); + crls.addAll(PKIXCRLStoreSelector.getCRLs(crlSelect, store)); foundValidStore = true; } catch (CertStoreException e) diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCertPathBuilderSpi.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCertPathBuilderSpi.java index 384eb861..b7133951 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCertPathBuilderSpi.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCertPathBuilderSpi.java @@ -6,8 +6,6 @@ import java.security.cert.CertPathBuilderException; import java.security.cert.CertPathBuilderResult; import java.security.cert.CertPathBuilderSpi; import java.security.cert.CertPathParameters; -import java.security.cert.CertPathValidator; -import java.security.cert.CertificateFactory; import java.security.cert.CertificateParsingException; import java.security.cert.PKIXBuilderParameters; import java.security.cert.PKIXCertPathBuilderResult; @@ -19,10 +17,15 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.jcajce.PKIXCertStore; +import org.bouncycastle.jcajce.PKIXCertStoreSelector; +import org.bouncycastle.jcajce.PKIXExtendedBuilderParameters; +import org.bouncycastle.jcajce.PKIXExtendedParameters; +import org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory; import org.bouncycastle.jce.exception.ExtCertPathBuilderException; -import org.bouncycastle.util.Selector; import org.bouncycastle.x509.ExtendedPKIXBuilderParameters; -import org.bouncycastle.x509.X509CertStoreSelector; +import org.bouncycastle.x509.ExtendedPKIXParameters; /** * Implements the PKIX CertPathBuilding algorithm for BouncyCastle. @@ -42,23 +45,45 @@ public class PKIXCertPathBuilderSpi throws CertPathBuilderException, InvalidAlgorithmParameterException { if (!(params instanceof PKIXBuilderParameters) - && !(params instanceof ExtendedPKIXBuilderParameters)) + && !(params instanceof ExtendedPKIXBuilderParameters) + && !(params instanceof PKIXExtendedBuilderParameters)) { throw new InvalidAlgorithmParameterException( "Parameters must be an instance of " + PKIXBuilderParameters.class.getName() + " or " - + ExtendedPKIXBuilderParameters.class.getName() + "."); + + PKIXExtendedBuilderParameters.class.getName() + "."); } - ExtendedPKIXBuilderParameters pkixParams = null; - if (params instanceof ExtendedPKIXBuilderParameters) + PKIXExtendedBuilderParameters paramsPKIX; + if (params instanceof PKIXBuilderParameters) { - pkixParams = (ExtendedPKIXBuilderParameters) params; + PKIXExtendedParameters.Builder paramsPKIXBldr = new PKIXExtendedParameters.Builder((PKIXBuilderParameters)params); + PKIXExtendedBuilderParameters.Builder paramsBldrPKIXBldr; + + if (params instanceof ExtendedPKIXParameters) + { + ExtendedPKIXBuilderParameters extPKIX = (ExtendedPKIXBuilderParameters)params; + + ; + for (Iterator it = extPKIX.getAdditionalStores().iterator(); it.hasNext();) + { + paramsPKIXBldr.addCertificateStore((PKIXCertStore)it.next()); + } + paramsBldrPKIXBldr = new PKIXExtendedBuilderParameters.Builder(paramsPKIXBldr.build()); + + paramsBldrPKIXBldr.addExcludedCerts(extPKIX.getExcludedCerts()); + paramsBldrPKIXBldr.setMaxPathLength(extPKIX.getMaxPathLength()); + } + else + { + paramsBldrPKIXBldr = new PKIXExtendedBuilderParameters.Builder((PKIXBuilderParameters)params); + } + + paramsPKIX = paramsBldrPKIXBldr.build(); } else { - pkixParams = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters - .getInstance((PKIXBuilderParameters) params); + paramsPKIX = (PKIXExtendedBuilderParameters)params; } Collection targets; @@ -68,19 +93,12 @@ public class PKIXCertPathBuilderSpi // search target certificates - Selector certSelect = pkixParams.getTargetConstraints(); - if (!(certSelect instanceof X509CertStoreSelector)) - { - throw new CertPathBuilderException( - "TargetConstraints must be an instance of " - + X509CertStoreSelector.class.getName() + " for " - + this.getClass().getName() + " class."); - } + PKIXCertStoreSelector certSelect = paramsPKIX.getBaseParameters().getTargetConstraints(); try { - targets = CertPathValidatorUtilities.findCertificates((X509CertStoreSelector)certSelect, pkixParams.getStores()); - targets.addAll(CertPathValidatorUtilities.findCertificates((X509CertStoreSelector)certSelect, pkixParams.getCertStores())); + targets = CertPathValidatorUtilities.findCertificates(certSelect, paramsPKIX.getBaseParameters().getCertificateStores()); + targets.addAll(CertPathValidatorUtilities.findCertificates(certSelect, paramsPKIX.getBaseParameters().getCertStores())); } catch (AnnotatedException e) { @@ -102,7 +120,7 @@ public class PKIXCertPathBuilderSpi while (targetIter.hasNext() && result == null) { cert = (X509Certificate) targetIter.next(); - result = build(cert, pkixParams, certPathList); + result = build(cert, paramsPKIX, certPathList); } if (result == null && certPathException != null) @@ -128,7 +146,7 @@ public class PKIXCertPathBuilderSpi private Exception certPathException; protected CertPathBuilderResult build(X509Certificate tbvCert, - ExtendedPKIXBuilderParameters pkixParams, List tbvPath) + PKIXExtendedBuilderParameters pkixParams, List tbvPath) { // If tbvCert is readily present in tbvPath, it indicates having run // into a cycle in the @@ -155,13 +173,13 @@ public class PKIXCertPathBuilderSpi tbvPath.add(tbvCert); CertificateFactory cFact; - CertPathValidator validator; + PKIXCertPathValidatorSpi validator; CertPathBuilderResult builderResult = null; try { - cFact = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); - validator = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME); + cFact = new CertificateFactory(); + validator = new PKIXCertPathValidatorSpi(); } catch (Exception e) { @@ -172,8 +190,8 @@ public class PKIXCertPathBuilderSpi try { // check whether the issuer of <tbvCert> is a TrustAnchor - if (CertPathValidatorUtilities.findTrustAnchor(tbvCert, pkixParams.getTrustAnchors(), - pkixParams.getSigProvider()) != null) + if (CertPathValidatorUtilities.findTrustAnchor(tbvCert, pkixParams.getBaseParameters().getTrustAnchors(), + pkixParams.getBaseParameters().getSigProvider()) != null) { // exception message from possibly later tried certification // chains @@ -181,7 +199,7 @@ public class PKIXCertPathBuilderSpi PKIXCertPathValidatorResult result = null; try { - certPath = cFact.generateCertPath(tbvPath); + certPath = cFact.engineGenerateCertPath(tbvPath); } catch (Exception e) { @@ -192,7 +210,7 @@ public class PKIXCertPathBuilderSpi try { - result = (PKIXCertPathValidatorResult) validator.validate( + result = (PKIXCertPathValidatorResult) validator.engineValidate( certPath, pkixParams); } catch (Exception e) @@ -208,16 +226,21 @@ public class PKIXCertPathBuilderSpi } else { + List stores = new ArrayList(); + + + stores.addAll(pkixParams.getBaseParameters().getCertificateStores()); + // add additional X.509 stores from locations in certificate try { - CertPathValidatorUtilities.addAdditionalStoresFromAltNames( - tbvCert, pkixParams); + stores.addAll(CertPathValidatorUtilities.getAdditionalStoresFromAltNames( + tbvCert.getExtensionValue(Extension.issuerAlternativeName.getId()), pkixParams.getBaseParameters().getNamedCertificateStoreMap())); } catch (CertificateParsingException e) { throw new AnnotatedException( - "No additiontal X.509 stores can be added from certificate locations.", + "No additional X.509 stores can be added from certificate locations.", e); } Collection issuers = new HashSet(); @@ -225,7 +248,7 @@ public class PKIXCertPathBuilderSpi // of the stores try { - issuers.addAll(CertPathValidatorUtilities.findIssuerCerts(tbvCert, pkixParams)); + issuers.addAll(CertPathValidatorUtilities.findIssuerCerts(tbvCert, pkixParams.getBaseParameters().getCertStores(), stores)); } catch (AnnotatedException e) { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCertPathValidatorSpi.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCertPathValidatorSpi.java index f28a02a7..f87b427d 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCertPathValidatorSpi.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXCertPathValidatorSpi.java @@ -18,11 +18,14 @@ import java.util.Iterator; import java.util.List; import java.util.Set; -import javax.security.auth.x500.X500Principal; - import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.DERObjectIdentifier; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.jcajce.PKIXExtendedBuilderParameters; +import org.bouncycastle.jcajce.PKIXExtendedParameters; +import org.bouncycastle.jcajce.util.BCJcaJceHelper; +import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.exception.ExtCertPathValidatorException; import org.bouncycastle.x509.ExtendedPKIXParameters; @@ -33,6 +36,11 @@ import org.bouncycastle.x509.ExtendedPKIXParameters; public class PKIXCertPathValidatorSpi extends CertPathValidatorSpi { + private final JcaJceHelper helper = new BCJcaJceHelper(); + + public PKIXCertPathValidatorSpi() + { + } public CertPathValidatorResult engineValidate( CertPath certPath, @@ -40,21 +48,36 @@ public class PKIXCertPathValidatorSpi throws CertPathValidatorException, InvalidAlgorithmParameterException { - if (!(params instanceof PKIXParameters)) + if (!(params instanceof CertPathParameters)) { throw new InvalidAlgorithmParameterException("Parameters must be a " + PKIXParameters.class.getName() + " instance."); } - ExtendedPKIXParameters paramsPKIX; - if (params instanceof ExtendedPKIXParameters) + PKIXExtendedParameters paramsPKIX; + if (params instanceof PKIXParameters) { - paramsPKIX = (ExtendedPKIXParameters)params; + PKIXExtendedParameters.Builder paramsPKIXBldr = new PKIXExtendedParameters.Builder((PKIXParameters)params); + + if (params instanceof ExtendedPKIXParameters) + { + ExtendedPKIXParameters extPKIX = (ExtendedPKIXParameters)params; + + paramsPKIXBldr.setUseDeltasEnabled(extPKIX.isUseDeltasEnabled()); + paramsPKIXBldr.setValidityModel(extPKIX.getValidityModel()); + } + + paramsPKIX = paramsPKIXBldr.build(); + } + else if (params instanceof PKIXExtendedBuilderParameters) + { + paramsPKIX = ((PKIXExtendedBuilderParameters)params).getBaseParameters(); } else { - paramsPKIX = ExtendedPKIXParameters.getInstance((PKIXParameters)params); + paramsPKIX = (PKIXExtendedParameters)params; } + if (paramsPKIX.getTrustAnchors() == null) { throw new InvalidAlgorithmParameterException( @@ -105,6 +128,9 @@ public class PKIXCertPathValidatorSpi throw new CertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1); } + // RFC 5280 - CRLs must originate from the same trust anchor as the target certificate. + paramsPKIX = new PKIXExtendedParameters.Builder(paramsPKIX).setTrustAnchor(trust).build(); + // // (e), (f), (g) are part of the paramsPKIX object. // @@ -186,19 +212,19 @@ public class PKIXCertPathValidatorSpi // (g), (h), (i), (j) // PublicKey workingPublicKey; - X500Principal workingIssuerName; + X500Name workingIssuerName; X509Certificate sign = trust.getTrustedCert(); try { if (sign != null) { - workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign); + workingIssuerName = PrincipalUtils.getSubjectPrincipal(sign); workingPublicKey = sign.getPublicKey(); } else { - workingIssuerName = new X500Principal(trust.getCAName()); + workingIssuerName = PrincipalUtils.getCA(trust); workingPublicKey = trust.getCAPublicKey(); } } @@ -218,7 +244,7 @@ public class PKIXCertPathValidatorSpi throw new ExtCertPathValidatorException( "Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1); } - DERObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getObjectId(); + ASN1ObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getAlgorithm(); ASN1Encodable workingPublicKeyParameters = workingAlgId.getParameters(); // @@ -272,7 +298,7 @@ public class PKIXCertPathValidatorSpi // RFC3280CertPathUtilities.processCertA(certPath, paramsPKIX, index, workingPublicKey, - verificationAlreadyPerformed, workingIssuerName, sign); + verificationAlreadyPerformed, workingIssuerName, sign, helper); RFC3280CertPathUtilities.processCertBC(certPath, index, nameConstraintValidator); @@ -357,12 +383,12 @@ public class PKIXCertPathValidatorSpi sign = cert; // (c) - workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign); + workingIssuerName = PrincipalUtils.getSubjectPrincipal(sign); // (d) try { - workingPublicKey = CertPathValidatorUtilities.getNextWorkingKey(certPath.getCertificates(), index); + workingPublicKey = CertPathValidatorUtilities.getNextWorkingKey(certPath.getCertificates(), index, helper); } catch (CertPathValidatorException e) { @@ -371,7 +397,7 @@ public class PKIXCertPathValidatorSpi workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey); // (f) - workingPublicKeyAlgorithm = workingAlgId.getObjectId(); + workingPublicKeyAlgorithm = workingAlgId.getAlgorithm(); // (e) workingPublicKeyParameters = workingAlgId.getParameters(); } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXNameConstraintValidator.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXNameConstraintValidator.java index 7ecc4860..07427122 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXNameConstraintValidator.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXNameConstraintValidator.java @@ -635,13 +635,17 @@ public class PKIXNameConstraintValidator private boolean emailIsConstrained(String email, String constraint) { String sub = email.substring(email.indexOf('@') + 1); - // a particular mailbox + // a particular mailbox or @domain if (constraint.indexOf('@') != -1) { if (email.equalsIgnoreCase(constraint)) { return true; } + if (sub.equalsIgnoreCase(constraint.substring(1))) + { + return true; + } } // on particular host else if (!(constraint.charAt(0) == '.')) diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXPolicyNode.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXPolicyNode.java index 34376055..d89e920d 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXPolicyNode.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/PKIXPolicyNode.java @@ -165,4 +165,9 @@ public class PKIXPolicyNode return _node; } + + public void setExpectedPolicies(Set expectedPolicies) + { + this.expectedPolicies = expectedPolicies; + } } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/PrincipalUtils.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/PrincipalUtils.java new file mode 100644 index 00000000..9059079e --- /dev/null +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/PrincipalUtils.java @@ -0,0 +1,53 @@ +package org.bouncycastle.jce.provider; + +import java.security.cert.TrustAnchor; +import java.security.cert.X509CRL; +import java.security.cert.X509CRLEntry; +import java.security.cert.X509Certificate; + +import javax.security.auth.x500.X500Principal; + +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.x509.X509AttributeCertificate; + +class PrincipalUtils +{ + static X500Name getSubjectPrincipal(X509Certificate cert) + { + return X500Name.getInstance(cert.getSubjectX500Principal().getEncoded()); + } + + static X500Name getIssuerPrincipal(X509CRL crl) + { + return X500Name.getInstance(crl.getIssuerX500Principal().getEncoded()); + } + + static X500Name getIssuerPrincipal(X509Certificate cert) + { + return X500Name.getInstance(cert.getIssuerX500Principal().getEncoded()); + } + + static X500Name getCA(TrustAnchor trustAnchor) + { + return X500Name.getInstance(trustAnchor.getCA().getEncoded()); + } + + /** + * Returns the issuer of an attribute certificate or certificate. + * + * @param cert The attribute certificate or certificate. + * @return The issuer as <code>X500Principal</code>. + */ + static X500Name getEncodedIssuerPrincipal( + Object cert) + { + if (cert instanceof X509Certificate) + { + return getIssuerPrincipal((X509Certificate)cert); + } + else + { + return X500Name.getInstance(((X500Principal)((X509AttributeCertificate)cert).getIssuer().getPrincipals()[0]).getEncoded()); + } + } +} diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java index 769edb8a..d67a77ee 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/RFC3280CertPathUtilities.java @@ -5,15 +5,17 @@ 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.X509CRLSelector; +import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.security.cert.X509Extension; +import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; @@ -24,47 +26,51 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Vector; - -import javax.security.auth.x500.X500Principal; +import java.util.TimeZone; 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.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1String; import org.bouncycastle.asn1.ASN1TaggedObject; -import org.bouncycastle.asn1.DERInteger; -import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DERSequence; +import org.bouncycastle.asn1.x500.RDN; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x500.style.BCStyle; 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.Extension; 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.jcajce.PKIXCRLStore; +import org.bouncycastle.jcajce.PKIXCRLStoreSelector; +import org.bouncycastle.jcajce.PKIXCertStoreSelector; +import org.bouncycastle.jcajce.PKIXExtendedBuilderParameters; +import org.bouncycastle.jcajce.PKIXExtendedParameters; +import org.bouncycastle.jcajce.util.JcaJceHelper; +import org.bouncycastle.jce.PrincipalUtil; import org.bouncycastle.jce.exception.ExtCertPathValidatorException; import org.bouncycastle.util.Arrays; -import org.bouncycastle.x509.ExtendedPKIXBuilderParameters; -import org.bouncycastle.x509.ExtendedPKIXParameters; -import org.bouncycastle.x509.X509CRLStoreSelector; -import org.bouncycastle.x509.X509CertStoreSelector; -public class RFC3280CertPathUtilities +class RFC3280CertPathUtilities { private static final PKIXCRLUtil CRL_UTIL = new PKIXCRLUtil(); /** * If the complete CRL includes an issuing distribution point (IDP) CRL * extension check the following: - * <p/> + * <p> * (i) If the distribution point name is present in the IDP CRL extension * and the distribution field is present in the DP, then verify that one of * the names in the IDP matches one of the names in the DP. If the @@ -73,17 +79,17 @@ public class RFC3280CertPathUtilities * names in the IDP matches one of the names in the cRLIssuer field of the * DP. * </p> - * <p/> + * <p> * (ii) If the onlyContainsUserCerts boolean is asserted in the IDP CRL * extension, verify that the certificate does not include the basic * constraints extension with the cA boolean asserted. * </p> - * <p/> + * <p> * (iii) If the onlyContainsCACerts boolean is asserted in the IDP CRL * extension, verify that the certificate includes the basic constraints * extension with the cA boolean asserted. * </p> - * <p/> + * <p> * (iv) Verify that the onlyContainsAttributeCerts boolean is not asserted. * </p> * @@ -131,20 +137,18 @@ public class RFC3280CertPathUtilities ASN1EncodableVector vec = new ASN1EncodableVector(); try { - Enumeration e = ASN1Sequence.getInstance( - ASN1Sequence.fromByteArray(CertPathValidatorUtilities.getIssuerPrincipal(crl) - .getEncoded())).getObjects(); + Enumeration e = ASN1Sequence.getInstance(PrincipalUtils.getIssuerPrincipal(crl)).getObjects(); while (e.hasMoreElements()) { vec.add((ASN1Encodable)e.nextElement()); } } - catch (IOException e) + catch (Exception e) { throw new AnnotatedException("Could not read CRL issuer.", e); } vec.add(dpName.getName()); - names.add(new GeneralName(X509Name.getInstance(new DERSequence(vec)))); + names.add(new GeneralName(X500Name.getInstance(new DERSequence(vec)))); } boolean matches = false; // verify that one of the names in the IDP matches one @@ -168,11 +172,10 @@ public class RFC3280CertPathUtilities genNames = new GeneralName[1]; try { - genNames[0] = new GeneralName(new X509Name( - (ASN1Sequence)ASN1Sequence.fromByteArray(CertPathValidatorUtilities - .getEncodedIssuerPrincipal(cert).getEncoded()))); + genNames[0] = new GeneralName(X500Name.getInstance(PrincipalUtils + .getEncodedIssuerPrincipal(cert).getEncoded())); } - catch (IOException e) + catch (Exception e) { throw new AnnotatedException("Could not read certificate issuer.", e); } @@ -186,7 +189,7 @@ public class RFC3280CertPathUtilities vec.add((ASN1Encodable)e.nextElement()); } vec.add(dpName.getName()); - genNames[j] = new GeneralName(new X509Name(new DERSequence(vec))); + genNames[j] = new GeneralName(X500Name.getInstance(new DERSequence(vec))); } } if (genNames != null) @@ -294,7 +297,16 @@ public class RFC3280CertPathUtilities isIndirect = true; } } - byte[] issuerBytes = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded(); + byte[] issuerBytes; + + try + { + issuerBytes = PrincipalUtils.getIssuerPrincipal(crl).getEncoded(); + } + catch (IOException e) + { + throw new AnnotatedException("Exception encoding CRL issuer: " + e.getMessage(), e); + } boolean matchIssuer = false; if (dp.getCRLIssuer() != null) @@ -329,8 +341,8 @@ public class RFC3280CertPathUtilities } else { - if (CertPathValidatorUtilities.getIssuerPrincipal(crl).equals( - CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert))) + if (PrincipalUtils.getIssuerPrincipal(crl).equals( + PrincipalUtils.getEncodedIssuerPrincipal(cert))) { matchIssuer = true; } @@ -375,33 +387,33 @@ public class RFC3280CertPathUtilities } - public static final String CERTIFICATE_POLICIES = X509Extensions.CertificatePolicies.getId(); + public static final String CERTIFICATE_POLICIES = Extension.certificatePolicies.getId(); - public static final String POLICY_MAPPINGS = X509Extensions.PolicyMappings.getId(); + public static final String POLICY_MAPPINGS = Extension.policyMappings.getId(); - public static final String INHIBIT_ANY_POLICY = X509Extensions.InhibitAnyPolicy.getId(); + public static final String INHIBIT_ANY_POLICY = Extension.inhibitAnyPolicy.getId(); - public static final String ISSUING_DISTRIBUTION_POINT = X509Extensions.IssuingDistributionPoint.getId(); + public static final String ISSUING_DISTRIBUTION_POINT = Extension.issuingDistributionPoint.getId(); - public static final String FRESHEST_CRL = X509Extensions.FreshestCRL.getId(); + public static final String FRESHEST_CRL = Extension.freshestCRL.getId(); - public static final String DELTA_CRL_INDICATOR = X509Extensions.DeltaCRLIndicator.getId(); + public static final String DELTA_CRL_INDICATOR = Extension.deltaCRLIndicator.getId(); - public static final String POLICY_CONSTRAINTS = X509Extensions.PolicyConstraints.getId(); + public static final String POLICY_CONSTRAINTS = Extension.policyConstraints.getId(); - public static final String BASIC_CONSTRAINTS = X509Extensions.BasicConstraints.getId(); + public static final String BASIC_CONSTRAINTS = Extension.basicConstraints.getId(); - public static final String CRL_DISTRIBUTION_POINTS = X509Extensions.CRLDistributionPoints.getId(); + public static final String CRL_DISTRIBUTION_POINTS = Extension.cRLDistributionPoints.getId(); - public static final String SUBJECT_ALTERNATIVE_NAME = X509Extensions.SubjectAlternativeName.getId(); + public static final String SUBJECT_ALTERNATIVE_NAME = Extension.subjectAlternativeName.getId(); - public static final String NAME_CONSTRAINTS = X509Extensions.NameConstraints.getId(); + public static final String NAME_CONSTRAINTS = Extension.nameConstraints.getId(); - public static final String AUTHORITY_KEY_IDENTIFIER = X509Extensions.AuthorityKeyIdentifier.getId(); + public static final String AUTHORITY_KEY_IDENTIFIER = Extension.authorityKeyIdentifier.getId(); - public static final String KEY_USAGE = X509Extensions.KeyUsage.getId(); + public static final String KEY_USAGE = Extension.keyUsage.getId(); - public static final String CRL_NUMBER = X509Extensions.CRLNumber.getId(); + public static final String CRL_NUMBER = Extension.cRLNumber.getId(); public static final String ANY_POLICY = "2.5.29.32.0"; @@ -436,18 +448,19 @@ public class RFC3280CertPathUtilities Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, - ExtendedPKIXParameters paramsPKIX, - List certPathCerts) + PKIXExtendedParameters paramsPKIX, + List certPathCerts, + JcaJceHelper helper) throws AnnotatedException { // (f) // get issuer from CRL - X509CertStoreSelector selector = new X509CertStoreSelector(); + X509CertSelector certSelector = new X509CertSelector(); try { - byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded(); - selector.setSubject(issuerPrincipal); + byte[] issuerPrincipal = PrincipalUtils.getIssuerPrincipal(crl).getEncoded(); + certSelector.setSubject(issuerPrincipal); } catch (IOException e) { @@ -455,12 +468,13 @@ public class RFC3280CertPathUtilities "Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e); } + PKIXCertStoreSelector selector = new PKIXCertStoreSelector.Builder(certSelector).build(); + // get CRL signing certs Collection coll; try { - coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores()); - coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores())); + coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertificateStores()); coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores())); } catch (AnnotatedException e) @@ -491,13 +505,13 @@ public class RFC3280CertPathUtilities } try { - CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME); - selector = new X509CertStoreSelector(); - selector.setCertificate(signingCert); - ExtendedPKIXParameters temp = (ExtendedPKIXParameters)paramsPKIX.clone(); - temp.setTargetCertConstraints(selector); - ExtendedPKIXBuilderParameters params = (ExtendedPKIXBuilderParameters)ExtendedPKIXBuilderParameters - .getInstance(temp); + PKIXCertPathBuilderSpi builder = new PKIXCertPathBuilderSpi(); + X509CertSelector tmpCertSelector = new X509CertSelector(); + tmpCertSelector.setCertificate(signingCert); + + PKIXExtendedParameters.Builder paramsBuilder = new PKIXExtendedParameters.Builder(paramsPKIX) + .setTargetConstraints(new PKIXCertStoreSelector.Builder(tmpCertSelector).build()); + /* * if signingCert is placed not higher on the cert path a * dependency loop results. CRL for cert is checked, but @@ -509,19 +523,22 @@ public class RFC3280CertPathUtilities */ if (certPathCerts.contains(signingCert)) { - params.setRevocationEnabled(false); + paramsBuilder.setRevocationEnabled(false); } else { - params.setRevocationEnabled(true); + paramsBuilder.setRevocationEnabled(true); } - List certs = builder.build(params).getCertPath().getCertificates(); + + PKIXExtendedBuilderParameters extParams = new PKIXExtendedBuilderParameters.Builder(paramsBuilder.build()).build(); + + List certs = builder.engineBuild(extParams).getCertPath().getCertificates(); validCerts.add(signingCert); - validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0)); + validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0, helper)); } catch (CertPathBuilderException e) { - throw new AnnotatedException("Internal error.", e); + throw new AnnotatedException("CertPath for CRL signer failed to validate.", e); } catch (CertPathValidatorException e) { @@ -529,7 +546,7 @@ public class RFC3280CertPathUtilities } catch (Exception e) { - throw new RuntimeException(e.getMessage()); + throw new AnnotatedException(e.getMessage()); } } @@ -616,7 +633,7 @@ public class RFC3280CertPathUtilities protected static Set processCRLA1i( Date currentDate, - ExtendedPKIXParameters paramsPKIX, + PKIXExtendedParameters paramsPKIX, X509Certificate cert, X509CRL crl) throws AnnotatedException @@ -648,19 +665,24 @@ public class RFC3280CertPathUtilities } if (freshestCRL != null) { + List crlStores = new ArrayList(); + + crlStores.addAll(paramsPKIX.getCRLStores()); + try { - CertPathValidatorUtilities.addAdditionalStoresFromCRLDistributionPoint(freshestCRL, paramsPKIX); + crlStores.addAll(CertPathValidatorUtilities.getAdditionalStoresFromCRLDistributionPoint(freshestCRL, paramsPKIX.getNamedCRLStoreMap())); } catch (AnnotatedException e) { throw new AnnotatedException( "No new delta CRL locations could be added from Freshest CRL extension.", e); } + // get delta CRL(s) try { - set.addAll(CertPathValidatorUtilities.getDeltaCRLs(currentDate, paramsPKIX, crl)); + set.addAll(CertPathValidatorUtilities.getDeltaCRLs(currentDate, crl, paramsPKIX.getCertStores(), crlStores)); } catch (AnnotatedException e) { @@ -673,33 +695,41 @@ public class RFC3280CertPathUtilities protected static Set[] processCRLA1ii( Date currentDate, - ExtendedPKIXParameters paramsPKIX, + PKIXExtendedParameters paramsPKIX, X509Certificate cert, X509CRL crl) throws AnnotatedException { Set deltaSet = new HashSet(); - X509CRLStoreSelector crlselect = new X509CRLStoreSelector(); + X509CRLSelector crlselect = new X509CRLSelector(); crlselect.setCertificateChecking(cert); try { - crlselect.addIssuerName(crl.getIssuerX500Principal().getEncoded()); + crlselect.addIssuerName(PrincipalUtils.getIssuerPrincipal(crl).getEncoded()); } catch (IOException e) { throw new AnnotatedException("Cannot extract issuer from CRL." + e, e); } - crlselect.setCompleteCRLEnabled(true); - Set completeSet = CRL_UTIL.findCRLs(crlselect, paramsPKIX, currentDate); + PKIXCRLStoreSelector extSelect = new PKIXCRLStoreSelector.Builder(crlselect).setCompleteCRLEnabled(true).build(); + + Date validityDate = currentDate; + + if (paramsPKIX.getDate() != null) + { + validityDate = paramsPKIX.getDate(); + } + + Set completeSet = CRL_UTIL.findCRLs(extSelect, validityDate, paramsPKIX.getCertStores(), paramsPKIX.getCRLStores()); if (paramsPKIX.isUseDeltasEnabled()) { // get delta CRL(s) try { - deltaSet.addAll(CertPathValidatorUtilities.getDeltaCRLs(currentDate, paramsPKIX, crl)); + deltaSet.addAll(CertPathValidatorUtilities.getDeltaCRLs(validityDate, crl, paramsPKIX.getCertStores(), paramsPKIX.getCRLStores())); } catch (AnnotatedException e) { @@ -725,7 +755,7 @@ public class RFC3280CertPathUtilities protected static void processCRLC( X509CRL deltaCRL, X509CRL completeCRL, - ExtendedPKIXParameters pkixParams) + PKIXExtendedParameters pkixParams) throws AnnotatedException { if (deltaCRL == null) @@ -746,7 +776,7 @@ public class RFC3280CertPathUtilities if (pkixParams.isUseDeltasEnabled()) { // (c) (1) - if (!deltaCRL.getIssuerX500Principal().equals(completeCRL.getIssuerX500Principal())) + if (!PrincipalUtils.getIssuerPrincipal(deltaCRL).equals(PrincipalUtils.getIssuerPrincipal(completeCRL))) { throw new AnnotatedException("Complete CRL issuer does not match delta CRL issuer."); } @@ -833,7 +863,7 @@ public class RFC3280CertPathUtilities X509CRL deltacrl, Object cert, CertStatus certStatus, - ExtendedPKIXParameters pkixParams) + PKIXExtendedParameters pkixParams) throws AnnotatedException { if (pkixParams.isUseDeltasEnabled() && deltacrl != null) @@ -891,8 +921,8 @@ public class RFC3280CertPathUtilities for (int j = 0; j < mappings.size(); j++) { ASN1Sequence mapping = (ASN1Sequence)mappings.getObjectAt(j); - String id_p = ((DERObjectIdentifier)mapping.getObjectAt(0)).getId(); - String sd_p = ((DERObjectIdentifier)mapping.getObjectAt(1)).getId(); + String id_p = ((ASN1ObjectIdentifier)mapping.getObjectAt(0)).getId(); + String sd_p = ((ASN1ObjectIdentifier)mapping.getObjectAt(1)).getId(); Set tmp; if (!m_idp.containsKey(id_p)) @@ -1070,14 +1100,14 @@ public class RFC3280CertPathUtilities for (int j = 0; j < mappings.size(); j++) { - DERObjectIdentifier issuerDomainPolicy = null; - DERObjectIdentifier subjectDomainPolicy = null; + ASN1ObjectIdentifier issuerDomainPolicy = null; + ASN1ObjectIdentifier subjectDomainPolicy = null; try { ASN1Sequence mapping = DERSequence.getInstance(mappings.getObjectAt(j)); - issuerDomainPolicy = DERObjectIdentifier.getInstance(mapping.getObjectAt(0)); - subjectDomainPolicy = DERObjectIdentifier.getInstance(mapping.getObjectAt(1)); + issuerDomainPolicy = ASN1ObjectIdentifier.getInstance(mapping.getObjectAt(0)); + subjectDomainPolicy = ASN1ObjectIdentifier.getInstance(mapping.getObjectAt(1)); } catch (Exception e) { @@ -1162,13 +1192,12 @@ public class RFC3280CertPathUtilities // if (!(CertPathValidatorUtilities.isSelfIssued(cert) && (i < n))) { - X500Principal principal = CertPathValidatorUtilities.getSubjectPrincipal(cert); - ASN1InputStream aIn = new ASN1InputStream(principal.getEncoded()); + X500Name principal = PrincipalUtils.getSubjectPrincipal(cert); ASN1Sequence dns; try { - dns = DERSequence.getInstance(aIn.readObject()); + dns = DERSequence.getInstance(principal.getEncoded()); } catch (Exception e) { @@ -1198,10 +1227,11 @@ public class RFC3280CertPathUtilities throw new CertPathValidatorException("Subject alternative name extension could not be decoded.", e, certPath, index); } - Vector emails = new X509Name(dns).getValues(X509Name.EmailAddress); - for (Enumeration e = emails.elements(); e.hasMoreElements();) + RDN[] emails = X500Name.getInstance(dns).getRDNs(BCStyle.EmailAddress); + for (int eI = 0; eI != emails.length; eI++) { - String email = (String)e.nextElement(); + // TODO: this should take into account multi-valued RDNs + String email = ((ASN1String)emails[eI].getFirst().getValue()).getString(); GeneralName emailAsGeneralName = new GeneralName(GeneralName.rfc822Name, email); try { @@ -1284,7 +1314,7 @@ public class RFC3280CertPathUtilities while (e.hasMoreElements()) { PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement()); - DERObjectIdentifier pOid = pInfo.getPolicyIdentifier(); + ASN1ObjectIdentifier pOid = pInfo.getPolicyIdentifier(); pols.add(pOid.getId()); @@ -1363,9 +1393,9 @@ public class RFC3280CertPathUtilities { _policy = (String)_tmp; } - else if (_tmp instanceof DERObjectIdentifier) + else if (_tmp instanceof ASN1ObjectIdentifier) { - _policy = ((DERObjectIdentifier)_tmp).getId(); + _policy = ((ASN1ObjectIdentifier)_tmp).getId(); } else { @@ -1448,12 +1478,13 @@ public class RFC3280CertPathUtilities protected static void processCertA( CertPath certPath, - ExtendedPKIXParameters paramsPKIX, + PKIXExtendedParameters paramsPKIX, int index, PublicKey workingPublicKey, boolean verificationAlreadyPerformed, - X500Principal workingIssuerName, - X509Certificate sign) + X500Name workingIssuerName, + X509Certificate sign, + JcaJceHelper helper) throws ExtCertPathValidatorException { List certs = certPath.getCertificates(); @@ -1504,7 +1535,7 @@ public class RFC3280CertPathUtilities try { checkCRLs(paramsPKIX, cert, CertPathValidatorUtilities.getValidCertDateFromValidityModel(paramsPKIX, - certPath, index), sign, workingPublicKey, certs); + certPath, index), sign, workingPublicKey, certs, helper); } catch (AnnotatedException e) { @@ -1520,9 +1551,9 @@ public class RFC3280CertPathUtilities // // (a) (4) name chaining // - if (!CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert).equals(workingIssuerName)) + if (!PrincipalUtils.getEncodedIssuerPrincipal(cert).equals(workingIssuerName)) { - throw new ExtCertPathValidatorException("IssuerName(" + CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert) + throw new ExtCertPathValidatorException("IssuerName(" + PrincipalUtils.getEncodedIssuerPrincipal(cert) + ") does not match SubjectName(" + workingIssuerName + ") of signing certificate.", null, certPath, index); } @@ -1565,7 +1596,7 @@ public class RFC3280CertPathUtilities ASN1TaggedObject constraint = ASN1TaggedObject.getInstance(policyConstraints.nextElement()); if (constraint.getTagNo() == 0) { - tmpInt = DERInteger.getInstance(constraint, false).getValue().intValue(); + tmpInt = ASN1Integer.getInstance(constraint, false).getValue().intValue(); if (tmpInt < explicitPolicy) { return tmpInt; @@ -1619,7 +1650,7 @@ public class RFC3280CertPathUtilities ASN1TaggedObject constraint = ASN1TaggedObject.getInstance(policyConstraints.nextElement()); if (constraint.getTagNo() == 1) { - tmpInt = DERInteger.getInstance(constraint, false).getValue().intValue(); + tmpInt = ASN1Integer.getInstance(constraint, false).getValue().intValue(); if (tmpInt < policyMapping) { return tmpInt; @@ -1723,14 +1754,15 @@ public class RFC3280CertPathUtilities */ private static void checkCRL( DistributionPoint dp, - ExtendedPKIXParameters paramsPKIX, + PKIXExtendedParameters paramsPKIX, X509Certificate cert, Date validDate, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, CertStatus certStatus, ReasonsMask reasonMask, - List certPathCerts) + List certPathCerts, + JcaJceHelper helper) throws AnnotatedException { Date currentDate = new Date(System.currentTimeMillis()); @@ -1774,16 +1806,23 @@ public class RFC3280CertPathUtilities // (f) Set keys = RFC3280CertPathUtilities.processCRLF(crl, cert, defaultCRLSignCert, defaultCRLSignKey, - paramsPKIX, certPathCerts); + paramsPKIX, certPathCerts, helper); // (g) PublicKey key = RFC3280CertPathUtilities.processCRLG(crl, keys); X509CRL deltaCRL = null; + Date validityDate = currentDate; + + if (paramsPKIX.getDate() != null) + { + validityDate = paramsPKIX.getDate(); + } + if (paramsPKIX.isUseDeltasEnabled()) { // get delta CRLs - Set deltaCRLs = CertPathValidatorUtilities.getDeltaCRLs(currentDate, paramsPKIX, crl); + Set deltaCRLs = CertPathValidatorUtilities.getDeltaCRLs(validityDate, crl, paramsPKIX.getCertStores(), paramsPKIX.getCRLStores()); // we only want one valid delta CRL // (h) deltaCRL = RFC3280CertPathUtilities.processCRLH(deltaCRLs, key); @@ -1802,7 +1841,7 @@ public class RFC3280CertPathUtilities * the CRL validity time */ - if (paramsPKIX.getValidityModel() != ExtendedPKIXParameters.CHAIN_VALIDITY_MODEL) + if (paramsPKIX.getValidityModel() != PKIXExtendedParameters.CHAIN_VALIDITY_MODEL) { /* * if a certificate has expired, but was revoked, it is not @@ -1842,8 +1881,8 @@ public class RFC3280CertPathUtilities if (criticalExtensions != null) { criticalExtensions = new HashSet(criticalExtensions); - criticalExtensions.remove(X509Extensions.IssuingDistributionPoint.getId()); - criticalExtensions.remove(X509Extensions.DeltaCRLIndicator.getId()); + criticalExtensions.remove(Extension.issuingDistributionPoint.getId()); + criticalExtensions.remove(Extension.deltaCRLIndicator.getId()); if (!criticalExtensions.isEmpty()) { @@ -1857,8 +1896,8 @@ public class RFC3280CertPathUtilities if (criticalExtensions != null) { criticalExtensions = new HashSet(criticalExtensions); - criticalExtensions.remove(X509Extensions.IssuingDistributionPoint.getId()); - criticalExtensions.remove(X509Extensions.DeltaCRLIndicator.getId()); + criticalExtensions.remove(Extension.issuingDistributionPoint.getId()); + criticalExtensions.remove(Extension.deltaCRLIndicator.getId()); if (!criticalExtensions.isEmpty()) { throw new AnnotatedException("Delta CRL contains unsupported critical extension."); @@ -1893,12 +1932,13 @@ public class RFC3280CertPathUtilities * or some error occurs. */ protected static void checkCRLs( - ExtendedPKIXParameters paramsPKIX, + PKIXExtendedParameters paramsPKIX, X509Certificate cert, Date validDate, X509Certificate sign, PublicKey workingPublicKey, - List certPathCerts) + List certPathCerts, + JcaJceHelper helper) throws AnnotatedException { AnnotatedException lastException = null; @@ -1912,9 +1952,15 @@ public class RFC3280CertPathUtilities { throw new AnnotatedException("CRL distribution point extension could not be read.", e); } + + PKIXExtendedParameters.Builder paramsBldr = new PKIXExtendedParameters.Builder(paramsPKIX); try { - CertPathValidatorUtilities.addAdditionalStoresFromCRLDistributionPoint(crldp, paramsPKIX); + List extras = CertPathValidatorUtilities.getAdditionalStoresFromCRLDistributionPoint(crldp, paramsPKIX.getNamedCRLStoreMap()); + for (Iterator it = extras.iterator(); it.hasNext();) + { + paramsBldr.addCRLStore((PKIXCRLStore)it.next()); + } } catch (AnnotatedException e) { @@ -1923,6 +1969,7 @@ public class RFC3280CertPathUtilities } CertStatus certStatus = new CertStatus(); ReasonsMask reasonsMask = new ReasonsMask(); + PKIXExtendedParameters finalParams = paramsBldr.build(); boolean validCrlFound = false; // for each distribution point @@ -1941,10 +1988,9 @@ public class RFC3280CertPathUtilities { for (int i = 0; i < dps.length && certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons(); i++) { - ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters)paramsPKIX.clone(); try { - checkCRL(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts); + checkCRL(dps[i], finalParams, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts, helper); validCrlFound = true; } catch (AnnotatedException e) @@ -1973,7 +2019,7 @@ public class RFC3280CertPathUtilities ASN1Primitive issuer = null; try { - issuer = new ASN1InputStream(CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert).getEncoded()) + issuer = new ASN1InputStream(PrincipalUtils.getEncodedIssuerPrincipal(cert).getEncoded()) .readObject(); } catch (Exception e) @@ -1982,9 +2028,9 @@ public class RFC3280CertPathUtilities } DistributionPoint dp = new DistributionPoint(new DistributionPointName(0, new GeneralNames( new GeneralName(GeneralName.directoryName, issuer))), null, null); - ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters)paramsPKIX.clone(); + PKIXExtendedParameters paramsPKIXClone = (PKIXExtendedParameters)paramsPKIX.clone(); checkCRL(dp, paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, - certPathCerts); + certPathCerts, helper); validCrlFound = true; } catch (AnnotatedException e) @@ -2004,7 +2050,9 @@ public class RFC3280CertPathUtilities } if (certStatus.getCertStatus() != CertStatus.UNREVOKED) { - String message = "Certificate revocation after " + certStatus.getRevocationDate(); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); + df.setTimeZone(TimeZone.getTimeZone("UTC")); + String message = "Certificate revocation after " + df.format(certStatus.getRevocationDate()); message += ", reason: " + crlReasons[certStatus.getCertStatus()]; throw new AnnotatedException(message); } @@ -2029,10 +2077,10 @@ public class RFC3280CertPathUtilities // // (j) // - DERInteger iap = null; + ASN1Integer iap = null; try { - iap = DERInteger.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, + iap = ASN1Integer.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.INHIBIT_ANY_POLICY)); } catch (Exception e) @@ -2335,7 +2383,7 @@ public class RFC3280CertPathUtilities case 0: try { - tmpInt = DERInteger.getInstance(constraint, false).getValue().intValue(); + tmpInt = ASN1Integer.getInstance(constraint, false).getValue().intValue(); } catch (Exception e) { @@ -2387,7 +2435,7 @@ public class RFC3280CertPathUtilities protected static PKIXPolicyNode wrapupCertG( CertPath certPath, - ExtendedPKIXParameters paramsPKIX, + PKIXExtendedParameters paramsPKIX, Set userInitialPolicySet, int index, List[] policyNodes, diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/RFC3281CertPathUtilities.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/RFC3281CertPathUtilities.java index 19dbae1d..b5153062 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/RFC3281CertPathUtilities.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/RFC3281CertPathUtilities.java @@ -5,6 +5,7 @@ import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Principal; +import java.security.Provider; import java.security.PublicKey; import java.security.cert.CertPath; import java.security.cert.CertPathBuilder; @@ -13,11 +14,14 @@ import java.security.cert.CertPathBuilderResult; import java.security.cert.CertPathValidator; import java.security.cert.CertPathValidatorException; import java.security.cert.CertPathValidatorResult; +import java.security.cert.CertSelector; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.TrustAnchor; import java.security.cert.X509CRL; +import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; +import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; @@ -36,9 +40,13 @@ import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.TargetInformation; import org.bouncycastle.asn1.x509.X509Extensions; +import org.bouncycastle.jcajce.PKIXCRLStore; +import org.bouncycastle.jcajce.PKIXCertStoreSelector; +import org.bouncycastle.jcajce.PKIXExtendedBuilderParameters; +import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.exception.ExtCertPathValidatorException; import org.bouncycastle.x509.ExtendedPKIXBuilderParameters; -import org.bouncycastle.x509.ExtendedPKIXParameters; +import org.bouncycastle.jcajce.PKIXExtendedParameters; import org.bouncycastle.x509.PKIXAttrCertChecker; import org.bouncycastle.x509.X509AttributeCertificate; import org.bouncycastle.x509.X509CertStoreSelector; @@ -60,7 +68,7 @@ class RFC3281CertPathUtilities protected static void processAttrCert7(X509AttributeCertificate attrCert, CertPath certPath, CertPath holderCertPath, - ExtendedPKIXParameters pkixParams) throws CertPathValidatorException + PKIXExtendedParameters pkixParams, Set attrCertCheckers) throws CertPathValidatorException { // TODO: // AA Controls @@ -90,7 +98,7 @@ class RFC3281CertPathUtilities } } set.remove(TARGET_INFORMATION); - for (Iterator it = pkixParams.getAttrCertCheckers().iterator(); it + for (Iterator it = attrCertCheckers.iterator(); it .hasNext();) { ((PKIXAttrCertChecker) it.next()).check(attrCert, certPath, @@ -120,8 +128,8 @@ class RFC3281CertPathUtilities * status cannot be checked or some error occurs. */ protected static void checkCRLs(X509AttributeCertificate attrCert, - ExtendedPKIXParameters paramsPKIX, X509Certificate issuerCert, - Date validDate, List certPathCerts) throws CertPathValidatorException + PKIXExtendedParameters paramsPKIX, X509Certificate issuerCert, + Date validDate, List certPathCerts, JcaJceHelper helper) throws CertPathValidatorException { if (paramsPKIX.isRevocationEnabled()) { @@ -140,11 +148,12 @@ class RFC3281CertPathUtilities "CRL distribution point extension could not be read.", e); } + + List crlStores = new ArrayList(); + try { - CertPathValidatorUtilities - .addAdditionalStoresFromCRLDistributionPoint(crldp, - paramsPKIX); + crlStores.addAll(CertPathValidatorUtilities.getAdditionalStoresFromCRLDistributionPoint(crldp, paramsPKIX.getNamedCRLStoreMap())); } catch (AnnotatedException e) { @@ -152,6 +161,16 @@ class RFC3281CertPathUtilities "No additional CRL locations could be decoded from CRL distribution point extension.", e); } + + PKIXExtendedParameters.Builder bldr = new PKIXExtendedParameters.Builder(paramsPKIX); + + for (Iterator it = crlStores.iterator(); it.hasNext(); ) + { + bldr.addCRLStore((PKIXCRLStore)crlStores); + } + + paramsPKIX = bldr.build(); + CertStatus certStatus = new CertStatus(); ReasonsMask reasonsMask = new ReasonsMask(); @@ -176,11 +195,12 @@ class RFC3281CertPathUtilities && certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons(); i++) { - ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters) paramsPKIX - .clone(); + PKIXExtendedParameters paramsPKIXClone = (PKIXExtendedParameters)paramsPKIX + .clone(); + checkCRL(dps[i], attrCert, paramsPKIXClone, validDate, issuerCert, certStatus, reasonsMask, - certPathCerts); + certPathCerts, helper); validCrlFound = true; } } @@ -226,10 +246,10 @@ class RFC3281CertPathUtilities new DistributionPointName(0, new GeneralNames( new GeneralName(GeneralName.directoryName, issuer))), null, null); - ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters) paramsPKIX + PKIXExtendedParameters paramsPKIXClone = (PKIXExtendedParameters) paramsPKIX .clone(); checkCRL(dp, attrCert, paramsPKIXClone, validDate, - issuerCert, certStatus, reasonsMask, certPathCerts); + issuerCert, certStatus, reasonsMask, certPathCerts, helper); validCrlFound = true; } catch (AnnotatedException e) @@ -278,10 +298,10 @@ class RFC3281CertPathUtilities } protected static void additionalChecks(X509AttributeCertificate attrCert, - ExtendedPKIXParameters pkixParams) throws CertPathValidatorException + Set prohibitedACAttributes, Set necessaryACAttributes) throws CertPathValidatorException { // 1 - for (Iterator it = pkixParams.getProhibitedACAttributes().iterator(); it + for (Iterator it = prohibitedACAttributes.iterator(); it .hasNext();) { String oid = (String) it.next(); @@ -292,7 +312,7 @@ class RFC3281CertPathUtilities + oid + "."); } } - for (Iterator it = pkixParams.getNecessaryACAttributes().iterator(); it + for (Iterator it = necessaryACAttributes.iterator(); it .hasNext();) { String oid = (String) it.next(); @@ -306,7 +326,7 @@ class RFC3281CertPathUtilities } protected static void processAttrCert5(X509AttributeCertificate attrCert, - ExtendedPKIXParameters pkixParams) throws CertPathValidatorException + PKIXExtendedParameters pkixParams) throws CertPathValidatorException { try { @@ -326,9 +346,9 @@ class RFC3281CertPathUtilities } protected static void processAttrCert4(X509Certificate acIssuerCert, - ExtendedPKIXParameters pkixParams) throws CertPathValidatorException + Set trustedACIssuers) throws CertPathValidatorException { - Set set = pkixParams.getTrustedACIssuers(); + Set set = trustedACIssuers; boolean trusted = false; for (Iterator it = set.iterator(); it.hasNext();) { @@ -348,7 +368,7 @@ class RFC3281CertPathUtilities } protected static void processAttrCert3(X509Certificate acIssuerCert, - ExtendedPKIXParameters pkixParams) throws CertPathValidatorException + PKIXExtendedParameters pkixParams) throws CertPathValidatorException { if (acIssuerCert.getKeyUsage() != null && (!acIssuerCert.getKeyUsage()[0] && !acIssuerCert.getKeyUsage()[1])) @@ -364,7 +384,7 @@ class RFC3281CertPathUtilities } protected static CertPathValidatorResult processAttrCert2( - CertPath certPath, ExtendedPKIXParameters pkixParams) + CertPath certPath, PKIXExtendedParameters pkixParams) throws CertPathValidatorException { CertPathValidator validator = null; @@ -417,7 +437,7 @@ class RFC3281CertPathUtilities * </ul> */ protected static CertPath processAttrCert1( - X509AttributeCertificate attrCert, ExtendedPKIXParameters pkixParams) + X509AttributeCertificate attrCert, PKIXExtendedParameters pkixParams) throws CertPathValidatorException { CertPathBuilderResult result = null; @@ -425,7 +445,7 @@ class RFC3281CertPathUtilities Set holderPKCs = new HashSet(); if (attrCert.getHolder().getIssuer() != null) { - X509CertStoreSelector selector = new X509CertStoreSelector(); + X509CertSelector selector = new X509CertSelector(); selector.setSerialNumber(attrCert.getHolder().getSerialNumber()); Principal[] principals = attrCert.getHolder().getIssuer(); for (int i = 0; i < principals.length; i++) @@ -438,7 +458,7 @@ class RFC3281CertPathUtilities .getEncoded()); } holderPKCs.addAll(CertPathValidatorUtilities - .findCertificates(selector, pkixParams.getStores())); + .findCertificates(new PKIXCertStoreSelector.Builder(selector).build(), pkixParams.getCertStores())); } catch (AnnotatedException e) { @@ -472,7 +492,7 @@ class RFC3281CertPathUtilities .getEncoded()); } holderPKCs.addAll(CertPathValidatorUtilities - .findCertificates(selector, pkixParams.getStores())); + .findCertificates(new PKIXCertStoreSelector.Builder(selector).build(), pkixParams.getCertStores())); } catch (AnnotatedException e) { @@ -493,14 +513,14 @@ class RFC3281CertPathUtilities } } // verify cert paths for PKCs - ExtendedPKIXBuilderParameters params = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters - .getInstance(pkixParams); + PKIXExtendedParameters.Builder paramsBldr = new PKIXExtendedParameters.Builder(pkixParams); + CertPathValidatorException lastException = null; for (Iterator it = holderPKCs.iterator(); it.hasNext();) { X509CertStoreSelector selector = new X509CertStoreSelector(); selector.setCertificate((X509Certificate) it.next()); - params.setTargetConstraints(selector); + paramsBldr.setTargetConstraints(new PKIXCertStoreSelector.Builder(selector).build()); CertPathBuilder builder = null; try { @@ -518,8 +538,7 @@ class RFC3281CertPathUtilities } try { - result = builder.build(ExtendedPKIXBuilderParameters - .getInstance(params)); + result = builder.build(new PKIXExtendedBuilderParameters.Builder(paramsBldr.build()).build()); } catch (CertPathBuilderException e) { @@ -558,9 +577,9 @@ class RFC3281CertPathUtilities * cannot be checked or some error occurs. */ private static void checkCRL(DistributionPoint dp, - X509AttributeCertificate attrCert, ExtendedPKIXParameters paramsPKIX, + X509AttributeCertificate attrCert, PKIXExtendedParameters paramsPKIX, Date validDate, X509Certificate issuerCert, CertStatus certStatus, - ReasonsMask reasonMask, List certPathCerts) throws AnnotatedException + ReasonsMask reasonMask, List certPathCerts, JcaJceHelper helper) throws AnnotatedException { /* @@ -584,7 +603,7 @@ class RFC3281CertPathUtilities /* * We always get timely valid CRLs, so there is no step (a) (1). * "locally cached" CRLs are assumed to be in getStore(), additional - * CRLs must be enabled in the ExtendedPKIXParameters and are in + * CRLs must be enabled in the PKIXExtendedParameters and are in * getAdditionalStore() */ @@ -618,8 +637,7 @@ class RFC3281CertPathUtilities } // (f) - Set keys = RFC3280CertPathUtilities.processCRLF(crl, attrCert, - null, null, paramsPKIX, certPathCerts); + Set keys = RFC3280CertPathUtilities.processCRLF(crl, attrCert, null, null, paramsPKIX, certPathCerts, helper); // (g) PublicKey key = RFC3280CertPathUtilities.processCRLG(crl, keys); @@ -628,8 +646,7 @@ class RFC3281CertPathUtilities if (paramsPKIX.isUseDeltasEnabled()) { // get delta CRLs - Set deltaCRLs = CertPathValidatorUtilities.getDeltaCRLs( - currentDate, paramsPKIX, crl); + Set deltaCRLs = CertPathValidatorUtilities.getDeltaCRLs(currentDate, crl, paramsPKIX.getCertStores(), paramsPKIX.getCRLStores()); // we only want one valid delta CRL // (h) deltaCRL = RFC3280CertPathUtilities.processCRLH(deltaCRLs, @@ -649,7 +666,7 @@ class RFC3281CertPathUtilities * the CRL vality time */ - if (paramsPKIX.getValidityModel() != ExtendedPKIXParameters.CHAIN_VALIDITY_MODEL) + if (paramsPKIX.getValidityModel() != PKIXExtendedParameters.CHAIN_VALIDITY_MODEL) { /* * if a certificate has expired, but was revoked, it is not diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509AttrCertParser.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509AttrCertParser.java index 847f32bd..08f61c2b 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509AttrCertParser.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509AttrCertParser.java @@ -8,10 +8,10 @@ import java.util.Collection; 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.DERObjectIdentifier; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.SignedData; import org.bouncycastle.x509.X509AttributeCertificate; @@ -36,7 +36,7 @@ public class X509AttrCertParser ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); if (seq.size() > 1 - && seq.getObjectAt(0) instanceof DERObjectIdentifier) + && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) { if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CRLObject.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CRLObject.java index b5b4f13a..c9ee77c8 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CRLObject.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CRLObject.java @@ -62,7 +62,7 @@ public class X509CRLObject private boolean isHashCodeSet = false; private int hashCodeValue; - static boolean isIndirectCRL(X509CRL crl) + public static boolean isIndirectCRL(X509CRL crl) throws CRLException { try diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CRLParser.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CRLParser.java index 40f0a64f..0d1eca72 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CRLParser.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CRLParser.java @@ -10,10 +10,10 @@ import java.util.Collection; 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.DERObjectIdentifier; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.SignedData; import org.bouncycastle.asn1.x509.CertificateList; @@ -37,7 +37,7 @@ public class X509CRLParser ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); if (seq.size() > 1 - && seq.getObjectAt(0) instanceof DERObjectIdentifier) + && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) { if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CertParser.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CertParser.java index a407ba83..0663735b 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CertParser.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CertParser.java @@ -10,10 +10,10 @@ import java.util.Collection; 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.DERObjectIdentifier; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.SignedData; import org.bouncycastle.x509.X509StreamParserSpi; @@ -36,7 +36,7 @@ public class X509CertParser ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); if (seq.size() > 1 - && seq.getObjectAt(0) instanceof DERObjectIdentifier) + && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) { if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509LDAPCertStoreSpi.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509LDAPCertStoreSpi.java index 3797607c..f5269947 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509LDAPCertStoreSpi.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509LDAPCertStoreSpi.java @@ -45,7 +45,7 @@ import org.bouncycastle.jce.X509LDAPCertStoreParameters; * information of the subject (for all kind of certificates) or issuer (for * CRLs), respectively, if a X509CertSelector is given with that details. For * CRLs, CA certificates and cross certificates a coarse search is made only for - * entries with that content to get more possibly matchign results. + * entries with that content to get more possibly matching results. */ public class X509LDAPCertStoreSpi extends CertStoreSpi diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509SignatureUtil.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509SignatureUtil.java index c9a13885..eb1e556e 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509SignatureUtil.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509SignatureUtil.java @@ -11,9 +11,9 @@ import java.security.spec.PSSParameterSpec; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Null; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; @@ -66,21 +66,21 @@ class X509SignatureUtil if (params != null && !derNull.equals(params)) { - if (sigAlgId.getObjectId().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) + if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) { RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - return getDigestAlgName(rsaParams.getHashAlgorithm().getObjectId()) + "withRSAandMGF1"; + return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "withRSAandMGF1"; } - if (sigAlgId.getObjectId().equals(X9ObjectIdentifiers.ecdsa_with_SHA2)) + if (sigAlgId.getAlgorithm().equals(X9ObjectIdentifiers.ecdsa_with_SHA2)) { ASN1Sequence ecDsaParams = ASN1Sequence.getInstance(params); - return getDigestAlgName((DERObjectIdentifier)ecDsaParams.getObjectAt(0)) + "withECDSA"; + return getDigestAlgName(ASN1ObjectIdentifier.getInstance(ecDsaParams.getObjectAt(0))) + "withECDSA"; } } - return sigAlgId.getObjectId().getId(); + return sigAlgId.getAlgorithm().getId(); } /** @@ -88,7 +88,7 @@ class X509SignatureUtil * representations rather the the algorithm identifier (if possible). */ private static String getDigestAlgName( - DERObjectIdentifier digestAlgOID) + ASN1ObjectIdentifier digestAlgOID) { if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreCertPairCollection.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreCertPairCollection.java index e67c25ba..2a6a2c33 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreCertPairCollection.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreCertPairCollection.java @@ -49,12 +49,12 @@ public class X509StoreCertPairCollection extends X509StoreSpi /** * Returns a colelction of certificate pairs which match the given * <code>selector</code>. - * <p/> + * <p> * The returned collection contains * {@link org.bouncycastle.x509.X509CertificatePair}s. The selector must be * a {@link org.bouncycastle.x509.X509CertPairStoreSelector} to select * certificate pairs. - * + * </p> * @return A collection with matching certificate pairs. */ public Collection engineGetMatches(Selector selector) diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPAttrCerts.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPAttrCerts.java index 96baa129..245f3052 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPAttrCerts.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPAttrCerts.java @@ -49,15 +49,15 @@ public class X509StoreLDAPAttrCerts extends X509StoreSpi /** * Returns a collection of matching attribute certificates from the LDAP * location. - * <p/> + * <p> * The selector must be a of type * <code>X509AttributeCertStoreSelector</code>. If it is not an empty * collection is returned. - * <p/> - * <p/> + * </p> + * <p> * The subject and the serial number should be reasonable criterias for a * selector. - * + * </p> * @param selector The selector to use for finding. * @return A collection with the matches. * @throws StoreException if an exception occurs while searching. diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCRLs.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCRLs.java index 5f4dfb48..8af4adeb 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCRLs.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCRLs.java @@ -48,12 +48,12 @@ public class X509StoreLDAPCRLs extends X509StoreSpi /** * Returns a collection of matching CRLs from the LDAP location. - * <p/> + * <p> * The selector must be a of type <code>X509CRLStoreSelector</code>. If * it is not an empty collection is returned. - * <p/> + * </p><p> * The issuer should be a reasonable criteria for a selector. - * + * </p> * @param selector The selector to use for finding. * @return A collection with the matches. * @throws StoreException if an exception occurs while searching. diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCertPairs.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCertPairs.java index f5687d8c..3d3036d3 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCertPairs.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCertPairs.java @@ -49,13 +49,13 @@ public class X509StoreLDAPCertPairs extends X509StoreSpi /** * Returns a collection of matching cross certificate pairs from the LDAP * location. - * <p/> + * <p> * The selector must be a of type <code>X509CertPairStoreSelector</code>. * If it is not an empty collection is returned. - * <p/> - * <p/> + * </p> + * <p> * The subject should be a reasonable criteria for a selector. - * + * </p> * @param selector The selector to use for finding. * @return A collection with the matches. * @throws StoreException if an exception occurs while searching. diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCerts.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCerts.java index dd811a17..c8463ef1 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCerts.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/X509StoreLDAPCerts.java @@ -52,17 +52,17 @@ public class X509StoreLDAPCerts /** * Returns a collection of matching certificates from the LDAP location. - * <p/> + * <p> * The selector must be a of type <code>X509CertStoreSelector</code>. If * it is not an empty collection is returned. - * <p/> + * </p><p> * The implementation searches only for CA certificates, if the method * {@link java.security.cert.X509CertSelector#getBasicConstraints()} is * greater or equal to 0. If it is -2 only end certificates are searched. - * <p/> + * </p><p> * The subject and the serial number for end certificates should be * reasonable criterias for a selector. - * + * </p> * @param selector The selector to use for finding. * @return A collection with the matches. * @throws StoreException if an exception occurs while searching. diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AEADTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AEADTest.java index d2f14057..7d89515a 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AEADTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AEADTest.java @@ -6,7 +6,9 @@ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; +import java.security.SecureRandom; import java.security.Security; +import java.security.spec.InvalidParameterSpecException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; @@ -46,18 +48,62 @@ public class AEADTest extends SimpleTest public void performTest() throws Exception { + boolean aeadAvailable = false; try { this.getClass().getClassLoader().loadClass("javax.crypto.spec.GCMParameterSpec"); - + aeadAvailable = true; + } + catch (ClassNotFoundException e) + { + } + if (aeadAvailable) + { checkCipherWithAD(K2, N2, A2, P2, C2_short); testGCMParameterSpec(K2, N2, A2, P2, C2); testGCMParameterSpecWithRepeatKey(K2, N2, A2, P2, C2); testGCMGeneric(KGCM, NGCM, new byte[0], new byte[0], CGCM); + testGCMParameterSpecWithMultipleUpdates(K2, N2, A2, P2, C2); } - catch (ClassNotFoundException e) + else + { + System.err.println("GCM AEADTests disabled due to JDK"); + } + testTampering(aeadAvailable); + } + + private void testTampering(boolean aeadAvailable) + throws InvalidKeyException, + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchProviderException, + NoSuchPaddingException, + IllegalBlockSizeException, + BadPaddingException + { + Cipher eax = Cipher.getInstance("AES/EAX/NoPadding", "BC"); + final SecretKeySpec key = new SecretKeySpec(new byte[eax.getBlockSize()], eax.getAlgorithm()); + final IvParameterSpec iv = new IvParameterSpec(new byte[eax.getBlockSize()]); + + eax.init(Cipher.ENCRYPT_MODE, key, iv); + byte[] ciphertext = eax.doFinal(new byte[100]); + ciphertext[0] = (byte)(ciphertext[0] + 1); // Tamper + + try { - System.err.println("AEADTest disabled due to JDK"); + eax.init(Cipher.DECRYPT_MODE, key, iv); + eax.doFinal(ciphertext); + fail("Tampered ciphertext should be invalid"); + } + catch (BadPaddingException e) + { + if (aeadAvailable) + { + if (!e.getClass().getName().equals("javax.crypto.AEADBadTagException")) + { + fail("Tampered AEAD ciphertext should fail with AEADBadTagException when available."); + } + } } } @@ -140,6 +186,62 @@ public class AEADTest extends SimpleTest } } + private void testGCMParameterSpecWithMultipleUpdates(byte[] K, + byte[] N, + byte[] A, + byte[] P, + byte[] C) + throws Exception + { + Cipher eax = Cipher.getInstance("AES/EAX/NoPadding", "BC"); + SecretKeySpec key = new SecretKeySpec(K, "AES"); + SecureRandom random = new SecureRandom(); + + // GCMParameterSpec mapped to AEADParameters and overrides default MAC + // size + GCMParameterSpec spec = new GCMParameterSpec(128, N); + + for (int i = 900; i != 1024; i++) + { + byte[] message = new byte[i]; + + random.nextBytes(message); + + eax.init(Cipher.ENCRYPT_MODE, key, spec); + + byte[] out = new byte[eax.getOutputSize(i)]; + + int offSet = 0; + + int count; + for (count = 0; count < i / 21; count++) + { + offSet += eax.update(message, count * 21, 21, out, offSet); + } + + offSet += eax.doFinal(message, count * 21, i - (count * 21), out, offSet); + + byte[] dec = new byte[i]; + int len = offSet; + + eax.init(Cipher.DECRYPT_MODE, key, spec); + + offSet = 0; + for (count = 0; count < len / 10; count++) + { + offSet += eax.update(out, count * 10, 10, dec, offSet); + } + + offSet += eax.doFinal(out, count * 10, len - (count * 10), dec, offSet); + + if (!Arrays.areEqual(message, dec) || offSet != message.length) + { + fail("message mismatch"); + } + } + } + + private void testGCMParameterSpecWithRepeatKey(byte[] K, byte[] N, byte[] A, @@ -192,7 +294,7 @@ public class AEADTest extends SimpleTest throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, - InvalidAlgorithmParameterException, NoSuchProviderException, IOException + InvalidAlgorithmParameterException, NoSuchProviderException, IOException, InvalidParameterSpecException { Cipher eax = Cipher.getInstance("AES/GCM/NoPadding", "BC"); SecretKeySpec key = new SecretKeySpec(K, "AES"); @@ -230,6 +332,18 @@ public class AEADTest extends SimpleTest { fail("parameters mismatch"); } + + GCMParameterSpec gcmSpec = algParams.getParameterSpec(GCMParameterSpec.class); + + if (!Arrays.areEqual(gcmSpec.getIV(), gcmParameters.getNonce()) || gcmSpec.getTLen() != gcmParameters.getIcvLen() * 8) + { + fail("spec parameters mismatch"); + } + + if (!Arrays.areEqual(eax.getIV(), gcmParameters.getNonce())) + { + fail("iv mismatch"); + } } public static void main(String[] args) throws Exception diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AESTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AESTest.java index b9ea1335..72a8a347 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AESTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AESTest.java @@ -1,8 +1,11 @@ package org.bouncycastle.jce.provider.test; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.encoders.Hex; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.security.Key; +import java.security.Security; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; @@ -10,12 +13,11 @@ import javax.crypto.CipherOutputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.IOException; -import java.security.Key; -import java.security.Security; + +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.crypto.prng.FixedSecureRandom; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.encoders.Hex; /** * basic test class for the AES cipher vectors from FIPS-197 @@ -351,6 +353,19 @@ public class AESTest wrapTest(1, "AESWrap", kek1, in1, out1); + byte[] kek2 = Hex.decode("000102030405060708090a0b0c0d0e0f"); + byte[] in2 = Hex.decode("00112233445566778899aabbccddeeff"); + byte[] out2 = Hex.decode("7c8798dfc802553b3f00bb4315e3a087322725c92398b9c112c74d0925c63b61"); + String rndData = "68d38e9635962288d4daa1df203e3e2a15adb2f1da8998b72ac24ab1c78cceac"; + + wrapTest(2, "AESRFC3211WRAP", kek2, kek2, new FixedSecureRandom(Hex.decode(rndData + rndData)), in2, out2); + + byte[] kek3 = Hex.decode("5840df6e29b02af1ab493b705bf16ea1ae8338f4dcc176a8"); + byte[] in3 = Hex.decode("c37b7e6492584340bed12207808941155068f738"); + byte[] out3 = Hex.decode("138bdeaa9b8fa7fc61f97742e72248ee5ae6ae5360d1ae6a5f54f373fa543b6a"); + + wrapTest(3, "AESRFC5649WRAP", kek3, in3, out3); + String[] oids = { NISTObjectIdentifiers.id_aes128_ECB.getId(), NISTObjectIdentifiers.id_aes128_CBC.getId(), diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AttrCertData.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AttrCertData.java new file mode 100644 index 00000000..3e496573 --- /dev/null +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AttrCertData.java @@ -0,0 +1,119 @@ +package org.bouncycastle.jce.provider.test; + +import java.math.BigInteger; +import java.security.spec.RSAPrivateCrtKeySpec; + +import org.bouncycastle.util.encoders.Base64; + +public class AttrCertData +{ + private static final RSAPrivateCrtKeySpec RSA_PRIVATE_KEY_SPEC = new RSAPrivateCrtKeySpec( + new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), + new BigInteger("11", 16), + new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), + new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), + new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), + new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), + new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), + new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); + + public static byte[] attrCert = Base64.decode( + "MIIHQDCCBqkCAQEwgZChgY2kgYowgYcxHDAaBgkqhkiG9w0BCQEWDW1sb3JjaEB2" + + "dC5lZHUxHjAcBgNVBAMTFU1hcmt1cyBMb3JjaCAobWxvcmNoKTEbMBkGA1UECxMS" + + "VmlyZ2luaWEgVGVjaCBVc2VyMRAwDgYDVQQLEwdDbGFzcyAyMQswCQYDVQQKEwJ2" + + "dDELMAkGA1UEBhMCVVMwgYmkgYYwgYMxGzAZBgkqhkiG9w0BCQEWDHNzaGFoQHZ0" + + "LmVkdTEbMBkGA1UEAxMSU3VtaXQgU2hhaCAoc3NoYWgpMRswGQYDVQQLExJWaXJn" + + "aW5pYSBUZWNoIFVzZXIxEDAOBgNVBAsTB0NsYXNzIDExCzAJBgNVBAoTAnZ0MQsw" + + "CQYDVQQGEwJVUzANBgkqhkiG9w0BAQQFAAIBBTAiGA8yMDAzMDcxODE2MDgwMloY" + + "DzIwMDMwNzI1MTYwODAyWjCCBU0wggVJBgorBgEEAbRoCAEBMYIFORaCBTU8UnVs" + + "ZSBSdWxlSWQ9IkZpbGUtUHJpdmlsZWdlLVJ1bGUiIEVmZmVjdD0iUGVybWl0Ij4K" + + "IDxUYXJnZXQ+CiAgPFN1YmplY3RzPgogICA8U3ViamVjdD4KICAgIDxTdWJqZWN0" + + "TWF0Y2ggTWF0Y2hJZD0idXJuOm9hc2lzOm5hbWVzOnRjOnhhY21sOjEuMDpmdW5j" + + "dGlvbjpzdHJpbmctZXF1YWwiPgogICAgIDxBdHRyaWJ1dGVWYWx1ZSBEYXRhVHlw" + + "ZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEjc3RyaW5nIj4KICAg" + + "ICAgIENOPU1hcmt1cyBMb3JjaDwvQXR0cmlidXRlVmFsdWU+CiAgICAgPFN1Ympl" + + "Y3RBdHRyaWJ1dGVEZXNpZ25hdG9yIEF0dHJpYnV0ZUlkPSJ1cm46b2FzaXM6bmFt" + + "ZXM6dGM6eGFjbWw6MS4wOnN1YmplY3Q6c3ViamVjdC1pZCIgRGF0YVR5cGU9Imh0" + + "dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hI3N0cmluZyIgLz4gCiAgICA8" + + "L1N1YmplY3RNYXRjaD4KICAgPC9TdWJqZWN0PgogIDwvU3ViamVjdHM+CiAgPFJl" + + "c291cmNlcz4KICAgPFJlc291cmNlPgogICAgPFJlc291cmNlTWF0Y2ggTWF0Y2hJ" + + "ZD0idXJuOm9hc2lzOm5hbWVzOnRjOnhhY21sOjEuMDpmdW5jdGlvbjpzdHJpbmct" + + "ZXF1YWwiPgogICAgIDxBdHRyaWJ1dGVWYWx1ZSBEYXRhVHlwZT0iaHR0cDovL3d3" + + "dy53My5vcmcvMjAwMS9YTUxTY2hlbWEjYW55VVJJIj4KICAgICAgaHR0cDovL3p1" + + "bmkuY3MudnQuZWR1PC9BdHRyaWJ1dGVWYWx1ZT4KICAgICA8UmVzb3VyY2VBdHRy" + + "aWJ1dGVEZXNpZ25hdG9yIEF0dHJpYnV0ZUlkPSJ1cm46b2FzaXM6bmFtZXM6dGM6" + + "eGFjbWw6MS4wOnJlc291cmNlOnJlc291cmNlLWlkIiBEYXRhVHlwZT0iaHR0cDov" + + "L3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEjYW55VVJJIiAvPiAKICAgIDwvUmVz" + + "b3VyY2VNYXRjaD4KICAgPC9SZXNvdXJjZT4KICA8L1Jlc291cmNlcz4KICA8QWN0" + + "aW9ucz4KICAgPEFjdGlvbj4KICAgIDxBY3Rpb25NYXRjaCBNYXRjaElkPSJ1cm46" + + "b2FzaXM6bmFtZXM6dGM6eGFjbWw6MS4wOmZ1bmN0aW9uOnN0cmluZy1lcXVhbCI+" + + "CiAgICAgPEF0dHJpYnV0ZVZhbHVlIERhdGFUeXBlPSJodHRwOi8vd3d3LnczLm9y" + + "Zy8yMDAxL1hNTFNjaGVtYSNzdHJpbmciPgpEZWxlZ2F0ZSBBY2Nlc3MgICAgIDwv" + + "QXR0cmlidXRlVmFsdWU+CgkgIDxBY3Rpb25BdHRyaWJ1dGVEZXNpZ25hdG9yIEF0" + + "dHJpYnV0ZUlkPSJ1cm46b2FzaXM6bmFtZXM6dGM6eGFjbWw6MS4wOmFjdGlvbjph" + + "Y3Rpb24taWQiIERhdGFUeXBlPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNj" + + "aGVtYSNzdHJpbmciIC8+IAogICAgPC9BY3Rpb25NYXRjaD4KICAgPC9BY3Rpb24+" + + "CiAgPC9BY3Rpb25zPgogPC9UYXJnZXQ+CjwvUnVsZT4KMA0GCSqGSIb3DQEBBAUA" + + "A4GBAGiJSM48XsY90HlYxGmGVSmNR6ZW2As+bot3KAfiCIkUIOAqhcphBS23egTr" + + "6asYwy151HshbPNYz+Cgeqs45KkVzh7bL/0e1r8sDVIaaGIkjHK3CqBABnfSayr3" + + "Rd1yBoDdEv8Qb+3eEPH6ab9021AsLEnJ6LWTmybbOpMNZ3tv"); + + byte[] signCert = Base64.decode( + "MIIGjTCCBXWgAwIBAgICAPswDQYJKoZIhvcNAQEEBQAwaTEdMBsGCSqGSIb3DQEJ" + + "ARYOaXJtaGVscEB2dC5lZHUxLjAsBgNVBAMTJVZpcmdpbmlhIFRlY2ggQ2VydGlm" + + "aWNhdGlvbiBBdXRob3JpdHkxCzAJBgNVBAoTAnZ0MQswCQYDVQQGEwJVUzAeFw0w" + + "MzAxMzExMzUyMTRaFw0wNDAxMzExMzUyMTRaMIGDMRswGQYJKoZIhvcNAQkBFgxz" + + "c2hhaEB2dC5lZHUxGzAZBgNVBAMTElN1bWl0IFNoYWggKHNzaGFoKTEbMBkGA1UE" + + "CxMSVmlyZ2luaWEgVGVjaCBVc2VyMRAwDgYDVQQLEwdDbGFzcyAxMQswCQYDVQQK" + + "EwJ2dDELMAkGA1UEBhMCVVMwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPDc" + + "scgSKmsEp0VegFkuitD5j5PUkDuzLjlfaYONt2SN8WeqU4j2qtlCnsipa128cyKS" + + "JzYe9duUdNxquh5BPIkMkHBw4jHoQA33tk0J/sydWdN74/AHPpPieK5GHwhU7GTG" + + "rCCS1PJRxjXqse79ExAlul+gjQwHeldAC+d4A6oZAgMBAAGjggOmMIIDojAMBgNV" + + "HRMBAf8EAjAAMBEGCWCGSAGG+EIBAQQEAwIFoDAOBgNVHQ8BAf8EBAMCA/gwHQYD" + + "VR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMB0GA1UdDgQWBBRUIoWAzlXbzBYE" + + "yVTjQFWyMMKo1jCBkwYDVR0jBIGLMIGIgBTgc3Fm+TGqKDhen+oKfbl+xVbj2KFt" + + "pGswaTEdMBsGCSqGSIb3DQEJARYOaXJtaGVscEB2dC5lZHUxLjAsBgNVBAMTJVZp" + + "cmdpbmlhIFRlY2ggQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxCzAJBgNVBAoTAnZ0" + + "MQswCQYDVQQGEwJVU4IBADCBiwYJYIZIAYb4QgENBH4WfFZpcmdpbmlhIFRlY2gg" + + "Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgZGlnaXRhbCBjZXJ0aWZpY2F0ZXMgYXJl" + + "IHN1YmplY3QgdG8gcG9saWNpZXMgbG9jYXRlZCBhdCBodHRwOi8vd3d3LnBraS52" + + "dC5lZHUvY2EvY3BzLy4wFwYDVR0RBBAwDoEMc3NoYWhAdnQuZWR1MBkGA1UdEgQS" + + "MBCBDmlybWhlbHBAdnQuZWR1MEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcwAoYn" + + "aHR0cDovL2JveDE3Ny5jYy52dC5lZHUvY2EvaXNzdWVycy5odG1sMEQGA1UdHwQ9" + + "MDswOaA3oDWGM2h0dHA6Ly9ib3gxNzcuY2MudnQuZWR1L2h0ZG9jcy1wdWJsaWMv" + + "Y3JsL2NhY3JsLmNybDBUBgNVHSAETTBLMA0GCysGAQQBtGgFAQEBMDoGCysGAQQB" + + "tGgFAQEBMCswKQYIKwYBBQUHAgEWHWh0dHA6Ly93d3cucGtpLnZ0LmVkdS9jYS9j" + + "cHMvMD8GCWCGSAGG+EIBBAQyFjBodHRwOi8vYm94MTc3LmNjLnZ0LmVkdS9jZ2kt" + + "cHVibGljL2NoZWNrX3Jldl9jYT8wPAYJYIZIAYb4QgEDBC8WLWh0dHA6Ly9ib3gx" + + "NzcuY2MudnQuZWR1L2NnaS1wdWJsaWMvY2hlY2tfcmV2PzBLBglghkgBhvhCAQcE" + + "PhY8aHR0cHM6Ly9ib3gxNzcuY2MudnQuZWR1L35PcGVuQ0E4LjAxMDYzMC9jZ2kt" + + "cHVibGljL3JlbmV3YWw/MCwGCWCGSAGG+EIBCAQfFh1odHRwOi8vd3d3LnBraS52" + + "dC5lZHUvY2EvY3BzLzANBgkqhkiG9w0BAQQFAAOCAQEAHJ2ls9yjpZVcu5DqiE67" + + "r7BfkdMnm7IOj2v8cd4EAlPp6OPBmjwDMwvKRBb/P733kLBqFNWXWKTpT008R0KB" + + "8kehbx4h0UPz9vp31zhGv169+5iReQUUQSIwTGNWGLzrT8kPdvxiSAvdAJxcbRBm" + + "KzDic5I8PoGe48kSCkPpT1oNmnivmcu5j1SMvlx0IS2BkFMksr0OHiAW1elSnE/N" + + "RuX2k73b3FucwVxB3NRo3vgoHPCTnh9r4qItAHdxFlF+pPtbw2oHESKRfMRfOIHz" + + "CLQWSIa6Tvg4NIV3RRJ0sbCObesyg08lymalQMdkXwtRn5eGE00SHWwEUjSXP2gR" + + "3g=="); + + static byte[] certWithBaseCertificateID = Base64.decode( + "MIIBqzCCARQCAQEwSKBGMD6kPDA6MQswCQYDVQQGEwJJVDEOMAwGA1UEChMFVU5JVE4xDDAKBgNV" + + "BAsTA0RJVDENMAsGA1UEAxMEcm9vdAIEAVMVjqB6MHikdjB0MQswCQYDVQQGEwJBVTEoMCYGA1UE" + + "ChMfVGhlIExlZ2lvbiBvZiB0aGUgQm91bmN5IENhc3RsZTEjMCEGA1UECxMaQm91bmN5IFByaW1h" + + "cnkgQ2VydGlmaWNhdGUxFjAUBgNVBAMTDUJvdW5jeSBDYXN0bGUwDQYJKoZIhvcNAQEFBQACBQKW" + + "RhnHMCIYDzIwMDUxMjEyMTIwMDQyWhgPMjAwNTEyMTkxMjAxMzJaMA8wDQYDVRhIMQaBBGVWSVAw" + + "DQYJKoZIhvcNAQEFBQADgYEAUAVin9StDaA+InxtXq/av6rUQLI9p1X6louBcj4kYJnxRvTrHpsr" + + "N3+i9Uq/uk5lRdAqmPFvcmSbuE3TRAsjrXON5uFiBBKZ1AouLqcr8nHbwcdwjJ9TyUNO9I4hfpSH" + + "UHHXMtBKgp4MOkhhX8xTGyWg3hp23d3GaUeg/IYlXBI="); + + byte[] holderCertWithBaseCertificateID = Base64.decode( + "MIIBwDCCASmgAwIBAgIEAVMVjjANBgkqhkiG9w0BAQUFADA6MQswCQYDVQQGEwJJVDEOMAwGA1UE" + + "ChMFVU5JVE4xDDAKBgNVBAsTA0RJVDENMAsGA1UEAxMEcm9vdDAeFw0wNTExMTExMjAxMzJaFw0w" + + "NjA2MTYxMjAxMzJaMD4xCzAJBgNVBAYTAklUMQ4wDAYDVQQKEwVVTklUTjEMMAoGA1UECxMDRElU" + + "MREwDwYDVQQDEwhMdWNhQm9yejBaMA0GCSqGSIb3DQEBAQUAA0kAMEYCQQC0p+RhcFdPFqlwgrIr" + + "5YtqKmKXmEGb4ShypL26Ymz66ZAPdqv7EhOdzl3lZWT6srZUMWWgQMYGiHQg4z2R7X7XAgERoxUw" + + "EzARBglghkgBhvhCAQEEBAMCBDAwDQYJKoZIhvcNAQEFBQADgYEAsX50VPQQCWmHvPq9y9DeCpmS" + + "4szcpFAhpZyn6gYRwY9CRZVtmZKH8713XhkGDWcIEMcG0u3oTz3tdKgPU5uyIPrDEWr6w8ClUj4x" + + "5aVz5c2223+dVY7KES//JSB2bE/KCIchN3kAioQ4K8O3e0OL6oDVjsqKGw5bfahgKuSIk/Q="); + +} diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AttrCertSelectorTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AttrCertSelectorTest.java deleted file mode 100644 index cc556d4f..00000000 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AttrCertSelectorTest.java +++ /dev/null @@ -1,241 +0,0 @@ -package org.bouncycastle.jce.provider.test; - -import java.io.ByteArrayInputStream; -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.PrivateKey; -import java.security.Security; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.security.spec.RSAPrivateCrtKeySpec; -import java.util.Date; - -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.Target; -import org.bouncycastle.asn1.x509.TargetInformation; -import org.bouncycastle.asn1.x509.X509Extensions; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.PrincipalUtil; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.util.test.SimpleTest; -import org.bouncycastle.util.test.Test; -import org.bouncycastle.util.test.TestResult; -import org.bouncycastle.x509.AttributeCertificateHolder; -import org.bouncycastle.x509.AttributeCertificateIssuer; -import org.bouncycastle.x509.X509Attribute; -import org.bouncycastle.x509.X509AttributeCertStoreSelector; -import org.bouncycastle.x509.X509AttributeCertificate; -import org.bouncycastle.x509.X509V2AttributeCertificateGenerator; - -public class AttrCertSelectorTest - extends SimpleTest -{ - - static final RSAPrivateCrtKeySpec RSA_PRIVATE_KEY_SPEC = new RSAPrivateCrtKeySpec( - new BigInteger( - "b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", - 16), - new BigInteger("11", 16), - new BigInteger( - "9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", - 16), new BigInteger( - "c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", - 16), new BigInteger( - "f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", - 16), new BigInteger( - "b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", - 16), new BigInteger( - "d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", - 16), new BigInteger( - "b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", - 16)); - - static final byte[] holderCert = Base64 - .decode("MIIGjTCCBXWgAwIBAgICAPswDQYJKoZIhvcNAQEEBQAwaTEdMBsGCSqGSIb3DQEJ" - + "ARYOaXJtaGVscEB2dC5lZHUxLjAsBgNVBAMTJVZpcmdpbmlhIFRlY2ggQ2VydGlm" - + "aWNhdGlvbiBBdXRob3JpdHkxCzAJBgNVBAoTAnZ0MQswCQYDVQQGEwJVUzAeFw0w" - + "MzAxMzExMzUyMTRaFw0wNDAxMzExMzUyMTRaMIGDMRswGQYJKoZIhvcNAQkBFgxz" - + "c2hhaEB2dC5lZHUxGzAZBgNVBAMTElN1bWl0IFNoYWggKHNzaGFoKTEbMBkGA1UE" - + "CxMSVmlyZ2luaWEgVGVjaCBVc2VyMRAwDgYDVQQLEwdDbGFzcyAxMQswCQYDVQQK" - + "EwJ2dDELMAkGA1UEBhMCVVMwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPDc" - + "scgSKmsEp0VegFkuitD5j5PUkDuzLjlfaYONt2SN8WeqU4j2qtlCnsipa128cyKS" - + "JzYe9duUdNxquh5BPIkMkHBw4jHoQA33tk0J/sydWdN74/AHPpPieK5GHwhU7GTG" - + "rCCS1PJRxjXqse79ExAlul+gjQwHeldAC+d4A6oZAgMBAAGjggOmMIIDojAMBgNV" - + "HRMBAf8EAjAAMBEGCWCGSAGG+EIBAQQEAwIFoDAOBgNVHQ8BAf8EBAMCA/gwHQYD" - + "VR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMB0GA1UdDgQWBBRUIoWAzlXbzBYE" - + "yVTjQFWyMMKo1jCBkwYDVR0jBIGLMIGIgBTgc3Fm+TGqKDhen+oKfbl+xVbj2KFt" - + "pGswaTEdMBsGCSqGSIb3DQEJARYOaXJtaGVscEB2dC5lZHUxLjAsBgNVBAMTJVZp" - + "cmdpbmlhIFRlY2ggQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxCzAJBgNVBAoTAnZ0" - + "MQswCQYDVQQGEwJVU4IBADCBiwYJYIZIAYb4QgENBH4WfFZpcmdpbmlhIFRlY2gg" - + "Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgZGlnaXRhbCBjZXJ0aWZpY2F0ZXMgYXJl" - + "IHN1YmplY3QgdG8gcG9saWNpZXMgbG9jYXRlZCBhdCBodHRwOi8vd3d3LnBraS52" - + "dC5lZHUvY2EvY3BzLy4wFwYDVR0RBBAwDoEMc3NoYWhAdnQuZWR1MBkGA1UdEgQS" - + "MBCBDmlybWhlbHBAdnQuZWR1MEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcwAoYn" - + "aHR0cDovL2JveDE3Ny5jYy52dC5lZHUvY2EvaXNzdWVycy5odG1sMEQGA1UdHwQ9" - + "MDswOaA3oDWGM2h0dHA6Ly9ib3gxNzcuY2MudnQuZWR1L2h0ZG9jcy1wdWJsaWMv" - + "Y3JsL2NhY3JsLmNybDBUBgNVHSAETTBLMA0GCysGAQQBtGgFAQEBMDoGCysGAQQB" - + "tGgFAQEBMCswKQYIKwYBBQUHAgEWHWh0dHA6Ly93d3cucGtpLnZ0LmVkdS9jYS9j" - + "cHMvMD8GCWCGSAGG+EIBBAQyFjBodHRwOi8vYm94MTc3LmNjLnZ0LmVkdS9jZ2kt" - + "cHVibGljL2NoZWNrX3Jldl9jYT8wPAYJYIZIAYb4QgEDBC8WLWh0dHA6Ly9ib3gx" - + "NzcuY2MudnQuZWR1L2NnaS1wdWJsaWMvY2hlY2tfcmV2PzBLBglghkgBhvhCAQcE" - + "PhY8aHR0cHM6Ly9ib3gxNzcuY2MudnQuZWR1L35PcGVuQ0E4LjAxMDYzMC9jZ2kt" - + "cHVibGljL3JlbmV3YWw/MCwGCWCGSAGG+EIBCAQfFh1odHRwOi8vd3d3LnBraS52" - + "dC5lZHUvY2EvY3BzLzANBgkqhkiG9w0BAQQFAAOCAQEAHJ2ls9yjpZVcu5DqiE67" - + "r7BfkdMnm7IOj2v8cd4EAlPp6OPBmjwDMwvKRBb/P733kLBqFNWXWKTpT008R0KB" - + "8kehbx4h0UPz9vp31zhGv169+5iReQUUQSIwTGNWGLzrT8kPdvxiSAvdAJxcbRBm" - + "KzDic5I8PoGe48kSCkPpT1oNmnivmcu5j1SMvlx0IS2BkFMksr0OHiAW1elSnE/N" - + "RuX2k73b3FucwVxB3NRo3vgoHPCTnh9r4qItAHdxFlF+pPtbw2oHESKRfMRfOIHz" - + "CLQWSIa6Tvg4NIV3RRJ0sbCObesyg08lymalQMdkXwtRn5eGE00SHWwEUjSXP2gR" - + "3g=="); - - public String getName() - { - return "AttrCertSelector"; - } - - private X509AttributeCertificate createAttrCert() throws Exception - { - CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); - X509Certificate iCert = (X509Certificate) fact - .generateCertificate(new ByteArrayInputStream(holderCert)); - - // - // a sample key pair. - // - // RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( - // new BigInteger( - // "b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", - // 16), new BigInteger("11", 16)); - - // - // set up the keys - // - PrivateKey privKey; - - KeyFactory kFact = KeyFactory.getInstance("RSA", "BC"); - - privKey = kFact.generatePrivate(RSA_PRIVATE_KEY_SPEC); - - X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator(); - - // the actual attributes - GeneralName roleName = new GeneralName(GeneralName.rfc822Name, - "DAU123456789@test.com"); - ASN1EncodableVector roleSyntax = new ASN1EncodableVector(); - roleSyntax.add(roleName); - - // roleSyntax OID: 2.5.24.72 - X509Attribute attributes = new X509Attribute("2.5.24.72", - new DERSequence(roleSyntax)); - - gen.addAttribute(attributes); - gen.setHolder(new AttributeCertificateHolder(PrincipalUtil.getSubjectX509Principal(iCert))); - gen.setIssuer(new AttributeCertificateIssuer(new X509Principal( - "cn=test"))); - gen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - gen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - gen.setSerialNumber(BigInteger.valueOf(1)); - gen.setSignatureAlgorithm("SHA1WithRSAEncryption"); - - Target targetName = new Target(Target.targetName, new GeneralName(GeneralName.dNSName, - "www.test.com")); - - Target targetGroup = new Target(Target.targetGroup, new GeneralName( - GeneralName.directoryName, "o=Test, ou=Test")); - Target[] targets = new Target[2]; - targets[0] = targetName; - targets[1] = targetGroup; - TargetInformation targetInformation = new TargetInformation(targets); - gen.addExtension(X509Extensions.TargetInformation.getId(), true, - targetInformation); - - return gen.generate(privKey, "BC"); - } - - public void testSelector() throws Exception - { - X509AttributeCertificate aCert = createAttrCert(); - X509AttributeCertStoreSelector sel = new X509AttributeCertStoreSelector(); - sel.setAttributeCert(aCert); - boolean match = sel.match(aCert); - if (!match) - { - fail("Selector does not match attribute certificate."); - } - sel.setAttributeCert(null); - match = sel.match(aCert); - if (!match) - { - fail("Selector does not match attribute certificate."); - } - sel.setHolder(aCert.getHolder()); - match = sel.match(aCert); - if (!match) - { - fail("Selector does not match attribute certificate holder."); - } - sel.setHolder(null); - sel.setIssuer(aCert.getIssuer()); - match = sel.match(aCert); - if (!match) - { - fail("Selector does not match attribute certificate issuer."); - } - sel.setIssuer(null); - - CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); - X509Certificate iCert = (X509Certificate) fact - .generateCertificate(new ByteArrayInputStream(holderCert)); - match = aCert.getHolder().match(iCert); - if (!match) - { - fail("Issuer holder does not match signing certificate of attribute certificate."); - } - - sel.setSerialNumber(aCert.getSerialNumber()); - match = sel.match(aCert); - if (!match) - { - fail("Selector does not match attribute certificate serial number."); - } - - sel.setAttributeCertificateValid(new Date()); - match = sel.match(aCert); - if (!match) - { - fail("Selector does not match attribute certificate time."); - } - - sel.addTargetName(new GeneralName(2, "www.test.com")); - match = sel.match(aCert); - if (!match) - { - fail("Selector does not match attribute certificate target name."); - } - sel.setTargetNames(null); - sel.addTargetGroup(new GeneralName(4, "o=Test, ou=Test")); - match = sel.match(aCert); - if (!match) - { - fail("Selector does not match attribute certificate target group."); - } - sel.setTargetGroups(null); - } - - public void performTest() throws Exception - { - Security.addProvider(new BouncyCastleProvider()); - testSelector(); - } - - public static void main(String[] args) - { - Test test = new AttrCertSelectorTest(); - TestResult result = test.perform(); - System.out.println(result); - } -} - diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AttrCertTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AttrCertTest.java deleted file mode 100644 index 416ba499..00000000 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/AttrCertTest.java +++ /dev/null @@ -1,634 +0,0 @@ -package org.bouncycastle.jce.provider.test; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.Principal; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Security; -import java.security.cert.CertStore; -import java.security.cert.CertificateFactory; -import java.security.cert.CollectionCertStoreParameters; -import java.security.cert.X509Certificate; -import java.security.spec.RSAPrivateCrtKeySpec; -import java.security.spec.RSAPublicKeySpec; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Set; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1String; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.util.test.SimpleTest; -import org.bouncycastle.x509.AttributeCertificateHolder; -import org.bouncycastle.x509.AttributeCertificateIssuer; -import org.bouncycastle.x509.X509Attribute; -import org.bouncycastle.x509.X509AttributeCertificate; -import org.bouncycastle.x509.X509V2AttributeCertificate; -import org.bouncycastle.x509.X509V2AttributeCertificateGenerator; -import org.bouncycastle.x509.extension.X509ExtensionUtil; - -public class AttrCertTest - extends SimpleTest -{ - private static final RSAPrivateCrtKeySpec RSA_PRIVATE_KEY_SPEC = new RSAPrivateCrtKeySpec( - new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), - new BigInteger("11", 16), - new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), - new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), - new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), - new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), - new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), - new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); - - public static byte[] attrCert = Base64.decode( - "MIIHQDCCBqkCAQEwgZChgY2kgYowgYcxHDAaBgkqhkiG9w0BCQEWDW1sb3JjaEB2" - + "dC5lZHUxHjAcBgNVBAMTFU1hcmt1cyBMb3JjaCAobWxvcmNoKTEbMBkGA1UECxMS" - + "VmlyZ2luaWEgVGVjaCBVc2VyMRAwDgYDVQQLEwdDbGFzcyAyMQswCQYDVQQKEwJ2" - + "dDELMAkGA1UEBhMCVVMwgYmkgYYwgYMxGzAZBgkqhkiG9w0BCQEWDHNzaGFoQHZ0" - + "LmVkdTEbMBkGA1UEAxMSU3VtaXQgU2hhaCAoc3NoYWgpMRswGQYDVQQLExJWaXJn" - + "aW5pYSBUZWNoIFVzZXIxEDAOBgNVBAsTB0NsYXNzIDExCzAJBgNVBAoTAnZ0MQsw" - + "CQYDVQQGEwJVUzANBgkqhkiG9w0BAQQFAAIBBTAiGA8yMDAzMDcxODE2MDgwMloY" - + "DzIwMDMwNzI1MTYwODAyWjCCBU0wggVJBgorBgEEAbRoCAEBMYIFORaCBTU8UnVs" - + "ZSBSdWxlSWQ9IkZpbGUtUHJpdmlsZWdlLVJ1bGUiIEVmZmVjdD0iUGVybWl0Ij4K" - + "IDxUYXJnZXQ+CiAgPFN1YmplY3RzPgogICA8U3ViamVjdD4KICAgIDxTdWJqZWN0" - + "TWF0Y2ggTWF0Y2hJZD0idXJuOm9hc2lzOm5hbWVzOnRjOnhhY21sOjEuMDpmdW5j" - + "dGlvbjpzdHJpbmctZXF1YWwiPgogICAgIDxBdHRyaWJ1dGVWYWx1ZSBEYXRhVHlw" - + "ZT0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEjc3RyaW5nIj4KICAg" - + "ICAgIENOPU1hcmt1cyBMb3JjaDwvQXR0cmlidXRlVmFsdWU+CiAgICAgPFN1Ympl" - + "Y3RBdHRyaWJ1dGVEZXNpZ25hdG9yIEF0dHJpYnV0ZUlkPSJ1cm46b2FzaXM6bmFt" - + "ZXM6dGM6eGFjbWw6MS4wOnN1YmplY3Q6c3ViamVjdC1pZCIgRGF0YVR5cGU9Imh0" - + "dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hI3N0cmluZyIgLz4gCiAgICA8" - + "L1N1YmplY3RNYXRjaD4KICAgPC9TdWJqZWN0PgogIDwvU3ViamVjdHM+CiAgPFJl" - + "c291cmNlcz4KICAgPFJlc291cmNlPgogICAgPFJlc291cmNlTWF0Y2ggTWF0Y2hJ" - + "ZD0idXJuOm9hc2lzOm5hbWVzOnRjOnhhY21sOjEuMDpmdW5jdGlvbjpzdHJpbmct" - + "ZXF1YWwiPgogICAgIDxBdHRyaWJ1dGVWYWx1ZSBEYXRhVHlwZT0iaHR0cDovL3d3" - + "dy53My5vcmcvMjAwMS9YTUxTY2hlbWEjYW55VVJJIj4KICAgICAgaHR0cDovL3p1" - + "bmkuY3MudnQuZWR1PC9BdHRyaWJ1dGVWYWx1ZT4KICAgICA8UmVzb3VyY2VBdHRy" - + "aWJ1dGVEZXNpZ25hdG9yIEF0dHJpYnV0ZUlkPSJ1cm46b2FzaXM6bmFtZXM6dGM6" - + "eGFjbWw6MS4wOnJlc291cmNlOnJlc291cmNlLWlkIiBEYXRhVHlwZT0iaHR0cDov" - + "L3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEjYW55VVJJIiAvPiAKICAgIDwvUmVz" - + "b3VyY2VNYXRjaD4KICAgPC9SZXNvdXJjZT4KICA8L1Jlc291cmNlcz4KICA8QWN0" - + "aW9ucz4KICAgPEFjdGlvbj4KICAgIDxBY3Rpb25NYXRjaCBNYXRjaElkPSJ1cm46" - + "b2FzaXM6bmFtZXM6dGM6eGFjbWw6MS4wOmZ1bmN0aW9uOnN0cmluZy1lcXVhbCI+" - + "CiAgICAgPEF0dHJpYnV0ZVZhbHVlIERhdGFUeXBlPSJodHRwOi8vd3d3LnczLm9y" - + "Zy8yMDAxL1hNTFNjaGVtYSNzdHJpbmciPgpEZWxlZ2F0ZSBBY2Nlc3MgICAgIDwv" - + "QXR0cmlidXRlVmFsdWU+CgkgIDxBY3Rpb25BdHRyaWJ1dGVEZXNpZ25hdG9yIEF0" - + "dHJpYnV0ZUlkPSJ1cm46b2FzaXM6bmFtZXM6dGM6eGFjbWw6MS4wOmFjdGlvbjph" - + "Y3Rpb24taWQiIERhdGFUeXBlPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNj" - + "aGVtYSNzdHJpbmciIC8+IAogICAgPC9BY3Rpb25NYXRjaD4KICAgPC9BY3Rpb24+" - + "CiAgPC9BY3Rpb25zPgogPC9UYXJnZXQ+CjwvUnVsZT4KMA0GCSqGSIb3DQEBBAUA" - + "A4GBAGiJSM48XsY90HlYxGmGVSmNR6ZW2As+bot3KAfiCIkUIOAqhcphBS23egTr" - + "6asYwy151HshbPNYz+Cgeqs45KkVzh7bL/0e1r8sDVIaaGIkjHK3CqBABnfSayr3" - + "Rd1yBoDdEv8Qb+3eEPH6ab9021AsLEnJ6LWTmybbOpMNZ3tv"); - - byte[] signCert = Base64.decode( - "MIIGjTCCBXWgAwIBAgICAPswDQYJKoZIhvcNAQEEBQAwaTEdMBsGCSqGSIb3DQEJ" - + "ARYOaXJtaGVscEB2dC5lZHUxLjAsBgNVBAMTJVZpcmdpbmlhIFRlY2ggQ2VydGlm" - + "aWNhdGlvbiBBdXRob3JpdHkxCzAJBgNVBAoTAnZ0MQswCQYDVQQGEwJVUzAeFw0w" - + "MzAxMzExMzUyMTRaFw0wNDAxMzExMzUyMTRaMIGDMRswGQYJKoZIhvcNAQkBFgxz" - + "c2hhaEB2dC5lZHUxGzAZBgNVBAMTElN1bWl0IFNoYWggKHNzaGFoKTEbMBkGA1UE" - + "CxMSVmlyZ2luaWEgVGVjaCBVc2VyMRAwDgYDVQQLEwdDbGFzcyAxMQswCQYDVQQK" - + "EwJ2dDELMAkGA1UEBhMCVVMwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPDc" - + "scgSKmsEp0VegFkuitD5j5PUkDuzLjlfaYONt2SN8WeqU4j2qtlCnsipa128cyKS" - + "JzYe9duUdNxquh5BPIkMkHBw4jHoQA33tk0J/sydWdN74/AHPpPieK5GHwhU7GTG" - + "rCCS1PJRxjXqse79ExAlul+gjQwHeldAC+d4A6oZAgMBAAGjggOmMIIDojAMBgNV" - + "HRMBAf8EAjAAMBEGCWCGSAGG+EIBAQQEAwIFoDAOBgNVHQ8BAf8EBAMCA/gwHQYD" - + "VR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMB0GA1UdDgQWBBRUIoWAzlXbzBYE" - + "yVTjQFWyMMKo1jCBkwYDVR0jBIGLMIGIgBTgc3Fm+TGqKDhen+oKfbl+xVbj2KFt" - + "pGswaTEdMBsGCSqGSIb3DQEJARYOaXJtaGVscEB2dC5lZHUxLjAsBgNVBAMTJVZp" - + "cmdpbmlhIFRlY2ggQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxCzAJBgNVBAoTAnZ0" - + "MQswCQYDVQQGEwJVU4IBADCBiwYJYIZIAYb4QgENBH4WfFZpcmdpbmlhIFRlY2gg" - + "Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgZGlnaXRhbCBjZXJ0aWZpY2F0ZXMgYXJl" - + "IHN1YmplY3QgdG8gcG9saWNpZXMgbG9jYXRlZCBhdCBodHRwOi8vd3d3LnBraS52" - + "dC5lZHUvY2EvY3BzLy4wFwYDVR0RBBAwDoEMc3NoYWhAdnQuZWR1MBkGA1UdEgQS" - + "MBCBDmlybWhlbHBAdnQuZWR1MEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcwAoYn" - + "aHR0cDovL2JveDE3Ny5jYy52dC5lZHUvY2EvaXNzdWVycy5odG1sMEQGA1UdHwQ9" - + "MDswOaA3oDWGM2h0dHA6Ly9ib3gxNzcuY2MudnQuZWR1L2h0ZG9jcy1wdWJsaWMv" - + "Y3JsL2NhY3JsLmNybDBUBgNVHSAETTBLMA0GCysGAQQBtGgFAQEBMDoGCysGAQQB" - + "tGgFAQEBMCswKQYIKwYBBQUHAgEWHWh0dHA6Ly93d3cucGtpLnZ0LmVkdS9jYS9j" - + "cHMvMD8GCWCGSAGG+EIBBAQyFjBodHRwOi8vYm94MTc3LmNjLnZ0LmVkdS9jZ2kt" - + "cHVibGljL2NoZWNrX3Jldl9jYT8wPAYJYIZIAYb4QgEDBC8WLWh0dHA6Ly9ib3gx" - + "NzcuY2MudnQuZWR1L2NnaS1wdWJsaWMvY2hlY2tfcmV2PzBLBglghkgBhvhCAQcE" - + "PhY8aHR0cHM6Ly9ib3gxNzcuY2MudnQuZWR1L35PcGVuQ0E4LjAxMDYzMC9jZ2kt" - + "cHVibGljL3JlbmV3YWw/MCwGCWCGSAGG+EIBCAQfFh1odHRwOi8vd3d3LnBraS52" - + "dC5lZHUvY2EvY3BzLzANBgkqhkiG9w0BAQQFAAOCAQEAHJ2ls9yjpZVcu5DqiE67" - + "r7BfkdMnm7IOj2v8cd4EAlPp6OPBmjwDMwvKRBb/P733kLBqFNWXWKTpT008R0KB" - + "8kehbx4h0UPz9vp31zhGv169+5iReQUUQSIwTGNWGLzrT8kPdvxiSAvdAJxcbRBm" - + "KzDic5I8PoGe48kSCkPpT1oNmnivmcu5j1SMvlx0IS2BkFMksr0OHiAW1elSnE/N" - + "RuX2k73b3FucwVxB3NRo3vgoHPCTnh9r4qItAHdxFlF+pPtbw2oHESKRfMRfOIHz" - + "CLQWSIa6Tvg4NIV3RRJ0sbCObesyg08lymalQMdkXwtRn5eGE00SHWwEUjSXP2gR" - + "3g=="); - - static byte[] certWithBaseCertificateID = Base64.decode( - "MIIBqzCCARQCAQEwSKBGMD6kPDA6MQswCQYDVQQGEwJJVDEOMAwGA1UEChMFVU5JVE4xDDAKBgNV" - + "BAsTA0RJVDENMAsGA1UEAxMEcm9vdAIEAVMVjqB6MHikdjB0MQswCQYDVQQGEwJBVTEoMCYGA1UE" - + "ChMfVGhlIExlZ2lvbiBvZiB0aGUgQm91bmN5IENhc3RsZTEjMCEGA1UECxMaQm91bmN5IFByaW1h" - + "cnkgQ2VydGlmaWNhdGUxFjAUBgNVBAMTDUJvdW5jeSBDYXN0bGUwDQYJKoZIhvcNAQEFBQACBQKW" - + "RhnHMCIYDzIwMDUxMjEyMTIwMDQyWhgPMjAwNTEyMTkxMjAxMzJaMA8wDQYDVRhIMQaBBGVWSVAw" - + "DQYJKoZIhvcNAQEFBQADgYEAUAVin9StDaA+InxtXq/av6rUQLI9p1X6louBcj4kYJnxRvTrHpsr" - + "N3+i9Uq/uk5lRdAqmPFvcmSbuE3TRAsjrXON5uFiBBKZ1AouLqcr8nHbwcdwjJ9TyUNO9I4hfpSH" - + "UHHXMtBKgp4MOkhhX8xTGyWg3hp23d3GaUeg/IYlXBI="); - - byte[] holderCertWithBaseCertificateID = Base64.decode( - "MIIBwDCCASmgAwIBAgIEAVMVjjANBgkqhkiG9w0BAQUFADA6MQswCQYDVQQGEwJJVDEOMAwGA1UE" - + "ChMFVU5JVE4xDDAKBgNVBAsTA0RJVDENMAsGA1UEAxMEcm9vdDAeFw0wNTExMTExMjAxMzJaFw0w" - + "NjA2MTYxMjAxMzJaMD4xCzAJBgNVBAYTAklUMQ4wDAYDVQQKEwVVTklUTjEMMAoGA1UECxMDRElU" - + "MREwDwYDVQQDEwhMdWNhQm9yejBaMA0GCSqGSIb3DQEBAQUAA0kAMEYCQQC0p+RhcFdPFqlwgrIr" - + "5YtqKmKXmEGb4ShypL26Ymz66ZAPdqv7EhOdzl3lZWT6srZUMWWgQMYGiHQg4z2R7X7XAgERoxUw" - + "EzARBglghkgBhvhCAQEEBAMCBDAwDQYJKoZIhvcNAQEFBQADgYEAsX50VPQQCWmHvPq9y9DeCpmS" - + "4szcpFAhpZyn6gYRwY9CRZVtmZKH8713XhkGDWcIEMcG0u3oTz3tdKgPU5uyIPrDEWr6w8ClUj4x" - + "5aVz5c2223+dVY7KES//JSB2bE/KCIchN3kAioQ4K8O3e0OL6oDVjsqKGw5bfahgKuSIk/Q="); - - - public String getName() - { - return "AttrCertTest"; - } - - private void testCertWithBaseCertificateID() - throws Exception - { - X509AttributeCertificate attrCert = new X509V2AttributeCertificate(certWithBaseCertificateID); - CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); - X509Certificate cert = (X509Certificate)fact.generateCertificate(new ByteArrayInputStream(holderCertWithBaseCertificateID)); - - AttributeCertificateHolder holder = attrCert.getHolder(); - - if (holder.getEntityNames() != null) - { - fail("entity names set when none expected"); - } - - if (!holder.getSerialNumber().equals(cert.getSerialNumber())) - { - fail("holder serial number doesn't match"); - } - - if (!holder.getIssuer()[0].equals(cert.getIssuerX500Principal())) - { - fail("holder issuer doesn't match"); - } - - if (!holder.match(cert)) - { - fail("holder not matching holder certificate"); - } - - if (!holder.equals(holder.clone())) - { - fail("holder clone test failed"); - } - - if (!attrCert.getIssuer().equals(attrCert.getIssuer().clone())) - { - fail("issuer clone test failed"); - } - - //equalityAndHashCodeTest(attrCert, certWithBaseCertificateID); - } - - private void equalityAndHashCodeTest(X509AttributeCertificate attrCert, byte[] encoding) - throws IOException - { - if (!attrCert.equals(attrCert)) - { - fail("same certificate not equal"); - } - - if (!attrCert.getHolder().equals(attrCert.getHolder())) - { - fail("same holder not equal"); - } - - if (!attrCert.getIssuer().equals(attrCert.getIssuer())) - { - fail("same issuer not equal"); - } - - if (attrCert.getHolder().equals(attrCert.getIssuer())) - { - fail("wrong holder equal"); - } - - if (attrCert.getIssuer().equals(attrCert.getHolder())) - { - fail("wrong issuer equal"); - } - - X509AttributeCertificate attrCert2 = new X509V2AttributeCertificate(encoding); - - if (attrCert2.getHolder().hashCode() != attrCert.getHolder().hashCode()) - { - fail("holder hashCode test failed"); - } - - if (!attrCert2.getHolder().equals(attrCert.getHolder())) - { - fail("holder equals test failed"); - } - - if (attrCert2.getIssuer().hashCode() != attrCert.getIssuer().hashCode()) - { - fail("issuer hashCode test failed"); - } - - if (!attrCert2.getIssuer().equals(attrCert.getIssuer())) - { - fail("issuer equals test failed"); - } - } - - private void testGenerateWithCert() - throws Exception - { - CertificateFactory fact = CertificateFactory.getInstance("X.509","BC"); - X509Certificate iCert = (X509Certificate)fact.generateCertificate(new ByteArrayInputStream(signCert)); - - // - // a sample key pair. - // - RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( - new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), - new BigInteger("11", 16)); - - // - // set up the keys - // - PrivateKey privKey; - PublicKey pubKey; - - KeyFactory kFact = KeyFactory.getInstance("RSA", "BC"); - - privKey = kFact.generatePrivate(RSA_PRIVATE_KEY_SPEC); - pubKey = kFact.generatePublic(pubKeySpec); - - X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator(); - - // the actual attributes - GeneralName roleName = new GeneralName(GeneralName.rfc822Name, "DAU123456789"); - ASN1EncodableVector roleSyntax = new ASN1EncodableVector(); - roleSyntax.add(roleName); - - // roleSyntax OID: 2.5.24.72 - X509Attribute attributes = new X509Attribute("2.5.24.72", - new DERSequence(roleSyntax)); - - gen.addAttribute(attributes); - gen.setHolder(new AttributeCertificateHolder(iCert)); - gen.setIssuer(new AttributeCertificateIssuer(new X509Principal("cn=test"))); - gen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - gen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - gen.setSerialNumber(BigInteger.ONE); - gen.setSignatureAlgorithm("SHA1WithRSAEncryption"); - - X509AttributeCertificate aCert = gen.generate(privKey, "BC"); - - aCert.checkValidity(); - - aCert.verify(pubKey, "BC"); - - AttributeCertificateHolder holder = aCert.getHolder(); - - if (holder.getEntityNames() != null) - { - fail("entity names set when none expected"); - } - - if (!holder.getSerialNumber().equals(iCert.getSerialNumber())) - { - fail("holder serial number doesn't match"); - } - - if (!holder.getIssuer()[0].equals(iCert.getIssuerX500Principal())) - { - fail("holder issuer doesn't match"); - } - - if (!holder.match(iCert)) - { - fail("generated holder not matching holder certificate"); - } - - X509Attribute[] attrs = aCert.getAttributes("2.5.24.72"); - - if (attrs == null) - { - fail("attributes related to 2.5.24.72 not found"); - } - - X509Attribute attr = attrs[0]; - - if (!attr.getOID().equals("2.5.24.72")) - { - fail("attribute oid mismatch"); - } - - ASN1Encodable[] values = attr.getValues(); - - GeneralName role = GeneralNames.getInstance(values[0]).getNames()[0]; - - if (role.getTagNo() != GeneralName.rfc822Name) - { - fail("wrong general name type found in role"); - } - - if (!((ASN1String)role.getName()).getString().equals("DAU123456789")) - { - fail("wrong general name value found in role"); - } - - X509Certificate sCert = (X509Certificate)fact.generateCertificate(new ByteArrayInputStream(holderCertWithBaseCertificateID)); - - if (holder.match(sCert)) - { - fail("generated holder matching wrong certificate"); - } - - equalityAndHashCodeTest(aCert, aCert.getEncoded()); - } - - private void testGenerateWithPrincipal() - throws Exception - { - CertificateFactory fact = CertificateFactory.getInstance("X.509","BC"); - X509Certificate iCert = (X509Certificate)fact.generateCertificate(new ByteArrayInputStream(signCert)); - - // - // a sample key pair. - // - RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( - new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), - new BigInteger("11", 16)); - - // - // set up the keys - // - PrivateKey privKey; - PublicKey pubKey; - - KeyFactory kFact = KeyFactory.getInstance("RSA", "BC"); - - privKey = kFact.generatePrivate(RSA_PRIVATE_KEY_SPEC); - pubKey = kFact.generatePublic(pubKeySpec); - - X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator(); - - // the actual attributes - GeneralName roleName = new GeneralName(GeneralName.rfc822Name, "DAU123456789"); - ASN1EncodableVector roleSyntax = new ASN1EncodableVector(); - roleSyntax.add(roleName); - - // roleSyntax OID: 2.5.24.72 - X509Attribute attributes = new X509Attribute("2.5.24.72", - new DERSequence(roleSyntax)); - - gen.addAttribute(attributes); - gen.setHolder(new AttributeCertificateHolder(iCert.getSubjectX500Principal())); - gen.setIssuer(new AttributeCertificateIssuer(new X509Principal("cn=test"))); - gen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - gen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - gen.setSerialNumber(BigInteger.ONE); - gen.setSignatureAlgorithm("SHA1WithRSAEncryption"); - - X509AttributeCertificate aCert = gen.generate(privKey, "BC"); - - aCert.checkValidity(); - - aCert.verify(pubKey, "BC"); - - AttributeCertificateHolder holder = aCert.getHolder(); - - if (holder.getEntityNames() == null) - { - fail("entity names not set when expected"); - } - - if (holder.getSerialNumber() != null) - { - fail("holder serial number found when none expected"); - } - - if (holder.getIssuer() != null) - { - fail("holder issuer found when none expected"); - } - - if (!holder.match(iCert)) - { - fail("generated holder not matching holder certificate"); - } - - X509Certificate sCert = (X509Certificate)fact.generateCertificate(new ByteArrayInputStream(holderCertWithBaseCertificateID)); - - if (holder.match(sCert)) - { - fail("principal generated holder matching wrong certificate"); - } - - equalityAndHashCodeTest(aCert, aCert.getEncoded()); - } - - public void performTest() - throws Exception - { - X509AttributeCertificate aCert = new X509V2AttributeCertificate(attrCert); - CertificateFactory fact = CertificateFactory.getInstance("X.509","BC"); - X509Certificate sCert = (X509Certificate)fact.generateCertificate(new ByteArrayInputStream(signCert)); - - aCert.verify(sCert.getPublicKey(), "BC"); - - // - // search test - // - - List list = new ArrayList(); - - list.add(sCert); - - CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); - CertStore store = CertStore.getInstance("Collection", ccsp); - - Collection certs = store.getCertificates(aCert.getIssuer()); - if (certs.size() != 1 || !certs.contains(sCert)) - { - fail("sCert not found by issuer"); - } - - X509Attribute[] attrs = aCert.getAttributes("1.3.6.1.4.1.6760.8.1.1"); - if (attrs == null || attrs.length != 1) - { - fail("attribute not found"); - } - - // - // reencode test - // - aCert = new X509V2AttributeCertificate(aCert.getEncoded()); - - aCert.verify(sCert.getPublicKey(), "BC"); - - X509AttributeCertificate saCert = new X509V2AttributeCertificate(new ByteArrayInputStream(aCert.getEncoded())); - - if (!aCert.getNotAfter().equals(saCert.getNotAfter())) - { - fail("failed date comparison"); - } - - // base generator test - - // - // a sample key pair. - // - RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( - new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), - new BigInteger("11", 16)); - - RSAPrivateCrtKeySpec privKeySpec = RSA_PRIVATE_KEY_SPEC; - - // - // set up the keys - // - PrivateKey privKey; - PublicKey pubKey; - - KeyFactory kFact = KeyFactory.getInstance("RSA", "BC"); - - privKey = kFact.generatePrivate(privKeySpec); - pubKey = kFact.generatePublic(pubKeySpec); - - X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator(); - - gen.addAttribute(attrs[0]); - gen.setHolder(aCert.getHolder()); - gen.setIssuer(aCert.getIssuer()); - gen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - gen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - gen.setSerialNumber(aCert.getSerialNumber()); - gen.setSignatureAlgorithm("SHA1WithRSAEncryption"); - - aCert = gen.generate(privKey, "BC"); - - aCert.checkValidity(); - - aCert.verify(pubKey, "BC"); - - // as the issuer is the same this should still work (even though it is not - // technically correct - - certs = store.getCertificates(aCert.getIssuer()); - if (certs.size() != 1 || !certs.contains(sCert)) - { - fail("sCert not found by issuer"); - } - - attrs = aCert.getAttributes("1.3.6.1.4.1.6760.8.1.1"); - if (attrs == null || attrs.length != 1) - { - fail("attribute not found"); - } - - // - // reencode test - // - aCert = new X509V2AttributeCertificate(aCert.getEncoded()); - - aCert.verify(pubKey, "BC"); - - AttributeCertificateIssuer issuer = aCert.getIssuer(); - - Principal[] principals = issuer.getPrincipals(); - - // - // test holder - // - AttributeCertificateHolder holder = aCert.getHolder(); - - if (holder.getEntityNames() == null) - { - fail("entity names not set"); - } - - if (holder.getSerialNumber() != null) - { - fail("holder serial number set when none expected"); - } - - if (holder.getIssuer() != null) - { - fail("holder issuer set when none expected"); - } - - principals = holder.getEntityNames(); - - if (!principals[0].toString().equals("C=US, O=vt, OU=Class 2, OU=Virginia Tech User, CN=Markus Lorch (mlorch), EMAILADDRESS=mlorch@vt.edu")) - { - fail("principal[0] for entity names don't match"); - } - - // - // extension test - // - - if (aCert.hasUnsupportedCriticalExtension()) - { - fail("unsupported extensions found with no extensions"); - } - - gen.addExtension("1.1", true, new DEROctetString(new byte[10])); - - gen.addExtension("2.2", false, new DEROctetString(new byte[20])); - - aCert = gen.generate(privKey, "BC"); - - Set exts = aCert.getCriticalExtensionOIDs(); - - if (exts.size() != 1 || !exts.contains("1.1")) - { - fail("critical extension test failed"); - } - - exts = aCert.getNonCriticalExtensionOIDs(); - - if (exts.size() != 1 || !exts.contains("2.2")) - { - fail("non-critical extension test failed"); - } - - if (!aCert.hasUnsupportedCriticalExtension()) - { - fail("unsupported extensions not found"); - } - - byte[] extString = aCert.getExtensionValue("1.1"); - ASN1Encodable extValue = X509ExtensionUtil.fromExtensionValue(extString); - - if (!extValue.equals(new DEROctetString(new byte[10]))) - { - fail("wrong extension value found for 1.1"); - } - - testCertWithBaseCertificateID(); - testGenerateWithCert(); - testGenerateWithPrincipal(); - } - - public static void main( - String[] args) - { - Security.addProvider(new BouncyCastleProvider()); - - runTest(new AttrCertTest()); - } -} diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/BaseBlockCipherTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/BaseBlockCipherTest.java index ebc56002..379bd44f 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/BaseBlockCipherTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/BaseBlockCipherTest.java @@ -1,15 +1,17 @@ package org.bouncycastle.jce.provider.test; -import org.bouncycastle.util.encoders.Hex; -import org.bouncycastle.util.test.SimpleTest; -import org.bouncycastle.util.test.TestFailedException; +import java.security.Key; +import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; -import java.security.Key; + +import org.bouncycastle.util.encoders.Hex; +import org.bouncycastle.util.test.SimpleTest; +import org.bouncycastle.util.test.TestFailedException; public abstract class BaseBlockCipherTest extends SimpleTest @@ -104,9 +106,29 @@ public abstract class BaseBlockCipherTest byte[] out) throws Exception { + wrapTest(id, wrappingAlgorithm, kek, null, null, in, out); + } + + protected void wrapTest( + int id, + String wrappingAlgorithm, + byte[] kek, + byte[] iv, + SecureRandom rand, + byte[] in, + byte[] out) + throws Exception + { Cipher wrapper = Cipher.getInstance(wrappingAlgorithm, "BC"); - wrapper.init(Cipher.WRAP_MODE, new SecretKeySpec(kek, algorithm)); + if (iv != null) + { + wrapper.init(Cipher.WRAP_MODE, new SecretKeySpec(kek, algorithm), new IvParameterSpec(iv), rand); + } + else + { + wrapper.init(Cipher.WRAP_MODE, new SecretKeySpec(kek, algorithm), rand); + } try { @@ -125,7 +147,14 @@ public abstract class BaseBlockCipherTest fail("failed wrap test exception " + e.toString(), e); } - wrapper.init(Cipher.UNWRAP_MODE, new SecretKeySpec(kek, algorithm)); + if (iv != null) + { + wrapper.init(Cipher.UNWRAP_MODE, new SecretKeySpec(kek, algorithm), new IvParameterSpec(iv)); + } + else + { + wrapper.init(Cipher.UNWRAP_MODE, new SecretKeySpec(kek, algorithm)); + } try { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertPathBuilderTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertPathBuilderTest.java index 85f4fad4..42f5878a 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertPathBuilderTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertPathBuilderTest.java @@ -16,7 +16,6 @@ import java.security.cert.X509CRL; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.ArrayList; -import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashSet; @@ -49,8 +48,7 @@ public class CertPathBuilderTest list.add(interCrl); CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); CertStore store = CertStore.getInstance("Collection", ccsp, "BC"); - Calendar validDate = Calendar.getInstance(); - validDate.set(2008,8,4,14,49,10); + Date validDate = new Date(rootCrl.getThisUpdate().getTime() + 60 * 60 * 1000); //Searching for rootCert by subjectDN without CRL Set trust = new HashSet(); @@ -61,7 +59,7 @@ public class CertPathBuilderTest targetConstraints.setSubject(finalCert.getSubjectX500Principal().getEncoded()); PKIXBuilderParameters params = new PKIXBuilderParameters(trust, targetConstraints); params.addCertStore(store); - params.setDate(validDate.getTime()); + params.setDate(validDate); PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) cpb.build(params); CertPath path = result.getCertPath(); diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertPathValidatorTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertPathValidatorTest.java index d1857b83..d4c2b420 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertPathValidatorTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertPathValidatorTest.java @@ -21,8 +21,8 @@ import java.security.cert.X509CRL; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.ArrayList; -import java.util.Calendar; import java.util.Collection; +import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -216,8 +216,7 @@ public class CertPathValidatorTest CertStoreParameters ccsp = new CollectionCertStoreParameters(list); CertStore store = CertStore.getInstance("Collection", ccsp); - Calendar validDate = Calendar.getInstance(); - validDate.set(2010,0,8,2,21,10); + Date validDate = new Date(crl.getThisUpdate().getTime() + 60 * 60 * 1000); //validating path List certchain = new ArrayList(); @@ -237,11 +236,42 @@ public class CertPathValidatorTest param.setTargetCertConstraints(certSelector); param.addCertStore(store); param.setRevocationEnabled(true); - param.setDate(validDate.getTime()); + param.setDate(validDate); PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult)cpv.validate(cp, param); } + private void checkPolicyProcessingAtDomainMatch() + throws Exception + { + CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); + + X509Certificate root = (X509Certificate)cf.generateCertificate(this.getClass().getResourceAsStream("qvRooCa3.crt")); + X509Certificate ca1 = (X509Certificate)cf.generateCertificate(this.getClass().getResourceAsStream("suvaRoot1.crt")); + X509Certificate ca2 = (X509Certificate)cf.generateCertificate(this.getClass().getResourceAsStream("suvaEmail1.crt")); + X509Certificate ee = (X509Certificate)cf.generateCertificate(this.getClass().getResourceAsStream("suvaEE.crt")); + + List certchain = new ArrayList(); + certchain.add(ee); + certchain.add(ca2); + certchain.add(ca1); + + Set trust = new HashSet(); + trust.add(new TrustAnchor(root, null)); + + CertPathValidator cpv = CertPathValidator.getInstance("PKIX","BC"); + PKIXParameters param = new PKIXParameters(trust); + param.setRevocationEnabled(false); + + CertPath cp = cf.generateCertPath(certchain); + + MyChecker checker = new MyChecker(); + param.addCertPathChecker(checker); + + PKIXCertPathValidatorResult result = + (PKIXCertPathValidatorResult) cpv.validate(cp, param); + } + public void performTest() throws Exception { @@ -261,8 +291,7 @@ public class CertPathValidatorTest list.add(interCrl); CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); CertStore store = CertStore.getInstance("Collection", ccsp, "BC"); - Calendar validDate = Calendar.getInstance(); - validDate.set(2008,8,4,14,49,10); + Date validDate = new Date(rootCrl.getThisUpdate().getTime() + 60 * 60 * 1000); //validating path List certchain = new ArrayList(); certchain.add(finalCert); @@ -274,7 +303,7 @@ public class CertPathValidatorTest CertPathValidator cpv = CertPathValidator.getInstance("PKIX","BC"); PKIXParameters param = new PKIXParameters(trust); param.addCertStore(store); - param.setDate(validDate.getTime()); + param.setDate(validDate); MyChecker checker = new MyChecker(); param.addCertPathChecker(checker); @@ -310,8 +339,7 @@ public class CertPathValidatorTest ccsp = new CollectionCertStoreParameters(list); store = CertStore.getInstance("Collection", ccsp); - validDate = Calendar.getInstance(); - validDate.set(2004,2,21,2,21,10); + validDate = new Date(finalCert.getNotBefore().getTime() + 60 * 60 * 1000); //validating path certchain = new ArrayList(); @@ -325,7 +353,7 @@ public class CertPathValidatorTest param = new PKIXParameters(trust); param.addCertStore(store); param.setRevocationEnabled(false); - param.setDate(validDate.getTime()); + param.setDate(validDate); result =(PKIXCertPathValidatorResult) cpv.validate(cp, param); policyTree = result.getPolicyTree(); @@ -343,6 +371,7 @@ public class CertPathValidatorTest } checkCircProcessing(); + checkPolicyProcessingAtDomainMatch(); } public String getName() diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertTest.java index 7977f1c1..1ad59fa6 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CertTest.java @@ -1,85 +1,39 @@ package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; -import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair; -import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; -import java.security.PrivateKey; import java.security.PublicKey; -import java.security.SecureRandom; import java.security.Security; -import java.security.Signature; import java.security.cert.CRL; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; -import java.security.cert.CertificateParsingException; import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.Collection; -import java.util.Date; -import java.util.Hashtable; import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.Vector; -import javax.security.auth.x500.X500Principal; - -import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.DEREnumerated; -import org.bouncycastle.asn1.DERObjectIdentifier; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.asn1.cms.SignedData; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; -import org.bouncycastle.asn1.x509.CRLReason; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.asn1.x509.KeyPurposeId; -import org.bouncycastle.asn1.x509.X509CertificateStructure; -import org.bouncycastle.asn1.x509.X509Extension; -import org.bouncycastle.asn1.x509.X509Extensions; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.jce.X509KeyUsage; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.interfaces.ECPointEncoder; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.jce.spec.ECParameterSpec; -import org.bouncycastle.jce.spec.ECPrivateKeySpec; -import org.bouncycastle.jce.spec.ECPublicKeySpec; -import org.bouncycastle.jce.spec.GOST3410ParameterSpec; -import org.bouncycastle.math.ec.ECCurve; -import org.bouncycastle.util.Integers; import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.io.Streams; import org.bouncycastle.util.test.SimpleTest; -import org.bouncycastle.x509.X509V1CertificateGenerator; -import org.bouncycastle.x509.X509V2CRLGenerator; -import org.bouncycastle.x509.X509V3CertificateGenerator; -import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure; -import org.bouncycastle.x509.extension.X509ExtensionUtil; +import org.bouncycastle.util.test.TestFailedException; public class CertTest extends SimpleTest @@ -1255,7 +1209,8 @@ public class CertTest public void checkSelfSignedCertificate( int id, - byte[] bytes) + byte[] bytes, + String sigAlgName) { ByteArrayInputStream bIn; String dump = ""; @@ -1271,588 +1226,23 @@ public class CertTest PublicKey k = cert.getPublicKey(); cert.verify(k); - // System.out.println(cert); - } - catch (Exception e) - { - fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); - } - - } - - /** - * we generate a self signed certificate for the sake of testing - RSA - */ - public void checkCreation1() - throws Exception - { - // - // a sample key pair. - // - RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( - new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), - new BigInteger("11", 16)); - - RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( - new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), - new BigInteger("11", 16), - new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), - new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), - new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), - new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), - new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), - new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); - - // - // set up the keys - // - PrivateKey privKey; - PublicKey pubKey; - - KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); - - privKey = fact.generatePrivate(privKeySpec); - pubKey = fact.generatePublic(pubKeySpec); - - // - // distinguished name table. - // - Vector ord = new Vector(); - Vector values = new Vector(); - - ord.addElement(X509Principal.C); - ord.addElement(X509Principal.O); - ord.addElement(X509Principal.L); - ord.addElement(X509Principal.ST); - ord.addElement(X509Principal.E); - - values.addElement("AU"); - values.addElement("The Legion of the Bouncy Castle"); - values.addElement("Melbourne"); - values.addElement("Victoria"); - values.addElement("feedback-crypto@bouncycastle.org"); - - // - // extensions - // - - // - // create the certificate - version 3 - without extensions - // - X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); - - certGen.setSerialNumber(BigInteger.valueOf(1)); - certGen.setIssuerDN(new X509Principal(ord, values)); - certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen.setSubjectDN(new X509Principal(ord, values)); - certGen.setPublicKey(pubKey); - certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); - - X509Certificate cert = certGen.generate(privKey); - - cert.checkValidity(new Date()); - - cert.verify(pubKey); - - Set dummySet = cert.getNonCriticalExtensionOIDs(); - if (dummySet != null) - { - fail("non-critical oid set should be null"); - } - dummySet = cert.getCriticalExtensionOIDs(); - if (dummySet != null) - { - fail("critical oid set should be null"); - } - - // - // create the certificate - version 3 - with extensions - // - certGen = new X509V3CertificateGenerator(); - - certGen.setSerialNumber(BigInteger.valueOf(1)); - certGen.setIssuerDN(new X509Principal(ord, values)); - certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen.setSubjectDN(new X509Principal(ord, values)); - certGen.setPublicKey(pubKey); - certGen.setSignatureAlgorithm("MD5WithRSAEncryption"); - certGen.addExtension("2.5.29.15", true, - new X509KeyUsage(X509KeyUsage.encipherOnly)); - certGen.addExtension("2.5.29.37", true, - new DERSequence(KeyPurposeId.anyExtendedKeyUsage)); - certGen.addExtension("2.5.29.17", true, - new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); - - cert = certGen.generate(privKey); - - cert.checkValidity(new Date()); - - cert.verify(pubKey); - - ByteArrayInputStream sbIn = new ByteArrayInputStream(cert.getEncoded()); - ASN1InputStream sdIn = new ASN1InputStream(sbIn); - ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); - CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC"); - - cert = (X509Certificate)certFact.generateCertificate(bIn); - - if (!cert.getKeyUsage()[7]) - { - fail("error generating cert - key usage wrong."); - } - - List l = cert.getExtendedKeyUsage(); - if (!l.get(0).equals(KeyPurposeId.anyExtendedKeyUsage.getId())) - { - fail("failed extended key usage test"); - } - - Collection c = cert.getSubjectAlternativeNames(); - Iterator it = c.iterator(); - while (it.hasNext()) - { - List gn = (List)it.next(); - if (!gn.get(1).equals("test@test.test")) + if (sigAlgName != null && !sigAlgName.equals(((X509Certificate)cert).getSigAlgName())) { - fail("failed subject alternative names test"); + fail("sigAlgName not matched on certificate: " + sigAlgName); } - } - - // System.out.println(cert); - - // - // create the certificate - version 1 - // - X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator(); - - certGen1.setSerialNumber(BigInteger.valueOf(1)); - certGen1.setIssuerDN(new X509Principal(ord, values)); - certGen1.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen1.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen1.setSubjectDN(new X509Principal(ord, values)); - certGen1.setPublicKey(pubKey); - certGen1.setSignatureAlgorithm("MD5WithRSAEncryption"); - - cert = certGen1.generate(privKey); - - cert.checkValidity(new Date()); - - cert.verify(pubKey); - - bIn = new ByteArrayInputStream(cert.getEncoded()); - certFact = CertificateFactory.getInstance("X.509", "BC"); - - cert = (X509Certificate)certFact.generateCertificate(bIn); - - // System.out.println(cert); - if (!cert.getIssuerDN().equals(cert.getSubjectDN())) - { - fail("name comparison fails"); - } - } - - /** - * we generate a self signed certificate for the sake of testing - DSA - */ - public void checkCreation2() - { - // - // set up the keys - // - PrivateKey privKey; - PublicKey pubKey; - - try - { - KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN"); - - g.initialize(512, new SecureRandom()); - - KeyPair p = g.generateKeyPair(); - - privKey = p.getPrivate(); - pubKey = p.getPublic(); - } - catch (Exception e) - { - fail("error setting up keys - " + e.toString()); - return; - } - - // - // distinguished name table. - // - Vector ord = new Vector(); - Vector values = new Vector(); - - ord.addElement(X509Principal.C); - ord.addElement(X509Principal.O); - ord.addElement(X509Principal.L); - ord.addElement(X509Principal.ST); - ord.addElement(X509Principal.E); - - values.addElement("AU"); - values.addElement("The Legion of the Bouncy Castle"); - values.addElement("Melbourne"); - values.addElement("Victoria"); - values.addElement("feedback-crypto@bouncycastle.org"); - - // - // extensions - // - - // - // create the certificate - version 3 - // - X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); - - certGen.setSerialNumber(BigInteger.valueOf(1)); - certGen.setIssuerDN(new X509Principal(ord, values)); - certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen.setSubjectDN(new X509Principal(ord, values)); - certGen.setPublicKey(pubKey); - certGen.setSignatureAlgorithm("SHA1withDSA"); - - try - { - X509Certificate cert = certGen.generate(privKey); - - cert.checkValidity(new Date()); - - cert.verify(pubKey); - - ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); - CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); - - cert = (X509Certificate)fact.generateCertificate(bIn); // System.out.println(cert); } - catch (Exception e) - { - fail("error setting generating cert - " + e.toString()); - } - - // - // create the certificate - version 1 - // - X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator(); - - certGen1.setSerialNumber(BigInteger.valueOf(1)); - certGen1.setIssuerDN(new X509Principal(ord, values)); - certGen1.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen1.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen1.setSubjectDN(new X509Principal(ord, values)); - certGen1.setPublicKey(pubKey); - certGen1.setSignatureAlgorithm("SHA1withDSA"); - - try - { - X509Certificate cert = certGen1.generate(privKey); - - cert.checkValidity(new Date()); - - cert.verify(pubKey); - - ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); - CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); - - cert = (X509Certificate)fact.generateCertificate(bIn); - - //System.out.println(cert); - } - catch (Exception e) - { - fail("error setting generating cert - " + e.toString()); - } - - // - // exception test - // - try - { - certGen.setPublicKey(dudPublicKey); - - fail("key without encoding not detected in v1"); - } - catch (IllegalArgumentException e) - { - // expected - } - } - - /** - * we generate a self signed certificate for the sake of testing - ECDSA - */ - public void checkCreation3() - { - ECCurve curve = new ECCurve.Fp( - new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q - new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a - new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b - - ECParameterSpec spec = new ECParameterSpec( - curve, - curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n - - - ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec( - new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d - spec); - - ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( - curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q - spec); - - // - // set up the keys - // - PrivateKey privKey; - PublicKey pubKey; - - try - { - KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC"); - - privKey = fact.generatePrivate(privKeySpec); - pubKey = fact.generatePublic(pubKeySpec); - } - catch (Exception e) - { - fail("error setting up keys - " + e.toString()); - return; - } - - // - // distinguished name table. - // - Hashtable attrs = new Hashtable(); - Vector order = new Vector(); - - attrs.put(X509Principal.C, "AU"); - attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); - attrs.put(X509Principal.L, "Melbourne"); - attrs.put(X509Principal.ST, "Victoria"); - attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); - - order.addElement(X509Principal.C); - order.addElement(X509Principal.O); - order.addElement(X509Principal.L); - order.addElement(X509Principal.ST); - order.addElement(X509Principal.E); - - - // - // toString test - // - X509Principal p = new X509Principal(order, attrs); - String s = p.toString(); - - if (!s.equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne,ST=Victoria,E=feedback-crypto@bouncycastle.org")) + catch (TestFailedException e) { - fail("ordered X509Principal test failed - s = " + s + "."); - } - -// p = new X509Principal(attrs); -// s = p.toString(); -// -// // -// // we need two of these as the hash code for strings changed... -// // -// if (!s.equals("O=The Legion of the Bouncy Castle,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU") && !s.equals("ST=Victoria,L=Melbourne,C=AU,E=feedback-crypto@bouncycastle.org,O=The Legion of the Bouncy Castle")) -// { -// fail("unordered X509Principal test failed."); -// } - - // - // create the certificate - version 3 - // - X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); - - certGen.setSerialNumber(BigInteger.valueOf(1)); - certGen.setIssuerDN(new X509Principal(order, attrs)); - certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen.setSubjectDN(new X509Principal(order, attrs)); - certGen.setPublicKey(pubKey); - certGen.setSignatureAlgorithm("SHA1withECDSA"); - - try - { - X509Certificate cert = certGen.generate(privKey); - - cert.checkValidity(new Date()); - - cert.verify(pubKey); - - ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); - CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); - - cert = (X509Certificate)fact.generateCertificate(bIn); - - // - // try with point compression turned off - // - ((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED"); - - certGen.setPublicKey(pubKey); - - cert = certGen.generate(privKey, "BC"); - - cert.checkValidity(new Date()); - - cert.verify(pubKey); - - bIn = new ByteArrayInputStream(cert.getEncoded()); - fact = CertificateFactory.getInstance("X.509", "BC"); - - cert = (X509Certificate)fact.generateCertificate(bIn); - // System.out.println(cert); + throw e; } catch (Exception e) { - fail("error setting generating cert - " + e.toString()); - } - - X509Principal pr = new X509Principal("O=\"The Bouncy Castle, The Legion of\",E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU"); - - if (!pr.toString().equals("O=The Bouncy Castle\\, The Legion of,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU")) - { - fail("string based X509Principal test failed."); - } - - pr = new X509Principal("O=The Bouncy Castle\\, The Legion of,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU"); - - if (!pr.toString().equals("O=The Bouncy Castle\\, The Legion of,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU")) - { - fail("string based X509Principal test failed."); + fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } - - /** - * we generate a self signed certificate for the sake of testing - SHA224withECDSA - */ - private void createECCert(String algorithm, DERObjectIdentifier algOid) - throws Exception - { - ECCurve.Fp curve = new ECCurve.Fp( - new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p) - new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16), // a - new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16)); // b - - ECParameterSpec spec = new ECParameterSpec( - curve, - curve.decodePoint(Hex.decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G - new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n - - ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec( - new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d - spec); - - ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( - curve.decodePoint(Hex.decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q - spec); - - // - // set up the keys - // - PrivateKey privKey; - PublicKey pubKey; - - KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC"); - - privKey = fact.generatePrivate(privKeySpec); - pubKey = fact.generatePublic(pubKeySpec); - - - // - // distinguished name table. - // - Hashtable attrs = new Hashtable(); - Vector order = new Vector(); - - attrs.put(X509Principal.C, "AU"); - attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); - attrs.put(X509Principal.L, "Melbourne"); - attrs.put(X509Principal.ST, "Victoria"); - attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); - - order.addElement(X509Principal.C); - order.addElement(X509Principal.O); - order.addElement(X509Principal.L); - order.addElement(X509Principal.ST); - order.addElement(X509Principal.E); - - // - // create the certificate - version 3 - // - X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); - - certGen.setSerialNumber(BigInteger.valueOf(1)); - certGen.setIssuerDN(new X509Principal(order, attrs)); - certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen.setSubjectDN(new X509Principal(order, attrs)); - certGen.setPublicKey(pubKey); - certGen.setSignatureAlgorithm(algorithm); - - - X509Certificate cert = certGen.generate(privKey, "BC"); - - cert.checkValidity(new Date()); - - cert.verify(pubKey); - - ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); - CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC"); - - cert = (X509Certificate)certFact.generateCertificate(bIn); - - // - // try with point compression turned off - // - ((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED"); - - certGen.setPublicKey(pubKey); - - cert = certGen.generate(privKey, "BC"); - - cert.checkValidity(new Date()); - - cert.verify(pubKey); - - bIn = new ByteArrayInputStream(cert.getEncoded()); - certFact = CertificateFactory.getInstance("X.509", "BC"); - - cert = (X509Certificate)certFact.generateCertificate(bIn); - - if (!cert.getSigAlgOID().equals(algOid.toString())) - { - fail("ECDSA oid incorrect."); - } - - if (cert.getSigAlgParams() != null) - { - fail("sig parameters present"); - } - - Signature sig = Signature.getInstance(algorithm, "BC"); - - sig.initVerify(pubKey); - - sig.update(cert.getTBSCertificate()); - - if (!sig.verify(cert.getSignature())) - { - fail("EC certificate signature not mapped correctly."); - } - // System.out.println(cert); - } private void checkCRL( int id, @@ -1878,527 +1268,6 @@ public class CertTest } - public void checkCRLCreation1() - throws Exception - { - KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); - X509V2CRLGenerator crlGen = new X509V2CRLGenerator(); - Date now = new Date(); - KeyPair pair = kpGen.generateKeyPair(); - - crlGen.setIssuerDN(new X500Principal("CN=Test CA")); - - crlGen.setThisUpdate(now); - crlGen.setNextUpdate(new Date(now.getTime() + 100000)); - crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); - - crlGen.addCRLEntry(BigInteger.ONE, now, CRLReason.privilegeWithdrawn); - - crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic())); - - X509CRL crl = crlGen.generate(pair.getPrivate(), "BC"); - - if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA"))) - { - fail("failed CRL issuer test"); - } - - byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); - - if (authExt == null) - { - fail("failed to find CRL extension"); - } - - AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt); - - X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE); - - if (entry == null) - { - fail("failed to find CRL entry"); - } - - if (!entry.getSerialNumber().equals(BigInteger.ONE)) - { - fail("CRL cert serial number does not match"); - } - - if (!entry.hasExtensions()) - { - fail("CRL entry extension not found"); - } - - byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId()); - - if (ext != null) - { - DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext); - - if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) - { - fail("CRL entry reasonCode wrong"); - } - } - else - { - fail("CRL entry reasonCode not found"); - } - } - - public void checkCRLCreation2() - throws Exception - { - KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); - X509V2CRLGenerator crlGen = new X509V2CRLGenerator(); - Date now = new Date(); - KeyPair pair = kpGen.generateKeyPair(); - - crlGen.setIssuerDN(new X500Principal("CN=Test CA")); - - crlGen.setThisUpdate(now); - crlGen.setNextUpdate(new Date(now.getTime() + 100000)); - crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); - - Vector extOids = new Vector(); - Vector extValues = new Vector(); - - CRLReason crlReason = CRLReason.lookup(CRLReason.privilegeWithdrawn); - - try - { - extOids.addElement(X509Extensions.ReasonCode); - extValues.addElement(new X509Extension(false, new DEROctetString(crlReason.getEncoded()))); - } - catch (IOException e) - { - throw new IllegalArgumentException("error encoding reason: " + e); - } - - X509Extensions entryExtensions = new X509Extensions(extOids, extValues); - - crlGen.addCRLEntry(BigInteger.ONE, now, entryExtensions); - - crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic())); - - X509CRL crl = crlGen.generate(pair.getPrivate(), "BC"); - - if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA"))) - { - fail("failed CRL issuer test"); - } - - byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); - - if (authExt == null) - { - fail("failed to find CRL extension"); - } - - AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt); - - X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE); - - if (entry == null) - { - fail("failed to find CRL entry"); - } - - if (!entry.getSerialNumber().equals(BigInteger.ONE)) - { - fail("CRL cert serial number does not match"); - } - - if (!entry.hasExtensions()) - { - fail("CRL entry extension not found"); - } - - byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId()); - - if (ext != null) - { - DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext); - - if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) - { - fail("CRL entry reasonCode wrong"); - } - } - else - { - fail("CRL entry reasonCode not found"); - } - } - - public void checkCRLCreation3() - throws Exception - { - KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); - X509V2CRLGenerator crlGen = new X509V2CRLGenerator(); - Date now = new Date(); - KeyPair pair = kpGen.generateKeyPair(); - - crlGen.setIssuerDN(new X500Principal("CN=Test CA")); - - crlGen.setThisUpdate(now); - crlGen.setNextUpdate(new Date(now.getTime() + 100000)); - crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); - - Vector extOids = new Vector(); - Vector extValues = new Vector(); - - CRLReason crlReason = CRLReason.lookup(CRLReason.privilegeWithdrawn); - - try - { - extOids.addElement(X509Extensions.ReasonCode); - extValues.addElement(new X509Extension(false, new DEROctetString(crlReason.getEncoded()))); - } - catch (IOException e) - { - throw new IllegalArgumentException("error encoding reason: " + e); - } - - X509Extensions entryExtensions = new X509Extensions(extOids, extValues); - - crlGen.addCRLEntry(BigInteger.ONE, now, entryExtensions); - - crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic())); - - X509CRL crl = crlGen.generate(pair.getPrivate(), "BC"); - - if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA"))) - { - fail("failed CRL issuer test"); - } - - byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); - - if (authExt == null) - { - fail("failed to find CRL extension"); - } - - AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt); - - X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE); - - if (entry == null) - { - fail("failed to find CRL entry"); - } - - if (!entry.getSerialNumber().equals(BigInteger.ONE)) - { - fail("CRL cert serial number does not match"); - } - - if (!entry.hasExtensions()) - { - fail("CRL entry extension not found"); - } - - byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId()); - - if (ext != null) - { - DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext); - - if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) - { - fail("CRL entry reasonCode wrong"); - } - } - else - { - fail("CRL entry reasonCode not found"); - } - - // - // check loading of existing CRL - // - crlGen = new X509V2CRLGenerator(); - now = new Date(); - - crlGen.setIssuerDN(new X500Principal("CN=Test CA")); - - crlGen.setThisUpdate(now); - crlGen.setNextUpdate(new Date(now.getTime() + 100000)); - crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); - - crlGen.addCRL(crl); - - crlGen.addCRLEntry(BigInteger.valueOf(2), now, entryExtensions); - - crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic())); - - X509CRL newCrl = crlGen.generate(pair.getPrivate(), "BC"); - - int count = 0; - boolean oneFound = false; - boolean twoFound = false; - - Iterator it = newCrl.getRevokedCertificates().iterator(); - while (it.hasNext()) - { - X509CRLEntry crlEnt = (X509CRLEntry)it.next(); - - if (crlEnt.getSerialNumber().intValue() == 1) - { - oneFound = true; - } - else if (crlEnt.getSerialNumber().intValue() == 2) - { - twoFound = true; - } - - count++; - } - - if (count != 2) - { - fail("wrong number of CRLs found"); - } - - if (!oneFound || !twoFound) - { - fail("wrong CRLs found in copied list"); - } - - // - // check factory read back - // - CertificateFactory cFact = CertificateFactory.getInstance("X.509", "BC"); - - X509CRL readCrl = (X509CRL)cFact.generateCRL(new ByteArrayInputStream(newCrl.getEncoded())); - - if (readCrl == null) - { - fail("crl not returned!"); - } - - Collection col = cFact.generateCRLs(new ByteArrayInputStream(newCrl.getEncoded())); - - if (col.size() != 1) - { - fail("wrong number of CRLs found in collection"); - } - } - - /** - * we generate a self signed certificate for the sake of testing - GOST3410 - */ - public void checkCreation4() - throws Exception - { - // - // set up the keys - // - PrivateKey privKey; - PublicKey pubKey; - - KeyPairGenerator g = KeyPairGenerator.getInstance("GOST3410", "BC"); - GOST3410ParameterSpec gost3410P = new GOST3410ParameterSpec("GostR3410-94-CryptoPro-A"); - - g.initialize(gost3410P, new SecureRandom()); - - KeyPair p = g.generateKeyPair(); - - privKey = p.getPrivate(); - pubKey = p.getPublic(); - - // - // distinguished name table. - // - Hashtable attrs = new Hashtable(); - Vector order = new Vector(); - - attrs.put(X509Principal.C, "AU"); - attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); - attrs.put(X509Principal.L, "Melbourne"); - attrs.put(X509Principal.ST, "Victoria"); - attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); - - order.addElement(X509Principal.C); - order.addElement(X509Principal.O); - order.addElement(X509Principal.L); - order.addElement(X509Principal.ST); - order.addElement(X509Principal.E); - - // - // extensions - // - - // - // create the certificate - version 3 - // - X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); - - certGen.setSerialNumber(BigInteger.valueOf(1)); - certGen.setIssuerDN(new X509Principal(order, attrs)); - certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen.setSubjectDN(new X509Principal(order, attrs)); - certGen.setPublicKey(pubKey); - certGen.setSignatureAlgorithm("GOST3411withGOST3410"); - - X509Certificate cert = certGen.generate(privKey, "BC"); - - cert.checkValidity(new Date()); - - // - // check verifies in general - // - cert.verify(pubKey); - - // - // check verifies with contained key - // - cert.verify(cert.getPublicKey()); - - ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); - CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); - - cert = (X509Certificate)fact.generateCertificate(bIn); - - //System.out.println(cert); - - //check getEncoded() - byte[] bytesch = cert.getEncoded(); - } - - public void checkCreation5() - throws Exception - { - // - // a sample key pair. - // - RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( - new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), - new BigInteger("11", 16)); - - RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( - new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), - new BigInteger("11", 16), - new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), - new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), - new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), - new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), - new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), - new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); - - // - // set up the keys - // - SecureRandom rand = new SecureRandom(); - PrivateKey privKey; - PublicKey pubKey; - - KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); - - privKey = fact.generatePrivate(privKeySpec); - pubKey = fact.generatePublic(pubKeySpec); - - // - // distinguished name table. - // - Vector ord = new Vector(); - Vector values = new Vector(); - - ord.addElement(X509Principal.C); - ord.addElement(X509Principal.O); - ord.addElement(X509Principal.L); - ord.addElement(X509Principal.ST); - ord.addElement(X509Principal.E); - - values.addElement("AU"); - values.addElement("The Legion of the Bouncy Castle"); - values.addElement("Melbourne"); - values.addElement("Victoria"); - values.addElement("feedback-crypto@bouncycastle.org"); - - // - // create base certificate - version 3 - // - X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); - - certGen.setSerialNumber(BigInteger.valueOf(1)); - certGen.setIssuerDN(new X509Principal(ord, values)); - certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen.setSubjectDN(new X509Principal(ord, values)); - certGen.setPublicKey(pubKey); - certGen.setSignatureAlgorithm("MD5WithRSAEncryption"); - certGen.addExtension("2.5.29.15", true, - new X509KeyUsage(X509KeyUsage.encipherOnly)); - certGen.addExtension("2.5.29.37", true, - new DERSequence(KeyPurposeId.anyExtendedKeyUsage)); - certGen.addExtension("2.5.29.17", true, - new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); - - X509Certificate baseCert = certGen.generate(privKey, "BC"); - - // - // copy certificate - // - certGen = new X509V3CertificateGenerator(); - - certGen.setSerialNumber(BigInteger.valueOf(1)); - certGen.setIssuerDN(new X509Principal(ord, values)); - certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen.setSubjectDN(new X509Principal(ord, values)); - certGen.setPublicKey(pubKey); - certGen.setSignatureAlgorithm("MD5WithRSAEncryption"); - - certGen.copyAndAddExtension(new DERObjectIdentifier("2.5.29.15"), true, baseCert); - certGen.copyAndAddExtension("2.5.29.37", false, baseCert); - - X509Certificate cert = certGen.generate(privKey, "BC"); - - cert.checkValidity(new Date()); - - cert.verify(pubKey); - - if (!areEqual(baseCert.getExtensionValue("2.5.29.15"), cert.getExtensionValue("2.5.29.15"))) - { - fail("2.5.29.15 differs"); - } - - if (!areEqual(baseCert.getExtensionValue("2.5.29.37"), cert.getExtensionValue("2.5.29.37"))) - { - fail("2.5.29.37 differs"); - } - - // - // exception test - // - try - { - certGen.copyAndAddExtension("2.5.99.99", true, baseCert); - - fail("exception not thrown on dud extension copy"); - } - catch (CertificateParsingException e) - { - // expected - } - - try - { - certGen.setPublicKey(dudPublicKey); - - certGen.generate(privKey, "BC"); - - fail("key without encoding not detected in v3"); - } - catch (IllegalArgumentException e) - { - // expected - } - } - private void testForgedSignature() throws Exception { @@ -2473,7 +1342,7 @@ public class CertTest ASN1EncodableVector certs = new ASN1EncodableVector(); certs.add(new ASN1InputStream(CertPathTest.rootCertBin).readObject()); - certs.add(new DERTaggedObject(false, 2, new ASN1InputStream(AttrCertTest.attrCert).readObject())); + certs.add(new DERTaggedObject(false, 2, new ASN1InputStream(AttrCertData.attrCert).readObject())); ASN1EncodableVector crls = new ASN1EncodableVector(); @@ -2494,6 +1363,12 @@ public class CertTest { fail("PKCS7 crl not read"); } + + if (!"SHA256WITHRSA".equals(crl.getSigAlgName())) + { + fail("signature ID not matched in CRL: " + crl.getSigAlgName()); + } + Collection col = cf.generateCertificates(new ByteArrayInputStream(info.getEncoded())); if (col.size() != 1 || !col.contains(cert)) { @@ -2557,90 +1432,6 @@ public class CertTest } } - private void createPSSCert(String algorithm) - throws Exception - { - KeyPair pair = generateLongFixedKeys(); - - PrivateKey privKey = pair.getPrivate(); - PublicKey pubKey = pair.getPublic(); - - // - // distinguished name table. - // - Vector ord = new Vector(); - Vector values = new Vector(); - - ord.addElement(X509Principal.C); - ord.addElement(X509Principal.O); - ord.addElement(X509Principal.L); - ord.addElement(X509Principal.ST); - ord.addElement(X509Principal.E); - - values.addElement("AU"); - values.addElement("The Legion of the Bouncy Castle"); - values.addElement("Melbourne"); - values.addElement("Victoria"); - values.addElement("feedback-crypto@bouncycastle.org"); - - // - // create base certificate - version 3 - // - X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); - - certGen.setSerialNumber(BigInteger.valueOf(1)); - certGen.setIssuerDN(new X509Principal(ord, values)); - certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen.setSubjectDN(new X509Principal(ord, values)); - certGen.setPublicKey(pubKey); - certGen.setSignatureAlgorithm(algorithm); - certGen.addExtension("2.5.29.15", true, - new X509KeyUsage(X509KeyUsage.encipherOnly)); - certGen.addExtension("2.5.29.37", true, - new DERSequence(KeyPurposeId.anyExtendedKeyUsage)); - certGen.addExtension(Extension.subjectAlternativeName.getId(), true, - new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); - certGen.addExtension(Extension.issuerAlternativeName, false, - new GeneralNames(new GeneralName(GeneralName.directoryName, new X500Name("O=Test, OU=Testing, C=AU")))); - - X509Certificate baseCert = certGen.generate(privKey, "BC"); - - Collection names = baseCert.getSubjectAlternativeNames(); - - if (names.size() != 1) - { - fail("subject alt names size incorrect"); - } - - List name = (List)names.iterator().next(); - if(!name.get(0).equals(Integers.valueOf(GeneralName.rfc822Name))) - { - fail("subject alt name type incorrect"); - } - - names = baseCert.getIssuerAlternativeNames(); - - if (names.size() != 1) - { - fail("issuer alt names size incorrect"); - } - - name = (List)names.iterator().next(); - if(!name.get(0).equals(Integers.valueOf(GeneralName.directoryName))) - { - fail("issuer alt name type incorrect"); - } - - // check IETF output (reverse of default BC) - if (!name.get(1).equals("c=AU,ou=Testing,o=Test")) - { - fail("issuer alt name dir string incorrect"); - } - - baseCert.verify(pubKey); - } - private KeyPair generateLongFixedKeys() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException { @@ -2677,55 +1468,6 @@ public class CertTest x509.verify(x509.getPublicKey(), "BC"); } - private void testNullDerNullCert() - throws Exception - { - KeyPair pair = generateLongFixedKeys(); - PublicKey pubKey = pair.getPublic(); - PrivateKey privKey = pair.getPrivate(); - - X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); - - certGen.setSerialNumber(BigInteger.valueOf(1)); - certGen.setIssuerDN(new X509Principal("CN=Test")); - certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); - certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); - certGen.setSubjectDN(new X509Principal("CN=Test")); - certGen.setPublicKey(pubKey); - certGen.setSignatureAlgorithm("MD5WithRSAEncryption"); - X509Certificate cert = certGen.generate(privKey, "BC"); - - X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded())); - - ASN1Encodable tbsCertificate = struct.getTBSCertificate(); - AlgorithmIdentifier sig = struct.getSignatureAlgorithm(); - - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(tbsCertificate); - v.add(new AlgorithmIdentifier(sig.getObjectId())); - v.add(struct.getSignature()); - - // verify - ByteArrayInputStream bIn; - String dump = ""; - - try - { - bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded()); - - CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); - - cert = (X509Certificate)fact.generateCertificate(bIn); - - cert.verify(cert.getPublicKey()); - } - catch (Exception e) - { - fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e); - } - } - private void checkComparison(byte[] encCert) throws NoSuchProviderException, CertificateException { @@ -2740,10 +1482,11 @@ public class CertTest fail("BC/Sun equals test failed"); } - if (bcCert.hashCode() != sunCert.hashCode()) - { - fail("BC/Sun hashCode test failed"); - } + // Yes, they actually changed hashCode() on a certificate in JDK 1.8... +// if (bcCert.hashCode() != sunCert.hashCode()) +// { +// fail("BC/Sun hashCode test failed"); +// } } private void testV1CRL() @@ -2762,7 +1505,6 @@ public class CertTest jceCRL.verify(jceIssuer.getPublicKey()); - // verify CRL with BC provider CertificateFactory bcFac = CertificateFactory.getInstance("X.509", "BC"); @@ -2774,6 +1516,16 @@ public class CertTest jceCRL.verify(bcIssuer.getPublicKey()); bcCRL.verify(bcIssuer.getPublicKey()); + + if (!"SHA1WITHRSA".equals(bcCRL.getSigAlgName())) + { + fail("signature ID not matched in CRL"); + } + + if (!"SHA1WITHRSA".equals(bcIssuer.getSigAlgName())) + { + fail("signature ID not matched in certificate"); + } } private void testCertPathEncAvailableTest() @@ -2818,24 +1570,24 @@ public class CertTest checkComparison(cert1); checkKeyUsage(8, keyUsage); - checkSelfSignedCertificate(9, uncompressedPtEC); + checkSelfSignedCertificate(9, uncompressedPtEC, "ECDSA"); checkNameCertificate(10, nameCert); - checkSelfSignedCertificate(11, probSelfSignedCert); - checkSelfSignedCertificate(12, gostCA1); - checkSelfSignedCertificate(13, gostCA2); - checkSelfSignedCertificate(14, gost341094base); - checkSelfSignedCertificate(15, gost34102001base); - checkSelfSignedCertificate(16, gost341094A); - checkSelfSignedCertificate(17, gost341094B); - checkSelfSignedCertificate(18, gost34102001A); + checkSelfSignedCertificate(11, probSelfSignedCert, "SHA1WITHRSA"); + checkSelfSignedCertificate(12, gostCA1, "GOST3410"); + checkSelfSignedCertificate(13, gostCA2, "GOST3411WITHECGOST3410"); + checkSelfSignedCertificate(14, gost341094base, "GOST3410"); + checkSelfSignedCertificate(15, gost34102001base, "GOST3411WITHECGOST3410"); + checkSelfSignedCertificate(16, gost341094A, "GOST3410"); + checkSelfSignedCertificate(17, gost341094B, "GOST3410"); + checkSelfSignedCertificate(18, gost34102001A, "GOST3411WITHECGOST3410"); try { - checkSelfSignedCertificate(19, uaczo1); - checkSelfSignedCertificate(20, uaczo2); - checkSelfSignedCertificate(21, uaczo3); - checkSelfSignedCertificate(22, uaczo4); + checkSelfSignedCertificate(19, uaczo1, "GOST3411WITHDSTU4145LE"); + checkSelfSignedCertificate(20, uaczo2, "GOST3411WITHDSTU4145LE"); + checkSelfSignedCertificate(21, uaczo3, "GOST3411WITHDSTU4145LE"); + checkSelfSignedCertificate(22, uaczo4, "GOST3411WITHDSTU4145LE"); } catch (Exception e) { @@ -2847,35 +1599,12 @@ public class CertTest checkCRL(1, crl1); - checkCreation1(); - checkCreation2(); - checkCreation3(); - checkCreation4(); - checkCreation5(); - - createECCert("SHA1withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1); - createECCert("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); - createECCert("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); - createECCert("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); - createECCert("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); - - createPSSCert("SHA1withRSAandMGF1"); - createPSSCert("SHA224withRSAandMGF1"); - createPSSCert("SHA256withRSAandMGF1"); - createPSSCert("SHA384withRSAandMGF1"); - - checkCRLCreation1(); - checkCRLCreation2(); - checkCRLCreation3(); - pemTest(); pkcs7Test(); rfc4491Test(); testForgedSignature(); - testNullDerNullCert(); - checkCertificate(18, emptyDNCert); testCertPathEncAvailableTest(); diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CipherStreamTest2.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CipherStreamTest2.java index de9533c2..2201c8a6 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CipherStreamTest2.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/CipherStreamTest2.java @@ -1,14 +1,10 @@ package org.bouncycastle.jce.provider.test; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; +import java.io.*; import java.security.Key; import java.security.Security; -import javax.crypto.Cipher; -import javax.crypto.KeyGenerator; +import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import org.bouncycastle.crypto.io.InvalidCipherTextIOException; @@ -21,9 +17,11 @@ import org.bouncycastle.util.test.SimpleTest; public class CipherStreamTest2 extends SimpleTest { + private int streamSize; + public String getName() { - return "CipherStreamTest"; + return "CipherStreamTest2"; } private void testModes(String algo, String[] transforms, boolean authenticated) @@ -33,32 +31,38 @@ public class CipherStreamTest2 for (int i = 0; i != transforms.length; i++) { String transform = transforms[i]; + String cipherName = algo + transform; - testWriteRead(algo + transform, key, authenticated, true, false); - testWriteRead(algo + transform, key, authenticated, true, true); - testWriteRead(algo + transform, key, authenticated, false, false); - testWriteRead(algo + transform, key, authenticated, false, true); - testReadWrite(algo + transform, key, authenticated, true, false); - testReadWrite(algo + transform, key, authenticated, true, true); - testReadWrite(algo + transform, key, authenticated, false, false); - testReadWrite(algo + transform, key, authenticated, false, true); - - if (!(transform.indexOf("CTS") > -1)) + boolean cts = transform.indexOf("CTS") > -1; + if (cts && streamSize < Cipher.getInstance(cipherName, "BC").getBlockSize()) + { + continue; + } + testWriteRead(cipherName, key, authenticated, true, false); + testWriteRead(cipherName, key, authenticated, true, true); + testWriteRead(cipherName, key, authenticated, false, false); + testWriteRead(cipherName, key, authenticated, false, true); + testReadWrite(cipherName, key, authenticated, true, false); + testReadWrite(cipherName, key, authenticated, true, true); + testReadWrite(cipherName, key, authenticated, false, false); + testReadWrite(cipherName, key, authenticated, false, true); + + if (!cts) { - testWriteReadEmpty(algo + transform, key, authenticated, true, false); - testWriteReadEmpty(algo + transform, key, authenticated, true, true); - testWriteReadEmpty(algo + transform, key, authenticated, false, false); - testWriteReadEmpty(algo + transform, key, authenticated, false, true); + testWriteReadEmpty(cipherName, key, authenticated, true, false); + testWriteReadEmpty(cipherName, key, authenticated, true, true); + testWriteReadEmpty(cipherName, key, authenticated, false, false); + testWriteReadEmpty(cipherName, key, authenticated, false, true); } if (authenticated) { - testTamperedRead(algo + transform, key, true, true); - testTamperedRead(algo + transform, key, true, false); - testTruncatedRead(algo + transform, key, true, true); - testTruncatedRead(algo + transform, key, true, false); - testTamperedWrite(algo + transform, key, true, true); - testTamperedWrite(algo + transform, key, true, false); + testTamperedRead(cipherName, key, true, true); + testTamperedRead(cipherName, key, true, false); + testTruncatedRead(cipherName, key, true, true); + testTruncatedRead(cipherName, key, true, false); + testTamperedWrite(cipherName, key, true, true); + testTamperedWrite(cipherName, key, true, false); } } } @@ -94,7 +98,7 @@ public class CipherStreamTest2 decrypt.init(Cipher.DECRYPT_MODE, key); } - byte[] ciphertext = encrypt.doFinal(new byte[1000]); + byte[] ciphertext = encrypt.doFinal(new byte[streamSize]); // Tamper ciphertext[0] += 1; @@ -111,6 +115,10 @@ public class CipherStreamTest2 { // Expected } + catch (IOException e) // cause will be AEADBadTagException + { + // Expected + } try { input.close(); @@ -140,10 +148,10 @@ public class CipherStreamTest2 decrypt.init(Cipher.DECRYPT_MODE, key); } - byte[] ciphertext = encrypt.doFinal(new byte[1000]); + byte[] ciphertext = encrypt.doFinal(new byte[streamSize]); // Truncate to just smaller than complete tag - byte[] truncated = new byte[ciphertext.length - 1000 - 1]; + byte[] truncated = new byte[ciphertext.length - streamSize - 1]; System.arraycopy(ciphertext, 0, truncated, 0, truncated.length); // Tamper @@ -162,6 +170,11 @@ public class CipherStreamTest2 // Expected break; } + catch (IOException e) + { + // Expected from JDK 1.7 on + break; + } catch (Exception e) { fail("Unexpected exception : " + name, e, authenticated, useBc); @@ -201,7 +214,7 @@ public class CipherStreamTest2 decrypt.init(Cipher.DECRYPT_MODE, key); } - byte[] ciphertext = encrypt.doFinal(new byte[1000]); + byte[] ciphertext = encrypt.doFinal(new byte[streamSize]); // Tamper ciphertext[0] += 1; @@ -230,7 +243,7 @@ public class CipherStreamTest2 private void testWriteRead(String name, Key key, boolean authenticated, boolean useBc, boolean blocks) throws Exception { - byte[] data = new byte[1000]; + byte[] data = new byte[streamSize]; for (int i = 0; i < data.length; i++) { data[i] = (byte)(i % 255); @@ -271,10 +284,10 @@ public class CipherStreamTest2 OutputStream cOut = createOutputStream(bOut, encrypt, useBc); if (blocks) { - int chunkSize = data.length / 8; + int chunkSize = Math.max(1, data.length / 8); for (int i = 0; i < data.length; i += chunkSize) { - cOut.write(data, i, chunkSize); + cOut.write(data, i, Math.min(chunkSize, data.length - i)); } } else @@ -434,6 +447,17 @@ public class CipherStreamTest2 public void performTest() throws Exception { + int[] testSizes = new int[]{0, 1, 7, 8, 9, 15, 16, 17, 1023, 1024, 1025, 2047, 2048, 2049, 4095, 4096, 4097}; + for (int i = 0; i < testSizes.length; i++) + { + this.streamSize = testSizes[i]; + performTests(); + } + } + + private void performTests() + throws Exception + { final String[] blockCiphers64 = new String[]{"BLOWFISH", "DES", "DESEDE", "TEA", "CAST5", "RC2", "XTEA"}; for (int i = 0; i != blockCiphers64.length; i++) diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/DHTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/DHTest.java index 4ab21edf..6b9ad4e5 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/DHTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/DHTest.java @@ -33,9 +33,11 @@ import javax.crypto.spec.DHPublicKeySpec; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; +import org.bouncycastle.jce.ECNamedCurveTable; import org.bouncycastle.jce.ECPointUtil; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; @@ -567,6 +569,53 @@ public class DHTest fail(size + " bit 3-way test failed (c and b differ)"); } } + + private void testECDH(String algorithm, String cipher, int keyLen) + throws Exception + { + ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec("secp521r1"); + KeyPairGenerator g = KeyPairGenerator.getInstance(algorithm, "BC"); + + g.initialize(parameterSpec); + + // + // a side + // + KeyPair aKeyPair = g.generateKeyPair(); + + KeyAgreement aKeyAgree = KeyAgreement.getInstance(algorithm, "BC"); + + aKeyAgree.init(aKeyPair.getPrivate()); + + // + // b side + // + KeyPair bKeyPair = g.generateKeyPair(); + + KeyAgreement bKeyAgree = KeyAgreement.getInstance(algorithm, "BC"); + + bKeyAgree.init(bKeyPair.getPrivate()); + + // + // agreement + // + aKeyAgree.doPhase(bKeyPair.getPublic(), true); + bKeyAgree.doPhase(aKeyPair.getPublic(), true); + + SecretKey k1 = aKeyAgree.generateSecret(cipher); + SecretKey k2 = bKeyAgree.generateSecret(cipher); + + if (!k1.equals(k2)) + { + fail(algorithm + " 2-way test failed"); + } + + if (k1.getEncoded().length != keyLen / 8) + { + fail("key for " + cipher + " the wrong size expected " + keyLen / 8 + " got " + k1.getEncoded().length); + } + } + private void testECDH(String algorithm) throws Exception { @@ -915,8 +964,15 @@ public class DHTest testGP("DIFFIEHELLMAN", 1024, 256, g1024, p1024); testExplicitWrapping(512, 0, g512, p512); testRandom(256); + testECDH("ECDH"); testECDH("ECDHC"); + testECDH("ECDH", "AES", 256); + testECDH("ECDH", "DESEDE", 192); + testECDH("ECDH", "DES", 64); + testECDH("ECDHwithSHA1KDF", "AES", 256); + testECDH("ECDHwithSHA1KDF", "DESEDE", 192); + testExceptions(); testDESAndDESede(g768, p768); testInitialise(); diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/DSATest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/DSATest.java index e0478997..3e2ebd41 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/DSATest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/DSATest.java @@ -25,10 +25,10 @@ import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1Integer; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERInteger; -import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; @@ -191,7 +191,7 @@ public class DSATest signer.init(false, keyParams); - if (!signer.verifySignature(dummySha1, DERInteger.getInstance(derSig.getObjectAt(0)).getValue(), DERInteger.getInstance(derSig.getObjectAt(1)).getValue())) + if (!signer.verifySignature(dummySha1, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue())) { fail("NONEwithDSA not really NONE!"); } @@ -474,7 +474,7 @@ public class DSATest } } - private void testECDSA239bitBinary(String algorithm, DERObjectIdentifier oid) + private void testECDSA239bitBinary(String algorithm, ASN1ObjectIdentifier oid) throws Exception { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); @@ -971,8 +971,8 @@ public class DSATest BigInteger[] sig = new BigInteger[2]; - sig[0] = ((DERInteger)s.getObjectAt(0)).getValue(); - sig[1] = ((DERInteger)s.getObjectAt(1)).getValue(); + sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); + sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); return sig; } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECDSA5Test.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECDSA5Test.java index 802134c1..87773da8 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECDSA5Test.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECDSA5Test.java @@ -11,11 +11,14 @@ import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; +import java.security.SignatureException; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; import java.security.spec.AlgorithmParameterSpec; @@ -27,22 +30,29 @@ import java.security.spec.ECPoint; import java.security.spec.ECPrivateKeySpec; import java.security.spec.ECPublicKeySpec; import java.security.spec.EllipticCurve; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERInteger; +import org.bouncycastle.asn1.bsi.BSIObjectIdentifiers; +import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.sec.SECObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X962Parameters; +import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; +import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil; import org.bouncycastle.jce.ECKeyUtil; import org.bouncycastle.jce.ECNamedCurveTable; import org.bouncycastle.jce.ECPointUtil; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.FixedSecureRandom; @@ -150,6 +160,61 @@ public class ECDSA5Test } } + // test BSI algorithm support. + private void testBSI() + throws Exception + { + KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ECDSA", "BC"); + + kpGen.initialize(new ECGenParameterSpec(TeleTrusTObjectIdentifiers.brainpoolP512r1.getId())); + + KeyPair kp = kpGen.generateKeyPair(); + + byte[] data = "Hello World!!!".getBytes(); + String[] cvcAlgs = { "SHA1WITHCVC-ECDSA", "SHA224WITHCVC-ECDSA", + "SHA256WITHCVC-ECDSA", "SHA384WITHCVC-ECDSA", + "SHA512WITHCVC-ECDSA" }; + String[] cvcOids = { EACObjectIdentifiers.id_TA_ECDSA_SHA_1.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_224.getId(), + EACObjectIdentifiers.id_TA_ECDSA_SHA_256.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_384.getId(), + EACObjectIdentifiers.id_TA_ECDSA_SHA_512.getId() }; + + testBsiAlgorithms(kp, data, cvcAlgs, cvcOids); + + String[] plainAlgs = { "SHA1WITHPLAIN-ECDSA", "SHA224WITHPLAIN-ECDSA", + "SHA256WITHPLAIN-ECDSA", "SHA384WITHPLAIN-ECDSA", + "SHA512WITHPLAIN-ECDSA", "RIPEMD160WITHPLAIN-ECDSA" }; + String[] plainOids = { BSIObjectIdentifiers.ecdsa_plain_SHA1.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA224.getId(), + BSIObjectIdentifiers.ecdsa_plain_SHA256.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA384.getId(), + BSIObjectIdentifiers.ecdsa_plain_SHA512.getId(), BSIObjectIdentifiers.ecdsa_plain_RIPEMD160.getId() }; + + testBsiAlgorithms(kp, data, plainAlgs, plainOids); + } + + private void testBsiAlgorithms(KeyPair kp, byte[] data, String[] algs, String[] oids) + throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException + { + for (int i = 0; i != algs.length; i++) + { + Signature sig1 = Signature.getInstance(algs[i], "BC"); + Signature sig2 = Signature.getInstance(oids[i], "BC"); + + sig1.initSign(kp.getPrivate()); + + sig1.update(data); + + byte[] sig = sig1.sign(); + + sig2.initVerify(kp.getPublic()); + + sig2.update(data); + + if (!sig2.verify(sig)) + { + fail("BSI CVC signature failed: " + algs[i]); + } + } + } + /** * X9.62 - 1998,<br> * J.2.1, Page 100, ECDSA over the field F2m<br> @@ -695,8 +760,16 @@ public class ECDSA5Test { public void nextBytes(byte[] bytes) { - byte[] src = BigInteger.valueOf(1000).toByteArray(); - System.arraycopy(src, 0, bytes, bytes.length - src.length, src.length); + byte[] src = new BigInteger("e2eb6663f551331bda00b90f1272c09d980260c1a70cab1ec481f6c937f34b62", 16).toByteArray(); + + if (src.length <= bytes.length) + { + System.arraycopy(src, 0, bytes, bytes.length - src.length, src.length); + } + else + { + System.arraycopy(src, 0, bytes, 0, bytes.length); + } } } @@ -734,6 +807,87 @@ public class ECDSA5Test } } + private void testNamedCurveSigning() + throws Exception + { + testCustomNamedCurveSigning("secp256r1"); + + try + { + testCustomNamedCurveSigning("secp256k1"); + } + catch (IllegalArgumentException e) + { + if (!e.getMessage().equals("first coefficient is negative")) // bogus jdk 1.5 exception... + { + throw e; + } + } + } + + private void testCustomNamedCurveSigning(String name) + throws Exception + { + X9ECParameters x9Params = ECUtil.getNamedCurveByOid(ECUtil.getNamedCurveOid(name)); + + // TODO: one day this may have to change + if (x9Params.getCurve() instanceof ECCurve.Fp) + { + fail("curve not custom curve!!"); + } + + AlgorithmParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(name); + KeyPairGenerator keygen = KeyPairGenerator.getInstance("EC", "BC"); + keygen.initialize(ecSpec, new ECRandom()); + + KeyPair keys = keygen.generateKeyPair(); + + PrivateKeyInfo priv1 = PrivateKeyInfo.getInstance(keys.getPrivate().getEncoded()); + SubjectPublicKeyInfo pub1 = SubjectPublicKeyInfo.getInstance(keys.getPublic().getEncoded()); + + keygen = KeyPairGenerator.getInstance("EC", "BC"); + keygen.initialize(new ECGenParameterSpec("secp256r1"), new ECRandom()); + + Signature ecdsaSigner = Signature.getInstance("ECDSA", "BC"); + + ecdsaSigner.initSign(keys.getPrivate()); + + ecdsaSigner.update(new byte[100]); + + byte[] sig = ecdsaSigner.sign(); + + ecdsaSigner.initVerify(keys.getPublic()); + + ecdsaSigner.update(new byte[100]); + + if (!ecdsaSigner.verify(sig)) + { + fail("signature failed to verify"); + } + + KeyFactory kFact = KeyFactory.getInstance("EC", "BC"); + + PublicKey pub = kFact.generatePublic(new X509EncodedKeySpec(pub1.getEncoded())); + PrivateKey pri = kFact.generatePrivate(new PKCS8EncodedKeySpec(priv1.getEncoded())); + + ecdsaSigner = Signature.getInstance("ECDSA", "BC"); + + ecdsaSigner.initSign(pri); + + ecdsaSigner.update(new byte[100]); + + sig = ecdsaSigner.sign(); + + ecdsaSigner.initVerify(pub); + + ecdsaSigner.update(new byte[100]); + + if (!ecdsaSigner.verify(sig)) + { + fail("signature failed to verify"); + } + } + protected BigInteger[] derDecode( byte[] encoding) throws IOException @@ -744,8 +898,8 @@ public class ECDSA5Test BigInteger[] sig = new BigInteger[2]; - sig[0] = ((DERInteger)s.getObjectAt(0)).getValue(); - sig[1] = ((DERInteger)s.getObjectAt(1)).getValue(); + sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); + sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); return sig; } @@ -766,6 +920,8 @@ public class ECDSA5Test testGeneration(); testKeyPairGenerationWithOIDs(); testNamedCurveParameterPreservation(); + testNamedCurveSigning(); + testBSI(); } public static void main( diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECIESTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECIESTest.java index 9af0670a..ad2b8b25 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECIESTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECIESTest.java @@ -1,5 +1,6 @@ package org.bouncycastle.jce.provider.test; +import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; @@ -85,8 +86,30 @@ public class ECIESTest // Testing ECIES with 256-bit curve using DES g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithDESEDE", params); - - + + // Testing ECIES with 256-bit curve using DES-CBC + g.initialize(256, new SecureRandom()); + doTest("256-bit", g, "ECIESwithDESEDE-CBC", params); + + params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("0001020304050607")); + g.initialize(256, new SecureRandom()); + doTest("256-bit", g, "ECIESwithDESEDE-CBC", params); + + try + { + params = new IESParameterSpec(derivation, encoding, 128, 128, new byte[10]); + g.initialize(256, new SecureRandom()); + doTest("256-bit", g, "ECIESwithDESEDE-CBC", params); + fail("DESEDE no exception!"); + } + catch (InvalidAlgorithmParameterException e) + { + if (!e.getMessage().equals("NONCE in IES Parameters needs to be 8 bytes long")) + { + fail("DESEDE wrong message!"); + } + } + c1 = new org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.ECIESwithAES(); c2 = new org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.ECIESwithAES(); params = new IESParameterSpec(derivation, encoding, 128, 128); @@ -102,7 +125,29 @@ public class ECIESTest // Testing ECIES with 256-bit curve using AES g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithAES", params); - + + // Testing ECIES with 256-bit curve using AES-CBC + g.initialize(256, new SecureRandom()); + doTest("256-bit", g, "ECIESwithAES-CBC", params); + + params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("000102030405060708090a0b0c0d0e0f")); + g.initialize(256, new SecureRandom()); + doTest("256-bit", g, "ECIESwithAES-CBC", params); + + try + { + params = new IESParameterSpec(derivation, encoding, 128, 128, new byte[10]); + g.initialize(256, new SecureRandom()); + doTest("256-bit", g, "ECIESwithAES-CBC", params); + fail("AES no exception!"); + } + catch (InvalidAlgorithmParameterException e) + { + if (!e.getMessage().equals("NONCE in IES Parameters needs to be 16 bytes long")) + { + fail("AES wrong message!"); + } + } } public void doTest( @@ -112,7 +157,7 @@ public class ECIESTest IESParameterSpec p) throws Exception { - + byte[] message = Hex.decode("0102030405060708090a0b0c0d0e0f10111213141516"); byte[] out1, out2; @@ -142,29 +187,30 @@ public class ECIESTest fail(testname + " test failed with non-null parameters, DHAES mode false."); - c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); - c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); - - // Testing with null parameters and DHAES mode on - c1.init(Cipher.ENCRYPT_MODE, Pub, new SecureRandom()); - c2.init(Cipher.DECRYPT_MODE, Priv, new SecureRandom()); - - out1 = c1.doFinal(message, 0, message.length); - out2 = c2.doFinal(out1, 0, out1.length); - if (!areEqual(out2, message)) - fail(testname + " test failed with null parameters, DHAES mode true."); - - c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding"); - c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding"); - - // Testing with given parameters and DHAES mode on - c1.init(Cipher.ENCRYPT_MODE, Pub, p, new SecureRandom()); - c2.init(Cipher.DECRYPT_MODE, Priv, p, new SecureRandom()); - - out1 = c1.doFinal(message, 0, message.length); - out2 = c2.doFinal(out1, 0, out1.length); - if (!areEqual(out2, message)) - fail(testname + " test failed with non-null parameters, DHAES mode true."); +// TODO: DHAES mode is not currently implemented, perhaps it shouldn't be... +// c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); +// c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); +// +// // Testing with null parameters and DHAES mode on +// c1.init(Cipher.ENCRYPT_MODE, Pub, new SecureRandom()); +// c2.init(Cipher.DECRYPT_MODE, Priv, new SecureRandom()); +// +// out1 = c1.doFinal(message, 0, message.length); +// out2 = c2.doFinal(out1, 0, out1.length); +// if (!areEqual(out2, message)) +// fail(testname + " test failed with null parameters, DHAES mode true."); +// +// c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding"); +// c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding"); +// +// // Testing with given parameters and DHAES mode on +// c1.init(Cipher.ENCRYPT_MODE, Pub, p, new SecureRandom()); +// c2.init(Cipher.DECRYPT_MODE, Priv, p, new SecureRandom()); +// +// out1 = c1.doFinal(message, 0, message.length); +// out2 = c2.doFinal(out1, 0, out1.length); +// if (!areEqual(out2, message)) +// fail(testname + " test failed with non-null parameters, DHAES mode true."); } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECNRTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECNRTest.java index dc60a5c7..74695060 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECNRTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ECNRTest.java @@ -11,8 +11,8 @@ import java.security.Security; import java.security.Signature; import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; @@ -218,8 +218,8 @@ public class ECNRTest BigInteger[] sig = new BigInteger[2]; - sig[0] = ((DERInteger)s.getObjectAt(0)).getValue(); - sig[1] = ((DERInteger)s.getObjectAt(1)).getValue(); + sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); + sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); return sig; } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PKCS10CertRequestTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PKCS10CertRequestTest.java index 35139c57..65ed2912 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PKCS10CertRequestTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PKCS10CertRequestTest.java @@ -14,7 +14,7 @@ import java.security.spec.RSAPublicKeySpec; import java.util.Hashtable; import java.util.Vector; -import org.bouncycastle.asn1.DERObjectIdentifier; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; @@ -23,10 +23,13 @@ import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.KeyUsage; import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.X509Extension; import org.bouncycastle.asn1.x509.X509Extensions; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.jce.ECGOST3410NamedCurveTable; import org.bouncycastle.jce.ECNamedCurveTable; import org.bouncycastle.jce.PKCS10CertificationRequest; @@ -41,7 +44,6 @@ import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; -import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure; /** **/ @@ -145,7 +147,7 @@ public class PKCS10CertRequestTest /* * we generate a self signed certificate for the sake of testing - SHA224withECDSA */ - private void createECRequest(String algorithm, DERObjectIdentifier algOid, DERObjectIdentifier curveOid) + private void createECRequest(String algorithm, ASN1ObjectIdentifier algOid, ASN1ObjectIdentifier curveOid) throws Exception { ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveOid.getId()); @@ -217,7 +219,7 @@ public class PKCS10CertRequestTest } } - private void createECRequest(String algorithm, DERObjectIdentifier algOid) + private void createECRequest(String algorithm, ASN1ObjectIdentifier algOid) throws Exception { ECCurve.Fp curve = new ECCurve.Fp( @@ -424,7 +426,7 @@ public class PKCS10CertRequestTest oids.add(X509Extensions.KeyUsage); values.add(new X509Extension(true, new DEROctetString( new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)))); - SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pair.getPublic()); + SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()))); X509Extension ski = new X509Extension(false, new DEROctetString(subjectKeyIdentifier)); oids.add(X509Extensions.SubjectKeyIdentifier); values.add(ski); @@ -521,7 +523,7 @@ public class PKCS10CertRequestTest createECRequest("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); createECRequest("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); - createECRequest("SHA1withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1, new DERObjectIdentifier("1.3.132.0.34")); + createECRequest("SHA1withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1, new ASN1ObjectIdentifier("1.3.132.0.34")); createECGOSTRequest(); @@ -533,6 +535,17 @@ public class PKCS10CertRequestTest nullPointerTest(); } + private static byte[] getDigest(SubjectPublicKeyInfo spki) + { + Digest digest = new SHA1Digest(); + byte[] resBuf = new byte[digest.getDigestSize()]; + + byte[] bytes = spki.getPublicKeyData().getBytes(); + digest.update(bytes, 0, bytes.length); + digest.doFinal(resBuf, 0); + return resBuf; + } + public static void main( String[] args) { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PKCS12StoreTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PKCS12StoreTest.java index 0828440b..1faa65dc 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PKCS12StoreTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PKCS12StoreTest.java @@ -35,7 +35,7 @@ import org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.Pfx; import org.bouncycastle.asn1.pkcs.SafeBag; -import org.bouncycastle.jcajce.provider.config.PKCS12StoreParameter; +import org.bouncycastle.jcajce.PKCS12StoreParameter; import org.bouncycastle.jce.PKCS12Util; import org.bouncycastle.jce.X509Principal; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; @@ -665,6 +665,34 @@ public class PKCS12StoreTest fail("Failed DER encoding test."); } + + // + // save test using LoadStoreParameter - old version + // + bOut = new ByteArrayOutputStream(); + + storeParam = new org.bouncycastle.jcajce.provider.config.PKCS12StoreParameter(bOut, passwd, true); + + store.store(storeParam); + + data = bOut.toByteArray(); + + stream = new ByteArrayInputStream(data); + store.load(stream, passwd); + + key = (PrivateKey)store.getKey(pName, null); + + if (!((RSAPrivateKey)key).getModulus().equals(mod)) + { + fail("Modulus doesn't match."); + } + + outer = new ASN1StreamParser(data).readObject(); + if (!(outer instanceof DERSequenceParser)) + { + fail("Failed DER encoding test."); + } + // // save test using LoadStoreParameter // diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PSSTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PSSTest.java index c886c392..44d18abd 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PSSTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/PSSTest.java @@ -14,7 +14,7 @@ import java.security.spec.PSSParameterSpec; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPublicKeySpec; -import org.bouncycastle.asn1.DERObjectIdentifier; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.jce.provider.BouncyCastleProvider; @@ -201,7 +201,7 @@ public class PSSTest rawModeTest("SHA512withRSA/PSS", NISTObjectIdentifiers.id_sha512, priv2048Key, pub2048Key, random); } - private void rawModeTest(String sigName, DERObjectIdentifier digestOID, + private void rawModeTest(String sigName, ASN1ObjectIdentifier digestOID, PrivateKey privKey, PublicKey pubKey, SecureRandom random) throws Exception { byte[] sampleMessage = new byte[1000 + random.nextInt(100)]; diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/RSATest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/RSATest.java index c1f4582a..ba138ec5 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/RSATest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/RSATest.java @@ -39,6 +39,7 @@ import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.pkcs.RSAESOAEPparams; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -149,6 +150,20 @@ public class RSATest PublicKey pub2048Key = fact.generatePublic(pub2048KeySpec); // + // key without CRT coefficients + // + PrivateKeyInfo keyInfo = PrivateKeyInfo.getInstance(privKey.getEncoded()); + BigInteger zero = BigInteger.valueOf(0); + PKCS8EncodedKeySpec noCrtSpec = new PKCS8EncodedKeySpec(new PrivateKeyInfo(keyInfo.getPrivateKeyAlgorithm(), + new org.bouncycastle.asn1.pkcs.RSAPrivateKey(privKeySpec.getModulus(), privKeySpec.getPublicExponent(), privKeySpec.getPrivateExponent(), zero, zero, zero, zero, zero)).getEncoded()); + + PrivateKey noCrtKey = fact.generatePrivate(noCrtSpec); + if (noCrtKey instanceof RSAPrivateCrtKey) + { + fail("private key without CRT coefficients returned as CRT key"); + } + + // // No Padding // Cipher c = Cipher.getInstance("RSA", "BC"); @@ -671,7 +686,7 @@ public class RSATest } oaepCompatibilityTest("SHA-1", priv2048Key, pub2048Key); - oaepCompatibilityTest("SHA-224", priv2048Key, pub2048Key); + // TODO: oaepCompatibilityTest("SHA-224", priv2048Key, pub2048Key); commented out as fails in JDK 1.7 oaepCompatibilityTest("SHA-256", priv2048Key, pub2048Key); oaepCompatibilityTest("SHA-384", priv2048Key, pub2048Key); oaepCompatibilityTest("SHA-512", priv2048Key, pub2048Key); diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/RegressionTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/RegressionTest.java index e98330e8..2dce85e4 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/RegressionTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/RegressionTest.java @@ -34,7 +34,6 @@ public class RegressionTest new ElGamalTest(), new IESTest(), new SigTest(), - new AttrCertTest(), new CertTest(), new PKCS10CertRequestTest(), new EncryptedPrivateKeyInfoTest(), @@ -49,7 +48,6 @@ public class RegressionTest new NamedCurveTest(), new PKIXTest(), new NetscapeCertRequestTest(), - new X509StoreTest(), new X509StreamParserTest(), new X509CertificatePairTest(), new CertPathTest(), @@ -64,7 +62,6 @@ public class RegressionTest new PKIXNameConstraintsTest(), new MultiCertStoreTest(), new NoekeonTest(), - new AttrCertSelectorTest(), new SerialisationTest(), new SigNameTest(), new MQVTest(), @@ -78,7 +75,8 @@ public class RegressionTest new SHA3Test(), new SkeinTest(), new Shacal2Test(), - new DetDSATest() + new DetDSATest(), + new ThreefishTest() }; public static void main( diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/Shacal2Test.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/Shacal2Test.java index 4b4954a3..14157b12 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/Shacal2Test.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/Shacal2Test.java @@ -5,14 +5,21 @@ import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.security.Key; +import java.security.SecureRandom; import java.security.Security; +import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; @@ -36,6 +43,45 @@ public class Shacal2Test return "Shacal2"; } + private static final int KEY_SIZE_BITS = 512; + + private static final byte[] TEST_BYTES = new byte[ 1536 ]; + + private static final char[] TEST_PASSWORD = new char[ 1536 ]; + + static + { + new SecureRandom().nextBytes( TEST_BYTES ); + int total = TEST_PASSWORD.length; + for ( char c = 'A'; c <= 'Z' && total > 0; TEST_PASSWORD[TEST_PASSWORD.length - total] = c, c++, total-- ); + } + + private void blockTest() + throws Exception + { + final byte[] salt = new byte[KEY_SIZE_BITS / 8]; + new SecureRandom().nextBytes(salt); + + final KeySpec keySpec = new PBEKeySpec(TEST_PASSWORD, salt, 262144, KEY_SIZE_BITS); + final SecretKey secretKey = new SecretKeySpec(SecretKeyFactory.getInstance("PBKDF2", "BC"). + generateSecret(keySpec).getEncoded(), "Shacal2"); + + final Cipher cipher = Cipher.getInstance("Shacal2/CBC/ISO10126Padding", "BC"); + cipher.init(Cipher.ENCRYPT_MODE, secretKey); + + final byte[] iv = cipher.getIV(); + final byte[] ciphertext = cipher.doFinal(TEST_BYTES); + + cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); + + final byte[] cleartext = cipher.doFinal(ciphertext); + + if (!Arrays.areEqual(TEST_BYTES, cleartext)) + { + fail("Invalid cleartext."); + } + } + public void testECB( int strength, byte[] keyBytes, @@ -142,6 +188,8 @@ public class Shacal2Test Hex.decode(cipherTests[i + 2]), Hex.decode(cipherTests[i + 3])); } + + blockTest(); } public static void main( diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SigNameTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SigNameTest.java index 0ed90c35..19f9e6db 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SigNameTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SigNameTest.java @@ -66,6 +66,15 @@ public class SigNameTest checkName("SHA1withRSA/ISO9796-2"); checkName("MD5withRSA/ISO9796-2"); checkName("RIPEMD160withRSA/ISO9796-2"); + + checkName("RIPEMD128withRSA/X9.31"); + checkName("RIPEMD160withRSA/X9.31"); + checkName("SHA1withRSA/X9.31"); + checkName("SHA224withRSA/X9.31"); + checkName("SHA256withRSA/X9.31"); + checkName("SHA384withRSA/X9.31"); + checkName("SHA512withRSA/X9.31"); + checkName("WhirlpoolwithRSA/X9.31"); } public String getName() diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SigTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SigTest.java index 1863ca69..2c2f5128 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SigTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SigTest.java @@ -1,15 +1,19 @@ package org.bouncycastle.jce.provider.test; import java.math.BigInteger; +import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; +import java.security.SignatureException; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; @@ -303,22 +307,20 @@ public class SigTest fail("SHA1/ISO verification failed"); } - sig = Signature.getInstance("RIPEMD160WithRSA/ISO9796-2", "BC"); - - sig.initSign(signingKey); + trySig("RIPEMD160WithRSA/ISO9796-2", data, signingKey, verifyKey); - sig.update(data); + trySig("RIPEMD128WithRSA/X9.31", data, signingKey, verifyKey); + trySig("RIPEMD160WithRSA/X9.31", data, signingKey, verifyKey); + trySig("SHA1WithRSA/X9.31", data, signingKey, verifyKey); + trySig("SHA224WithRSA/X9.31", data, signingKey, verifyKey); + trySig("SHA256withRSA/X9.31", data, signingKey, verifyKey); + trySig("SHA384WithRSA/X9.31", data, signingKey, verifyKey); + trySig("SHA512WithRSA/X9.31", data, signingKey, verifyKey); + trySig("WhirlpoolWithRSA/X9.31", data, signingKey, verifyKey); - sigBytes = sig.sign(); - - sig.initVerify(verifyKey); - - sig.update(data); - - if (!sig.verify(sigBytes)) - { - fail("RIPEMD160/ISO verification failed"); - } + shouldPassSignatureX931Test1(); + shouldPassSignatureX931Test2(); + shouldPassSignatureX931Test3(); // // standard vector test - B.1.3 RIPEMD160, implicit. @@ -358,6 +360,137 @@ public class SigTest } } + private void trySig(String algorithm, byte[] data, PrivateKey signingKey, PublicKey verifyKey) + throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException + { + Signature sig; + byte[] sigBytes; + sig = Signature.getInstance(algorithm, "BC"); + + sig.initSign(signingKey); + + sig.update(data); + + sigBytes = sig.sign(); + + sig.initVerify(verifyKey); + + sig.update(data); + + if (!sig.verify(sigBytes)) + { + fail(algorithm + " verification failed"); + } + } + + private void shouldPassSignatureX931Test1() + throws Exception + { + BigInteger n = new BigInteger("c9be1b28f8caccca65d86cc3c9bbcc13eccc059df3b80bd2292b811eff3aa0dd75e1e85c333b8e3fa9bed53bb20f5359ff4e6900c5e9a388e3a4772a583a79e2299c76582c2b27694b65e9ba22e66bfb817f8b70b22206d7d8ae488c86dbb7137c26d5eff9b33c90e6cee640630313b7a715802e15142fef498c404a8de19674974785f0f852e2d470fe85a2e54ffca9f5851f672b71df691785a5cdabe8f14aa628942147de7593b2cf962414a5b59c632c4e14f1768c0ab2e9250824beea60a3529f11bf5e070ce90a47686eb0be1086fb21f0827f55295b4a48307db0b048c05a4aec3f488c576ca6f1879d354224c7e84cbcd8e76dd217a3de54dba73c35", 16); + BigInteger e = new BigInteger("e75b1b", 16); + byte[] msg = Hex.decode("5bb0d1c0ef9b5c7af2477fe08d45523d3842a4b2db943f7033126c2a7829bacb3d2cfc6497ec91688189e81b7f8742488224ba320ce983ce9480722f2cc5bc42611f00bb6311884f660ccc244788378673532edb05284fd92e83f6f6dab406209032e6af9a33c998677933e32d6fb95fd27408940d7728f9c9c40267ca1d20ce"); + byte[] sig = Hex.decode("0fe8bb8e3109a1eb7489ef35bf4c1a0780071da789c8bd226a4170538eafefdd30b732d628f0e87a0b9450051feae9754d4fb61f57862d10f0bacc4f660d13281d0cd1141c006ade5186ff7d961a4c6cd0a4b352fc1295c5afd088f80ac1f8e192ef116a010a442655fe8ff5eeacea15807906fb0f0dfa86e680d4c005872357f7ece9aa4e20b15d5f709b30f08648ecaa34f2fbf54eb6b414fa2ff6f87561f70163235e69ccb4ac82a2e46d3be214cc2ef5263b569b2d8fd839b21a9e102665105ea762bda25bb446cfd831487a6b846100dee113ae95ae64f4af22c428c87bab809541c962bb3a56d4c86588e0af4ebc7fcc66dadced311051356d3ea745f7"); + + RSAPublicKeySpec rsaPublic = new RSAPublicKeySpec(n, e); + Signature signer = Signature.getInstance("SHA1withRSA/X9.31", "BC"); + + signer.initVerify(KeyFactory.getInstance("RSA", "BC").generatePublic(rsaPublic)); + + signer.update(msg, 0, msg.length); + + if (!signer.verify(sig)) + { + fail("RSA X931 verify test 1 failed."); + } + } + + private void shouldPassSignatureX931Test2() + throws Exception + { + BigInteger n = new BigInteger("b746ba6c3c0be64bbe33aa55b2929b0af4e86d773d44bfe5914db9287788c4663984b61a418d2eecca30d752ff6b620a07ec72eeb2b422d2429da352407b99982800b9dd7697be6a7b1baa98ca5f4fc2fe33400f20b9dba337ac25c987804165d4a6e0ee4d18eabd6de5abdfe578cae6713ff91d16c80a5bb20217fe614d9509e75a43e1825327b9da8f0a9f6eeaa1c04b69fb4bacc073569fff4ab491becbe6d0441d437fc3fa823239c4a0f75321666b68dd3f66e2dd394089a15bcc288a68a4eb0a48e17d639743b9dea0a91cc35820544732aff253f8ca9967c609dc01c2f8cd0313a7a91cfa94ff74289a1d2b6f19d1811f4b9a65f4cce9e5759b4cc64f", 16); + BigInteger e = new BigInteger("dcbbdb", 16); + byte[] msg = Hex.decode("a5d3c8a060f897bbbc20ae0955052f37fbc70986b6e11c65075c9f457142bfa93856897c69020aa81a91b5e4f39e05cdeecc63395ab849c8262ca8bc5c96870aecb8edb0aba0024a9bdb71e06de6100344e5c318bc979ef32b8a49a8278ba99d4861bce42ebbc5c8c666aaa6cac39aff8779f2cae367620f9edd4cb1d80b6c8c"); + byte[] sig = Hex.decode("39fbbd1804c689a533b0043f84da0f06081038c0fbf31e443e46a05e58f50de5198bbca40522afefaba3aed7082a6cb93b1da39f1f5a42246bf64930781948d300549bef0f8d554ecfca60a1b1ecba95a7014ee4545ad4f0c4e3a31942c6738b4ccd6244b6a21267dadf0826a5f713f13b1f5a9ab8501d957a26d4948278ac67851071a315674bdab173bfef2c2690c8373da6bf3d69f30c0e5da8883de872f59521b40793854085641adf98d13db991c5d0a8aaa0222934fa33332e90ef0b954e195cb267d6ffb36c96e14d1ec7b915a87598b4461a3146566354dc2ae748c84ee0cd46543b53ebff8cdf47725b280a1f799fb6ebb4a31ad2bdd5178250f83a"); + + RSAPublicKeySpec rsaPublic = new RSAPublicKeySpec(n, e); + Signature signer = Signature.getInstance("SHA224withRSA/X9.31", "BC"); + + signer.initVerify(KeyFactory.getInstance("RSA", "BC").generatePublic(rsaPublic)); + + signer.update(msg, 0, msg.length); + + if (!signer.verify(sig)) + { + fail("RSA X931 verify test 2 failed."); + } + } + + private void shouldPassSignatureX931Test3() + throws Exception + { + BigInteger n = new BigInteger("dcb5686a3d2063a3f9cf7b9b32d2d3765b4c449b09b4960245a9111cd3b0cbd3260496885b8e1fa5db33b03efcc759d9c1afe29d93c6faebc7e0efada334b5b9a29655e2da2c8f11103d8203be311feab7ae88e9f1b2ec7d8fc655d77202b1681dd9717ec0f525b35584987e19539635a1ed23ca482a00149c609a23dc1645fd", 16); + BigInteger e = new BigInteger("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000dc9f7", 16); + BigInteger d = new BigInteger("189d6345099098992e0c9ca5f281e1338092342fa0acc85cc2a111f30f9bd2fb4753cd1a48ef0ddca9bf1af33ec76fb2e23a9fb4896c26f2235b516f7c05ef7ae81e70f4b491a5fedba9b935e9c76d761a813ce7776ff8a1e5efe1166ff2eca26aa900da88c908d51af9de26977fe39719cc781df32216fa41b838f0c63803c3", 16); + + RSAPublicKeySpec rsaPublic = new RSAPublicKeySpec(n, e); + RSAPrivateKeySpec rsaPriv = new RSAPrivateKeySpec(n, d); + + PrivateKey privateKey = KeyFactory.getInstance("RSA", "BC").generatePrivate(rsaPriv); + PublicKey publicKey = KeyFactory.getInstance("RSA", "BC").generatePublic(rsaPublic); + + + byte[] msg = Hex.decode("911475c6e210ef4ac65b6fe8d2bfe5e01b959771b137c4ef69b88716e0d2ff9ebc1fad0f358c1dd7d50cc99a7b893ac9a6207076f08d8467d9e48c69c683bfe64a44dabaa3f7c243880f6ab7229bf7bb587822314fc5de5131983bfb2eef8b4bc1eac36f353724b567cd1ae8cddd64ddb7057549d5c81ad5fa3b5e751f00abf5"); + byte[] sig = Hex.decode("02c50ec0ac8a7f38ef5630c396964d6a6daaa7e3083ab5b57fa2a2632f3b70e2e85c8456cd774d45d7e44fcb063f0f04fff9f1e3adfda11272535a92cb59320b190b5ee4261f23d6ceaa925df3a7bfa42e26bf61ea9645d9d64b3c90a820802768a6e209c9f83705375a3867afccc037e8242a98fa4c3db6b2d9877754d47289"); + + doGenVerify("SHA1withRSA/X9.31", privateKey, publicKey, msg, sig); + + msg = Hex.decode("911475c6e210ef4ac65b6fe8d2bfe5e01b959771b137c4ef69b88716e0d2ff9ebc1fad0f358c1dd7d50cc99a7b893ac9a6207076f08d8467d9e48c69c683bfe64a44dabaa3f7c243880f6ab7229bf7bb587822314fc5de5131983bfb2eef8b4bc1eac36f353724b567cd1ae8cddd64ddb7057549d5c81ad5fa3b5e751f00abf5"); + sig = Hex.decode("2e2e279850ce21e34228a8e810d3ba835c51932e03c5e8886e99036f25a9a43aa5e33168274b7bfc1745ce8fc7ff3335f0927920f09fe9d4a6fac5e546eaf5aedc7e11ba75d33ae1487857b017930e69ec63a10971ca062c0e24f5b08226e59446d02a7827ceecbbcf6ecf0ffa7b3dff3e1a76b5f7432f804a4aa858e18877a5"); + + doGenVerify("SHA224withRSA/X9.31", privateKey, publicKey, msg, sig); + + msg = Hex.decode("911475c6e210ef4ac65b6fe8d2bfe5e01b959771b137c4ef69b88716e0d2ff9ebc1fad0f358c1dd7d50cc99a7b893ac9a6207076f08d8467d9e48c69c683bfe64a44dabaa3f7c243880f6ab7229bf7bb587822314fc5de5131983bfb2eef8b4bc1eac36f353724b567cd1ae8cddd64ddb7057549d5c81ad5fa3b5e751f00abf5"); + sig = Hex.decode("4f917837c2aedfb13e8c039cb076e399de39c2a964e418ad541745ff8062ca967d2ce6d51190732d3db089e48e31e95746f306314468c7d2248ace2cfbf4d67c59629a6e61813d52c1a84ea9d21a73b0afa7e871217f2ebeffeaa1268278edfcb7f2f98d1d32ef835123906e8d5f896d1af6877e304a39b03cf014ddaf850911"); + + doGenVerify("SHA256withRSA/X9.31", privateKey, publicKey, msg, sig); + + msg = Hex.decode("7d1f36e728dd03b07825c5dcdf6ea933136e1eb819dd8a8aa27c3b0c9b56a0440045b981f1b9cc4107b55a51e81a5136192883cc1442572d9bf1bed44b2c690374d73a612889f8e8929246fe893dd6e26552da4a12dfbb4b63380e78a83dc44e82dba0d0f6d6ef6ec1c5732beb5ea0ff9ff30b7a3a3d1faba2591140d91017ee"); + sig = Hex.decode("1210a59883326234d363155876818f43bdbe7ba758c44104ad771984636e13ecfbad97beb138a836b2d94dafd910ecb5b6ba7de6125a15f683af96220b3370e92ea2e1fb22fcd5e83def31728d9196b59308eb4498dadeddad66e26152b456e613ecc5fc8a7ed33f0608ea1ef886949f3741ab8c41ee453de877e5acea33a557"); + + doGenVerify("SHA384withRSA/X9.31", privateKey, publicKey, msg, sig); + + msg = Hex.decode("911475c6e210ef4ac65b6fe8d2bfe5e01b959771b137c4ef69b88716e0d2ff9ebc1fad0f358c1dd7d50cc99a7b893ac9a6207076f08d8467d9e48c69c683bfe64a44dabaa3f7c243880f6ab7229bf7bb587822314fc5de5131983bfb2eef8b4bc1eac36f353724b567cd1ae8cddd64ddb7057549d5c81ad5fa3b5e751f00abf5"); + sig = Hex.decode("154bbde6991b6c8c137a62595619e0038e6787703568a213cff95dac33bc871f7a45f8a3471b823451d1262f7a8932f11d5f93cadbc63daf840e0bbd7d317b57d385be706b58670afac7f055f67d8834f574863b1e295b2a85905bb9926f3114be2be59ad7782321578a451b91587bda7cd6a5051c0fd934af28d5d479463642"); + + doGenVerify("SHA512withRSA/X9.31", privateKey, publicKey, msg, sig); + } + + private void doGenVerify(String algorithm, PrivateKey privateKey, PublicKey publicKey, byte[] msg, byte[] sig) + throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException + { + Signature signer = Signature.getInstance(algorithm, "BC"); + + signer.initSign(privateKey); + + signer.update(msg, 0, msg.length); + + byte[] s = signer.sign(); + + if (!Arrays.areEqual(sig, s)) + { + fail(algorithm + " sig test 3 failed."); + } + + signer.initVerify(publicKey); + + signer.update(msg, 0, msg.length); + + if (!signer.verify(sig)) + { + fail(algorithm + " verify test 3 failed."); + } + } + public String getName() { return "SigTest"; diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SipHashTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SipHashTest.java index 9120e88b..59861410 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SipHashTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/SipHashTest.java @@ -1,8 +1,13 @@ package org.bouncycastle.jce.provider.test; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; import java.security.Security; +import javax.crypto.KeyGenerator; import javax.crypto.Mac; +import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; @@ -16,6 +21,42 @@ public class SipHashTest public void performTest() throws Exception { + testMac(); + testKeyGenerator(); + } + + private void testKeyGenerator() + throws NoSuchAlgorithmException, + NoSuchProviderException + { + testKeyGen("SipHash"); + testKeyGen("SipHash-2-4"); + testKeyGen("SipHash-4-8"); + } + + private void testKeyGen(String algorithm) + throws NoSuchAlgorithmException, + NoSuchProviderException + { + KeyGenerator kg = KeyGenerator.getInstance(algorithm, "BC"); + + SecretKey key = kg.generateKey(); + + if (!key.getAlgorithm().equalsIgnoreCase("SipHash")) + { + fail("Unexpected algorithm name in key", "SipHash", key.getAlgorithm()); + } + if (key.getEncoded().length != 16) + { + fail("Expected 128 bit key"); + } + } + + private void testMac() + throws NoSuchAlgorithmException, + NoSuchProviderException, + InvalidKeyException + { byte[] key = Hex.decode("000102030405060708090a0b0c0d0e0f"); byte[] input = Hex.decode("000102030405060708090a0b0c0d0e"); diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/TestUtils.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/TestUtils.java index 4751fb2b..4d57efe0 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/TestUtils.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/TestUtils.java @@ -24,14 +24,17 @@ import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.CRLNumber; import org.bouncycastle.asn1.x509.CRLReason; import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.X509Extensions; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.jce.PrincipalUtil; import org.bouncycastle.jce.X509Principal; import org.bouncycastle.x509.X509V1CertificateGenerator; import org.bouncycastle.x509.X509V2CRLGenerator; import org.bouncycastle.x509.X509V3CertificateGenerator; import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure; -import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure; /** * Test Utils @@ -81,7 +84,7 @@ class TestUtils certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); - certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey)); + certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(intKey.getEncoded())))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); @@ -102,7 +105,7 @@ class TestUtils certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); - certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); + certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(entityKey.getEncoded())))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); @@ -282,5 +285,17 @@ class TestUtils { return new byte[0]; } + + } + + private static byte[] getDigest(SubjectPublicKeyInfo spki) + { + Digest digest = new SHA1Digest(); + byte[] resBuf = new byte[digest.getDigestSize()]; + + byte[] bytes = spki.getPublicKeyData().getBytes(); + digest.update(bytes, 0, bytes.length); + digest.doFinal(resBuf, 0); + return resBuf; } } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ThreefishTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ThreefishTest.java new file mode 100644 index 00000000..c2787877 --- /dev/null +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/ThreefishTest.java @@ -0,0 +1,80 @@ +package org.bouncycastle.jce.provider.test; + +import java.security.Security; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.test.SimpleTest; + +public class ThreefishTest + extends SimpleTest +{ + + private static final byte[] SECRET_KEY_1024 = + { + -15, -32, 56, 110, 22, -42, -26, 34, 25, 17, -83, -2, -78, 112, 49, 127, -4, 70, -110, -21, -10, -114, -82, -122, + 78, 53, -105, -44, 34, 45, -102, -19, -30, 73, 87, 19, 25, -92, -64, -72, 11, 125, -92, -124, -126, -70, -92, 54, + 46, 3, 86, -108, 71, -42, 44, -110, -36, -31, -48, -84, -19, 102, 124, -118, 17, -84, -119, 126, 37, -8, -13, 21, + -4, 86, 104, -85, -44, 82, 60, -61, -95, -9, -92, 68, -123, -111, -53, -36, -47, 36, -92, 121, 95, 25, 73, 124, + -13, -7, -106, -32, 75, -30, -25, -95, 120, 88, 2, 55, 68, -113, -60, 104, 59, 57, -86, -79, -110, -126, -44, + -18, 73, -37, -128, -40, -62, -15, 23, 87 + }; + + private static final byte[] TEST_BYTES = new byte[1536]; + + public String getName() + { + return "Threefish"; + } + + public void performTest() + throws Exception + { + // padding test at 128 pad bytes. + + final SecretKey secretKey = new SecretKeySpec(SECRET_KEY_1024, "Threefish-1024"); + + Cipher cipher = Cipher.getInstance("Threefish-1024/CBC/ISO10126Padding", "BC"); + cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[128])); + + byte[] iv = cipher.getIV(); + byte[] ciphertext = cipher.doFinal(TEST_BYTES); + + cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); + + byte[] cleartext = cipher.doFinal(ciphertext); + + if (!Arrays.areEqual(TEST_BYTES, cleartext)) + { + fail("Invalid cleartext - ISO10126Padding."); + } + + cipher = Cipher.getInstance("Threefish-1024/CBC/PKCS7Padding", "BC"); + cipher.init(Cipher.ENCRYPT_MODE, secretKey); + + iv = cipher.getIV(); + ciphertext = cipher.doFinal(TEST_BYTES); + + cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); + + cleartext = cipher.doFinal(ciphertext); + + if (!Arrays.areEqual(TEST_BYTES, cleartext)) + { + fail("Invalid cleartext - PKCS7."); + } + } + + public static void main(final String[] args) + throws Exception + { + Security.addProvider(new BouncyCastleProvider()); + + runTest(new ThreefishTest()); + } +} diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/X509StoreTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/X509StoreTest.java deleted file mode 100644 index 5897117b..00000000 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/X509StoreTest.java +++ /dev/null @@ -1,345 +0,0 @@ -package org.bouncycastle.jce.provider.test; - -import org.bouncycastle.jce.PrincipalUtil; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.test.SimpleTest; -import org.bouncycastle.x509.X509AttributeCertStoreSelector; -import org.bouncycastle.x509.X509AttributeCertificate; -import org.bouncycastle.x509.X509CRLStoreSelector; -import org.bouncycastle.x509.X509CertPairStoreSelector; -import org.bouncycastle.x509.X509CertStoreSelector; -import org.bouncycastle.x509.X509CertificatePair; -import org.bouncycastle.x509.X509CollectionStoreParameters; -import org.bouncycastle.x509.X509Store; -import org.bouncycastle.x509.X509V2AttributeCertificate; - -import java.io.ByteArrayInputStream; -import java.math.BigInteger; -import java.security.Security; -import java.security.cert.CertificateFactory; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -public class X509StoreTest - extends SimpleTest -{ - private void certPairTest() - throws Exception - { - CertificateFactory cf = CertificateFactory.getInstance("X.509", - "BC"); - - X509Certificate rootCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.rootCertBin)); - X509Certificate interCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.interCertBin)); - X509Certificate finalCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.finalCertBin)); - - // Testing CollectionCertStore generation from List - X509CertificatePair pair1 = new X509CertificatePair(rootCert, interCert); - List certList = new ArrayList(); - - certList.add(pair1); - certList.add(new X509CertificatePair(interCert, finalCert)); - - X509CollectionStoreParameters ccsp = new X509CollectionStoreParameters(certList); - - X509Store certStore = X509Store.getInstance("CertificatePair/Collection", ccsp, "BC"); - X509CertPairStoreSelector selector = new X509CertPairStoreSelector(); - X509CertStoreSelector fwSelector = new X509CertStoreSelector(); - - fwSelector.setSerialNumber(rootCert.getSerialNumber()); - fwSelector.setSubject(rootCert.getIssuerDN().getName()); - - selector.setForwardSelector(fwSelector); - - Collection col = certStore.getMatches(selector); - - if (col.size() != 1 || !col.contains(pair1)) - { - fail("failed pair1 test"); - } - - col = certStore.getMatches(null); - - if (col.size() != 2) - { - fail("failed null test"); - } - } - - public void performTest() - throws Exception - { - CertificateFactory cf = CertificateFactory.getInstance("X.509", - "BC"); - - X509Certificate rootCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.rootCertBin)); - X509Certificate interCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.interCertBin)); - X509Certificate finalCert = (X509Certificate)cf - .generateCertificate(new ByteArrayInputStream( - CertPathTest.finalCertBin)); - X509CRL rootCrl = (X509CRL)cf.generateCRL(new ByteArrayInputStream( - CertPathTest.rootCrlBin)); - X509CRL interCrl = (X509CRL)cf - .generateCRL(new ByteArrayInputStream( - CertPathTest.interCrlBin)); - - // Testing CollectionCertStore generation from List - List certList = new ArrayList(); - certList.add(rootCert); - certList.add(interCert); - certList.add(finalCert); - X509CollectionStoreParameters ccsp = new X509CollectionStoreParameters(certList); - X509Store certStore = X509Store.getInstance("Certificate/Collection", ccsp, "BC"); - // set default to be the same as for SUN X500 name - X509Principal.DefaultReverse = true; - - // Searching for rootCert by subjectDN - - X509CertStoreSelector targetConstraints = new X509CertStoreSelector(); - targetConstraints.setSubject(PrincipalUtil.getSubjectX509Principal(rootCert).getEncoded()); - Collection certs = certStore.getMatches(targetConstraints); - if (certs.size() != 1 || !certs.contains(rootCert)) - { - fail("rootCert not found by subjectDN"); - } - - // Searching for rootCert by subjectDN encoded as byte - targetConstraints = new X509CertStoreSelector(); - targetConstraints.setSubject(PrincipalUtil.getSubjectX509Principal(rootCert).getEncoded()); - certs = certStore.getMatches(targetConstraints); - if (certs.size() != 1 || !certs.contains(rootCert)) - { - fail("rootCert not found by encoded subjectDN"); - } - - X509Principal.DefaultReverse = false; - - // Searching for rootCert by public key encoded as byte - targetConstraints = new X509CertStoreSelector(); - targetConstraints.setSubjectPublicKey(rootCert.getPublicKey().getEncoded()); - certs = certStore.getMatches(targetConstraints); - if (certs.size() != 1 || !certs.contains(rootCert)) - { - fail("rootCert not found by encoded public key"); - } - - // Searching for interCert by issuerDN - targetConstraints = new X509CertStoreSelector(); - targetConstraints.setIssuer(PrincipalUtil.getSubjectX509Principal(rootCert).getEncoded()); - certs = certStore.getMatches(targetConstraints); - if (certs.size() != 2) - { - fail("did not found 2 certs"); - } - if (!certs.contains(rootCert)) - { - fail("rootCert not found"); - } - if (!certs.contains(interCert)) - { - fail("interCert not found"); - } - - // Searching for rootCrl by issuerDN - List crlList = new ArrayList(); - crlList.add(rootCrl); - crlList.add(interCrl); - ccsp = new X509CollectionStoreParameters(crlList); - X509Store store = X509Store.getInstance("CRL/Collection", ccsp, "BC"); - X509CRLStoreSelector targetConstraintsCRL = new X509CRLStoreSelector(); - targetConstraintsCRL.setIssuers(Collections.singleton(rootCrl.getIssuerX500Principal())); - Collection crls = store.getMatches(targetConstraintsCRL); - if (crls.size() != 1 || !crls.contains(rootCrl)) - { - fail("rootCrl not found"); - } - - crls = certStore.getMatches(targetConstraintsCRL); - if (crls.size() != 0) - { - fail("error using wrong selector (CRL)"); - } - certs = store.getMatches(targetConstraints); - if (certs.size() != 0) - { - fail("error using wrong selector (certs)"); - } - // Searching for attribute certificates - X509V2AttributeCertificate attrCert = new X509V2AttributeCertificate(AttrCertTest.attrCert); - X509AttributeCertificate attrCert2 = new X509V2AttributeCertificate(AttrCertTest.certWithBaseCertificateID); - - List attrList = new ArrayList(); - attrList.add(attrCert); - attrList.add(attrCert2); - ccsp = new X509CollectionStoreParameters(attrList); - store = X509Store.getInstance("AttributeCertificate/Collection", ccsp, "BC"); - X509AttributeCertStoreSelector attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setHolder(attrCert.getHolder()); - if (!attrSelector.getHolder().equals(attrCert.getHolder())) - { - fail("holder get not correct"); - } - Collection attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on holder"); - } - attrSelector.setHolder(attrCert2.getHolder()); - if (attrSelector.getHolder().equals(attrCert.getHolder())) - { - fail("holder get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert2)) - { - fail("attrCert2 not found on holder"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setIssuer(attrCert.getIssuer()); - if (!attrSelector.getIssuer().equals(attrCert.getIssuer())) - { - fail("issuer get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on issuer"); - } - attrSelector.setIssuer(attrCert2.getIssuer()); - if (attrSelector.getIssuer().equals(attrCert.getIssuer())) - { - fail("issuer get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert2)) - { - fail("attrCert2 not found on issuer"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setAttributeCert(attrCert); - if (!attrSelector.getAttributeCert().equals(attrCert)) - { - fail("attrCert get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on attrCert"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setSerialNumber(attrCert.getSerialNumber()); - if (!attrSelector.getSerialNumber().equals(attrCert.getSerialNumber())) - { - fail("serial number get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on serial number"); - } - attrSelector = (X509AttributeCertStoreSelector)attrSelector.clone(); - if (!attrSelector.getSerialNumber().equals(attrCert.getSerialNumber())) - { - fail("serial number get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on serial number"); - } - - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setAttributeCertificateValid(attrCert.getNotBefore()); - if (!attrSelector.getAttributeCertificateValid().equals(attrCert.getNotBefore())) - { - fail("valid get not correct"); - } - attrs = store.getMatches(attrSelector); - if (attrs.size() != 1 || !attrs.contains(attrCert)) - { - fail("attrCert not found on valid"); - } - attrSelector = new X509AttributeCertStoreSelector(); - attrSelector.setAttributeCertificateValid(new Date(attrCert.getNotBefore().getTime() - 100)); - attrs = store.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("attrCert found on before"); - } - attrSelector.setAttributeCertificateValid(new Date(attrCert.getNotAfter().getTime() + 100)); - attrs = store.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("attrCert found on after"); - } - attrSelector.setSerialNumber(BigInteger.valueOf(10000)); - attrs = store.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("attrCert found on wrong serial number"); - } - - attrSelector.setAttributeCert(null); - attrSelector.setAttributeCertificateValid(null); - attrSelector.setHolder(null); - attrSelector.setIssuer(null); - attrSelector.setSerialNumber(null); - if (attrSelector.getAttributeCert() != null) - { - fail("null attrCert"); - } - if (attrSelector.getAttributeCertificateValid() != null) - { - fail("null attrCertValid"); - } - if (attrSelector.getHolder() != null) - { - fail("null attrCert holder"); - } - if (attrSelector.getIssuer() != null) - { - fail("null attrCert issuer"); - } - if (attrSelector.getSerialNumber() != null) - { - fail("null attrCert serial"); - } - - attrs = certStore.getMatches(attrSelector); - if (attrs.size() != 0) - { - fail("error using wrong selector (attrs)"); - } - - certPairTest(); - } - - public String getName() - { - return "X509Store"; - } - - public static void main(String[] args) - { - Security.addProvider(new BouncyCastleProvider()); - - runTest(new X509StoreTest()); - } - -} diff --git a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/nist/NistCertPathTest.java b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/nist/NistCertPathTest.java index ddbda5d3..af94e4e1 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/provider/test/nist/NistCertPathTest.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/provider/test/nist/NistCertPathTest.java @@ -34,8 +34,9 @@ import junit.framework.TestCase; import junit.framework.TestSuite; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.x509.X509Extension; -import org.bouncycastle.x509.extension.X509ExtensionUtil; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.x509.Extension; /** * NIST CertPath test data for RFC 3280 @@ -206,7 +207,7 @@ public class NistCertPathTest new String[] { "NegativeSerialNumberCACert", "InvalidNegativeSerialNumberTest15EE" }, new String[] { TRUST_ANCHOR_ROOT_CRL, "NegativeSerialNumberCACRL" }, 0, - "Certificate revocation after Fri Apr 20 00:57:20", "reason: keyCompromise"); + "Certificate revocation after 2001-04-19 14:57:20 +0000", "reason: keyCompromise"); } // @@ -830,11 +831,11 @@ public class NistCertPathTest throws Exception { X509Certificate cert = loadCert(trustAnchorName); - byte[] extBytes = cert.getExtensionValue(X509Extension.nameConstraints.getId()); + byte[] extBytes = cert.getExtensionValue(Extension.nameConstraints.getId()); if (extBytes != null) { - ASN1Encodable extValue = X509ExtensionUtil.fromExtensionValue(extBytes); + ASN1Encodable extValue = ASN1Primitive.fromByteArray(ASN1OctetString.getInstance(extBytes).getOctets()); return new TrustAnchor(cert, extValue.toASN1Primitive().getEncoded(ASN1Encoding.DER)); } diff --git a/bcprov/src/main/java/org/bouncycastle/jce/spec/ECNamedCurveParameterSpec.java b/bcprov/src/main/java/org/bouncycastle/jce/spec/ECNamedCurveParameterSpec.java index 47416a22..4e749a58 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/spec/ECNamedCurveParameterSpec.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/spec/ECNamedCurveParameterSpec.java @@ -7,9 +7,9 @@ import org.bouncycastle.math.ec.ECPoint; /** * specification signifying that the curve parameters can also be - * refered to by name. + * referred to by name. * <p> - * If you are using JDK 1.5 you should be looking at ECNamedCurveSpec. + * If you are using JDK 1.5 you should be looking at {@link ECNamedCurveSpec}. */ public class ECNamedCurveParameterSpec extends ECParameterSpec diff --git a/bcprov/src/main/java/org/bouncycastle/jce/spec/ECNamedCurveSpec.java b/bcprov/src/main/java/org/bouncycastle/jce/spec/ECNamedCurveSpec.java index b3d239e1..c1b5ccc6 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/spec/ECNamedCurveSpec.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/spec/ECNamedCurveSpec.java @@ -6,6 +6,7 @@ import java.security.spec.ECFieldFp; import java.security.spec.ECPoint; import java.security.spec.EllipticCurve; +import org.bouncycastle.math.ec.ECAlgorithms; import org.bouncycastle.math.ec.ECCurve; /** @@ -21,9 +22,9 @@ public class ECNamedCurveSpec ECCurve curve, byte[] seed) { - if (curve instanceof ECCurve.Fp) + if (ECAlgorithms.isFpCurve(curve)) { - return new EllipticCurve(new ECFieldFp(((ECCurve.Fp)curve).getQ()), curve.getA().toBigInteger(), curve.getB().toBigInteger(), seed); + return new EllipticCurve(new ECFieldFp(curve.getField().getCharacteristic()), curve.getA().toBigInteger(), curve.getB().toBigInteger(), seed); } else { diff --git a/bcprov/src/main/java/org/bouncycastle/jce/spec/IESParameterSpec.java b/bcprov/src/main/java/org/bouncycastle/jce/spec/IESParameterSpec.java index 165df9f1..c18a88fd 100644 --- a/bcprov/src/main/java/org/bouncycastle/jce/spec/IESParameterSpec.java +++ b/bcprov/src/main/java/org/bouncycastle/jce/spec/IESParameterSpec.java @@ -2,6 +2,8 @@ package org.bouncycastle.jce.spec; import java.security.spec.AlgorithmParameterSpec; +import org.bouncycastle.util.Arrays; + /** * Parameter spec for an integrated encryptor, as in IEEE P1363a */ @@ -12,6 +14,8 @@ public class IESParameterSpec private byte[] encoding; private int macKeySize; private int cipherKeySize; + private byte[] nonce; + private boolean usePointCompression; /** @@ -26,7 +30,7 @@ public class IESParameterSpec byte[] encoding, int macKeySize) { - this(derivation, encoding, macKeySize, -1); + this(derivation, encoding, macKeySize, -1, null, false); } @@ -44,6 +48,46 @@ public class IESParameterSpec int macKeySize, int cipherKeySize) { + this(derivation, encoding, macKeySize, cipherKeySize, null, false); + } + + /** + * Set the IES engine parameters. + * + * @param derivation the optional derivation vector for the KDF. + * @param encoding the optional encoding vector for the KDF. + * @param macKeySize the key size (in bits) for the MAC. + * @param cipherKeySize the key size (in bits) for the block cipher. + * @param nonce an IV to use initialising the block cipher. + */ + public IESParameterSpec( + byte[] derivation, + byte[] encoding, + int macKeySize, + int cipherKeySize, + byte[] nonce) + { + this(derivation, encoding, macKeySize, cipherKeySize, nonce, false); + } + + /** + * Set the IES engine parameters. + * + * @param derivation the optional derivation vector for the KDF. + * @param encoding the optional encoding vector for the KDF. + * @param macKeySize the key size (in bits) for the MAC. + * @param cipherKeySize the key size (in bits) for the block cipher. + * @param nonce an IV to use initialising the block cipher. + * @param usePointCompression whether to use EC point compression or not (false by default) + */ + public IESParameterSpec( + byte[] derivation, + byte[] encoding, + int macKeySize, + int cipherKeySize, + byte[] nonce, + boolean usePointCompression) + { if (derivation != null) { this.derivation = new byte[derivation.length]; @@ -66,15 +110,16 @@ public class IESParameterSpec this.macKeySize = macKeySize; this.cipherKeySize = cipherKeySize; + this.nonce = Arrays.clone(nonce); + this.usePointCompression = usePointCompression; } - /** * return the derivation vector. */ public byte[] getDerivationV() { - return derivation; + return Arrays.clone(derivation); } /** @@ -82,7 +127,7 @@ public class IESParameterSpec */ public byte[] getEncodingV() { - return encoding; + return Arrays.clone(encoding); } /** @@ -101,4 +146,31 @@ public class IESParameterSpec return cipherKeySize; } -} + /** + * Return the nonce (IV) value to be associated with message. + * + * @return block cipher IV for message. + */ + public byte[] getNonce() + { + return Arrays.clone(nonce); + } + + /** + * Set the 'point compression' flag. + */ + public void setPointCompression(boolean usePointCompression) + { + this.usePointCompression = usePointCompression; + } + + /** + * Return the 'point compression' flag. + * + * @return the point compression flag + */ + public boolean getPointCompression() + { + return usePointCompression; + } +}
\ No newline at end of file diff --git a/bcprov/src/main/java/org/bouncycastle/jce/spec/package.html b/bcprov/src/main/java/org/bouncycastle/jce/spec/package.html new file mode 100644 index 00000000..6f370577 --- /dev/null +++ b/bcprov/src/main/java/org/bouncycastle/jce/spec/package.html @@ -0,0 +1,5 @@ +<html> +<body bgcolor="#ffffff"> +Parameter specifications for supporting El Gamal, and Elliptic Curve. +</body> +</html> |