private X509v3CertificateBuilder createCertificateBuilder(KeyPair keyPair) throws PropertyConfigurationException, CertIOException { X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, propertyConfigurationService.getConfigValue(CERT_COMMON_NAME_PROPERTY)); nameBuilder.addRDN(BCStyle.O, propertyConfigurationService.getConfigValue(CERT_ORGANISATION_PROPERTY)); nameBuilder.addRDN(BCStyle.OU, propertyConfigurationService.getConfigValue(CERT_ORGANISATIONAL_UNIT_PROPERTY)); nameBuilder.addRDN(BCStyle.C, propertyConfigurationService.getConfigValue(CERT_COUNTRY_PROPERTY)); X500Name x500Name = nameBuilder.build(); BigInteger serial = new BigInteger(CERT_SERIAL_NUMBER_BIT_SIZE, SecureRandomFactory.createPRNG()); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = Date.from(startDate.toInstant().plus(propertyConfigurationService.getConfigValueAsInt(CERT_VALIDITY_DAYS_PROPERTY), ChronoUnit.DAYS)); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(x500Name, serial, startDate, endDate, x500Name, publicKeyInfo); String certFriendlyName = propertyConfigurationService.getConfigValue(CERT_PRIVATE_FRIENDLY_NAME_PROPERTY); certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, false, new DERBMPString(certFriendlyName)); return certificateBuilder; }
private String getMsCertTypeStringValue(byte[] octets) { // @formatter:off /* Not much information available about that extension... 06 09 ; OBJECT_ID (9 Bytes) | 2b 06 01 04 01 82 37 14 02 | ; 1.3.6.1.4.1.311.20.2 Certificate Template Name (Certificate Type) 04 0a ; OCTET_STRING (a Bytes)# 1e 08 00 55 00 73 00 65 00 72 ; ...U.s.e.r */ // @formatter:on DERBMPString derbmpString = DERBMPString.getInstance(octets); return derbmpString.toString(); }
private static boolean matchStringType(ASN1Encodable atvValue, StringType stringType) { boolean correctStringType = true; switch (stringType) { case bmpString: correctStringType = (atvValue instanceof DERBMPString); break; case printableString: correctStringType = (atvValue instanceof DERPrintableString); break; case teletexString: correctStringType = (atvValue instanceof DERT61String); break; case utf8String: correctStringType = (atvValue instanceof DERUTF8String); break; case ia5String: correctStringType = (atvValue instanceof DERIA5String); break; default: throw new RuntimeException("should not reach here, unknown StringType " + stringType); } // end switch return correctStringType; }
public static DirectoryString getInstance(Object o) { if (o == null || o instanceof DirectoryString) { return (DirectoryString)o; } if (o instanceof DERT61String) { return new DirectoryString((DERT61String)o); } if (o instanceof DERPrintableString) { return new DirectoryString((DERPrintableString)o); } if (o instanceof DERUniversalString) { return new DirectoryString((DERUniversalString)o); } if (o instanceof DERUTF8String) { return new DirectoryString((DERUTF8String)o); } if (o instanceof DERBMPString) { return new DirectoryString((DERBMPString)o); } throw new IllegalArgumentException("illegal object in getInstance: " + o.getClass().getName()); }
private static PKCS12SafeBagBuilder createCRTSafeBagBuilder(String alias, X509Certificate crt, boolean addKeyId) throws IOException, GeneralSecurityException { PKCS12SafeBagBuilder safeBagBuilder = new JcaPKCS12SafeBagBuilder(crt); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); if (addKeyId) { JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils(); SubjectKeyIdentifier subjectKeyIdentifier = extensionUtils.createSubjectKeyIdentifier(crt.getPublicKey()); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, subjectKeyIdentifier); } return safeBagBuilder; }
private static PKCS12SafeBagBuilder createKeySafeBagBuilder(String alias, KeyPair key) throws GeneralSecurityException { PKCS12SafeBagBuilder safeBagBuilder = new JcaPKCS12SafeBagBuilder(key.getPrivate()); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils(); SubjectKeyIdentifier subjectKeyIdentifier = extensionUtils.createSubjectKeyIdentifier(key.getPublic()); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, subjectKeyIdentifier); return safeBagBuilder; }
private static PKCS12SafeBagBuilder createKeySafeBagBuilder(String alias, KeyPair key, char[] passwordChars) throws GeneralSecurityException { PKCS12SafeBagBuilder safeBagBuilder = new JcaPKCS12SafeBagBuilder(key.getPrivate(), PKCS12_ENCRYPTOR_BUILDER.build(passwordChars)); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils(); SubjectKeyIdentifier subjectKeyIdentifier = extensionUtils.createSubjectKeyIdentifier(key.getPublic()); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, subjectKeyIdentifier); return safeBagBuilder; }
private String dumpString(ASN1String asn1String) { StringBuilder sb = new StringBuilder(); sb.append(indentSequence.toString(indentLevel)); if (asn1String instanceof DERBMPString) { sb.append("BMP STRING="); } else if (asn1String instanceof DERGeneralString) { sb.append("GENERAL STRING="); } else if (asn1String instanceof DERIA5String) { sb.append("IA5 STRING="); } else if (asn1String instanceof DERNumericString) { sb.append("NUMERIC STRING="); } else if (asn1String instanceof DERPrintableString) { sb.append("PRINTABLE STRING="); } else if (asn1String instanceof DERT61String) { sb.append("TELETEX STRING="); } else if (asn1String instanceof DERUniversalString) { sb.append("UNIVERSAL STRING="); } else if (asn1String instanceof DERUTF8String) { sb.append("UTF8 STRING="); } else if (asn1String instanceof DERVisibleString) { sb.append("VISIBLE STRING="); } else { sb.append("UNKNOWN STRING="); } sb.append("'"); sb.append(asn1String.getString()); sb.append("'"); sb.append(NEWLINE); return sb.toString(); }
private String getKeyID(Attribute[] attributes) { for (Attribute attr : attributes) { if (PKCS12SafeBag.friendlyNameAttribute.equals(attr.getAttrType())) { return DERBMPString.getInstance(attr.getAttrValues().getObjectAt(0)).getString(); } } throw new IllegalStateException("No friendlyNameAttribute found."); }
/** * 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; }
private DirectoryString( DERBMPString string) { this.string = string; }
private void checkDirectoryString(ASN1ObjectIdentifier extType, QaDirectoryString conf, StringBuilder failureMsg, byte[] extensionValue, Extensions requestedExtensions, ExtensionControl extControl) { if (conf == null) { byte[] expected = getExpectedExtValue(extType, requestedExtensions, extControl); if (!Arrays.equals(expected, extensionValue)) { addViolation(failureMsg, "extension values", hex(extensionValue), (expected == null) ? "not present" : hex(expected)); } return; } ASN1Primitive asn1; try { asn1 = ASN1Primitive.fromByteArray(extensionValue); } catch (IOException ex) { failureMsg.append("invalid syntax of extension value; "); return; } boolean correctStringType; switch (conf.type()) { case bmpString: correctStringType = (asn1 instanceof DERBMPString); break; case printableString: correctStringType = (asn1 instanceof DERPrintableString); break; case teletexString: correctStringType = (asn1 instanceof DERT61String); break; case utf8String: correctStringType = (asn1 instanceof DERUTF8String); break; default: throw new RuntimeException("should not reach here, unknown DirectoryStringType " + conf.type()); } // end switch if (!correctStringType) { failureMsg.append("extension value is not of type DirectoryString.") .append(conf.text()).append("; "); return; } String extTextValue = ((ASN1String) asn1).getString(); if (!conf.text().equals(extTextValue)) { addViolation(failureMsg, "content", extTextValue, conf.text()); } }
public PKCS12BagAttributeSetter setFriendlyName(String name) { carrier.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(name)); return this; }
public void testKeyBag() throws Exception { OutputEncryptor encOut = new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())).build(passwd); InputDecryptorProvider inputDecryptorProvider = new BcPKCS12PBEInputDecryptorProviderBuilder().build(passwd); KeyFactory fact = KeyFactory.getInstance("RSA", BC); PrivateKey privKey = fact.generatePrivate(privKeySpec); PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey); keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key")); PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder(); builder.addEncryptedData(encOut, keyBagBuilder.build()); PKCS12PfxPdu pfx = builder.build(new BcPKCS12MacCalculatorBuilder(), passwd); assertTrue(pfx.hasMac()); assertTrue(pfx.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE), passwd)); ContentInfo[] infos = pfx.getContentInfos(); for (int i = 0; i != infos.length; i++) { if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) { PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); PKCS12SafeBag[] bags = dataFact.getSafeBags(); assertEquals(1, bags.length); assertEquals(PKCSObjectIdentifiers.keyBag, bags[0].getType()); assertTrue(Arrays.areEqual(privKey.getEncoded(), ((PrivateKeyInfo)bags[0].getBagValue()).getEncoded())); Attribute[] attributes = bags[0].getAttributes(); assertEquals(1, attributes.length); assertEquals(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, attributes[0].getAttrType()); ASN1Encodable[] attrValues = attributes[0].getAttributeValues(); assertEquals(1, attrValues.length); assertEquals(new DERBMPString("Eric's Key"), attrValues[0]); } else { fail("unknown bag encountered"); } } }
public TestResult perform() { byte[] data = { 0, 1, 0, 1, 0, 0, 1 }; ASN1Primitive values[] = { new BERConstructedOctetString(data), new BERSequence(new DERPrintableString("hello world")), new BERSet(new DERPrintableString("hello world")), new BERTaggedObject(0, new DERPrintableString("hello world")), new DERApplicationSpecific(0, data), new DERBitString(data), new DERBMPString("hello world"), new DERBoolean(true), new DERBoolean(false), new DEREnumerated(100), new DERGeneralizedTime("20070315173729Z"), new DERGeneralString("hello world"), new DERIA5String("hello"), new DERInteger(1000), new DERNull(), new DERNumericString("123456"), new DERObjectIdentifier("1.1.1.10000.1"), new DEROctetString(data), new DERPrintableString("hello world"), new DERSequence(new DERPrintableString("hello world")), new DERSet(new DERPrintableString("hello world")), new DERT61String("hello world"), new DERTaggedObject(0, new DERPrintableString("hello world")), new DERUniversalString(data), new DERUTCTime(new Date()), new DERUTF8String("hello world"), new DERVisibleString("hello world") }; try { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); for (int i = 0; i != values.length; i++) { aOut.writeObject(values[i]); } ASN1Primitive[] readValues = new ASN1Primitive[values.length]; ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); ASN1InputStream aIn = new ASN1InputStream(bIn); for (int i = 0; i != values.length; i++) { ASN1Primitive o = aIn.readObject(); if (!o.equals(values[i])) { return new SimpleTestResult(false, getName() + ": Failed equality test for " + o.getClass()); } if (o.hashCode() != values[i].hashCode()) { return new SimpleTestResult(false, getName() + ": Failed hashCode test for " + o.getClass()); } } } catch (Exception e) { return new SimpleTestResult(false, getName() + ": Failed - exception " + e.toString(), e); } return new SimpleTestResult(true, getName() + ": Okay"); }
private PKCS12PfxPdu createPfx(PrivateKey privKey, PublicKey pubKey, X509Certificate[] chain) throws NoSuchAlgorithmException, IOException, PKCSException { JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); PKCS12SafeBagBuilder taCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[2]); taCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Primary Certificate")); PKCS12SafeBagBuilder caCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[1]); caCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Intermediate Certificate")); PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[0]); eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key")); eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey)); PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey, new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())).build(passwd)); keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key")); keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey)); // // construct the actual key store // PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder(); PKCS12SafeBag[] certs = new PKCS12SafeBag[3]; certs[0] = eeCertBagBuilder.build(); certs[1] = caCertBagBuilder.build(); certs[2] = taCertBagBuilder.build(); pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(passwd), certs); pfxPduBuilder.addData(keyBagBuilder.build()); return pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), passwd); }