use of org.openecard.bouncycastle.asn1.x509.Certificate in project nhin-d by DirectProject.
the class CertGenerator method createNewCA.
private static CertCreateFields createNewCA(CertCreateFields fields, KeyPair keyPair, boolean addAltNames) throws Exception {
StringBuilder dnBuilder = new StringBuilder();
String altName = "";
// create the DN
if (fields.getAttributes().containsKey("EMAILADDRESS")) {
dnBuilder.append("EMAILADDRESS=").append(fields.getAttributes().get("EMAILADDRESS")).append(", ");
altName = fields.getAttributes().get("EMAILADDRESS").toString();
}
if (fields.getAttributes().containsKey("CN"))
dnBuilder.append("CN=").append(fields.getAttributes().get("CN")).append(", ");
if (fields.getAttributes().containsKey("C"))
dnBuilder.append("C=").append(fields.getAttributes().get("C")).append(", ");
if (fields.getAttributes().containsKey("ST"))
dnBuilder.append("ST=").append(fields.getAttributes().get("ST")).append(", ");
if (fields.getAttributes().containsKey("L"))
dnBuilder.append("L=").append(fields.getAttributes().get("L")).append(", ");
if (fields.getAttributes().containsKey("O"))
dnBuilder.append("O=").append(fields.getAttributes().get("O")).append(", ");
String DN = dnBuilder.toString().trim();
if (DN.endsWith(","))
DN = DN.substring(0, DN.length() - 1);
X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.DAY_OF_MONTH, fields.getExpDays());
v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
v1CertGen.setIssuerDN(new X509Principal(DN));
v1CertGen.setNotBefore(start.getTime());
v1CertGen.setNotAfter(end.getTime());
// issuer and subject are the same for a CA
v1CertGen.setSubjectDN(new X509Principal(DN));
v1CertGen.setPublicKey(keyPair.getPublic());
v1CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
v1CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
if (addAltNames && !altName.isEmpty()) {
int nameType = altName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
GeneralNames subjectAltName = new GeneralNames(new GeneralName(nameType, altName));
v1CertGen.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
}
X509Certificate newCACert = v1CertGen.generate(keyPair.getPrivate(), CryptoExtensions.getJCEProviderName());
// validate the certificate
newCACert.verify(keyPair.getPublic());
// write the certificate the file system
writeCertAndKey(newCACert, keyPair.getPrivate(), fields);
return fields;
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project nhin-d by DirectProject.
the class MessageSigInspector method main.
public static void main(String[] args) {
if (args.length == 0) {
//printUsage();
System.exit(-1);
}
String messgefile = null;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
// Options
if (!arg.startsWith("-")) {
System.err.println("Error: Unexpected argument [" + arg + "]\n");
//printUsage();
System.exit(-1);
} else if (arg.equalsIgnoreCase("-msgFile")) {
if (i == args.length - 1 || args[i + 1].startsWith("-")) {
System.err.println("Error: Missing message file");
System.exit(-1);
}
messgefile = args[++i];
} else if (arg.equals("-help")) {
//printUsage();
System.exit(-1);
} else {
System.err.println("Error: Unknown argument " + arg + "\n");
//printUsage();
System.exit(-1);
}
}
if (messgefile == null) {
System.err.println("Error: missing message file\n");
}
InputStream inStream = null;
try {
inStream = FileUtils.openInputStream(new File(messgefile));
MimeMessage message = new MimeMessage(null, inStream);
MimeMultipart mm = (MimeMultipart) message.getContent();
//byte[] messageBytes = EntitySerializer.Default.serializeToBytes(mm.getBodyPart(0).getContent());
//MimeBodyPart signedContent = null;
//signedContent = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
final CMSSignedData signed = new CMSSignedData(new CMSProcessableBodyPart(mm.getBodyPart(0)), mm.getBodyPart(1).getInputStream());
CertStore certs = signed.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
SignerInformationStore signers = signed.getSignerInfos();
@SuppressWarnings("unchecked") Collection<SignerInformation> c = signers.getSigners();
System.out.println("Found " + c.size() + " signers");
int cnt = 1;
for (SignerInformation signer : c) {
Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID());
if (certCollection != null && certCollection.size() > 0) {
X509Certificate cert = (X509Certificate) certCollection.iterator().next();
System.out.println("\r\nInfo for certificate " + cnt++);
System.out.println("\tSubject " + cert.getSubjectDN());
FileUtils.writeByteArrayToFile(new File("SigCert.der"), cert.getEncoded());
byte[] bytes = cert.getExtensionValue("2.5.29.15");
if (bytes != null) {
final DERObject obj = getObject(bytes);
final KeyUsage keyUsage = new KeyUsage((DERBitString) obj);
final byte[] data = keyUsage.getBytes();
final int intValue = (data.length == 1) ? data[0] & 0xff : (data[1] & 0xff) << 8 | (data[0] & 0xff);
System.out.println("\tKey Usage: " + intValue);
} else
System.out.println("\tKey Usage: NONE");
//verify and get the digests
final Attribute digAttr = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
final DERObject hashObj = digAttr.getAttrValues().getObjectAt(0).getDERObject();
final byte[] signedDigest = ((ASN1OctetString) hashObj).getOctets();
final String signedDigestHex = org.apache.commons.codec.binary.Hex.encodeHexString(signedDigest);
System.out.println("\r\nSigned Message Digest: " + signedDigestHex);
try {
signer.verify(cert, "BC");
System.out.println("Signature verified.");
} catch (CMSException e) {
System.out.println("Signature failed to verify.");
}
// should have the computed digest now
final byte[] digest = signer.getContentDigest();
final String digestHex = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
System.out.println("\r\nComputed Message Digest: " + digestHex);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(inStream);
}
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project XobotOS by xamarin.
the class CertPathValidatorUtilities method getNextWorkingKey.
/**
* Return the next working key inheriting DSA parameters if necessary.
* <p>
* This methods inherits DSA parameters from the indexed certificate or
* previous certificates in the certificate chain to the returned
* <code>PublicKey</code>. The list is searched upwards, meaning the end
* certificate is at position 0 and previous certificates are following.
* </p>
* <p>
* If the indexed certificate does not contain a DSA key this method simply
* returns the public key. If the DSA key already contains DSA parameters
* the key is also only returned.
* </p>
*
* @param certs The certification path.
* @param index The index of the certificate which contains the public key
* which should be extended with DSA parameters.
* @return The public key of the certificate in list position
* <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) throws CertPathValidatorException {
Certificate cert = (Certificate) certs.get(index);
PublicKey pubKey = cert.getPublicKey();
if (!(pubKey instanceof DSAPublicKey)) {
return pubKey;
}
DSAPublicKey dsaPubKey = (DSAPublicKey) pubKey;
if (dsaPubKey.getParams() != null) {
return dsaPubKey;
}
for (int i = index + 1; i < certs.size(); i++) {
X509Certificate parentCert = (X509Certificate) certs.get(i);
pubKey = parentCert.getPublicKey();
if (!(pubKey instanceof DSAPublicKey)) {
throw new CertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
}
DSAPublicKey prevDSAPubKey = (DSAPublicKey) pubKey;
if (prevDSAPubKey.getParams() == null) {
continue;
}
DSAParams dsaParams = prevDSAPubKey.getParams();
DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec(dsaPubKey.getY(), dsaParams.getP(), dsaParams.getQ(), dsaParams.getG());
try {
KeyFactory keyFactory = KeyFactory.getInstance("DSA", BouncyCastleProvider.PROVIDER_NAME);
return keyFactory.generatePublic(dsaPubKeySpec);
} catch (Exception exception) {
throw new RuntimeException(exception.getMessage());
}
}
throw new CertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project Openfire by igniterealtime.
the class CertificateManagerTest method testServerIdentitiesXmppAddr.
/**
* {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
* <ul>
* <li>the 'xmppAddr' subjectAltName value</li>
* <li>explicitly not the Common Name</li>
* </ul>
*
* when a certificate contains:
* <ul>
* <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-xmppAddr"</li>
* </ul>
*/
@Test
public void testServerIdentitiesXmppAddr() throws Exception {
// Setup fixture.
final String subjectCommonName = "MySubjectCommonName";
final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr";
final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(// Issuer
new X500Name("CN=MyIssuer"), // Random serial number
BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())), // Not before 30 days ago
new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30)), // Not after 99 days from now
new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99)), // Subject
new X500Name("CN=" + subjectCommonName), subjectKeyPair.getPublic());
final DERSequence otherName = new DERSequence(new ASN1Encodable[] { XMPP_ADDR_OID, new DERUTF8String(subjectAltNameXmppAddr) });
final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.otherName, otherName));
builder.addExtension(Extension.subjectAlternativeName, true, subjectAltNames);
final X509CertificateHolder certificateHolder = builder.build(contentSigner);
final X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
// Execute system under test
final List<String> serverIdentities = CertificateManager.getServerIdentities(cert);
// Verify result
assertEquals(1, serverIdentities.size());
assertTrue(serverIdentities.contains(subjectAltNameXmppAddr));
assertFalse(serverIdentities.contains(subjectCommonName));
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project Openfire by igniterealtime.
the class CertificateManagerTest method testServerIdentitiesDNS.
/**
* {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
* <ul>
* <li>the DNS subjectAltName value</li>
* <li>explicitly not the Common Name</li>
* </ul>
*
* when a certificate contains:
* <ul>
* <li>a subjectAltName entry of type DNS </li>
* </ul>
*/
@Test
public void testServerIdentitiesDNS() throws Exception {
// Setup fixture.
final String subjectCommonName = "MySubjectCommonName";
final String subjectAltNameDNS = "MySubjectAltNameDNS";
final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(// Issuer
new X500Name("CN=MyIssuer"), // Random serial number
BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())), // Not before 30 days ago
new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30)), // Not after 99 days from now
new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99)), // Subject
new X500Name("CN=" + subjectCommonName), subjectKeyPair.getPublic());
final GeneralNames generalNames = new GeneralNames(new GeneralName(GeneralName.dNSName, subjectAltNameDNS));
builder.addExtension(Extension.subjectAlternativeName, false, generalNames);
final X509CertificateHolder certificateHolder = builder.build(contentSigner);
final X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
// Execute system under test
final List<String> serverIdentities = CertificateManager.getServerIdentities(cert);
// Verify result
assertEquals(1, serverIdentities.size());
assertTrue(serverIdentities.contains(subjectAltNameDNS));
assertFalse(serverIdentities.contains(subjectCommonName));
}
Aggregations