use of com.github.zhenwei.core.asn1.x509.KeyUsage in project XobotOS by xamarin.
the class RFC3280CertPathUtilities method processCRLF.
/**
* Obtain and validate the certification path for the complete CRL issuer.
* If a key usage extension is present in the CRL issuer's certificate,
* verify that the cRLSign bit is set.
*
* @param crl CRL which contains revocation information for the certificate
* <code>cert</code>.
* @param cert The attribute certificate or certificate to check if it is
* revoked.
* @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
* @param defaultCRLSignKey The public key of the issuer certificate
* <code>defaultCRLSignCert</code>.
* @param paramsPKIX paramsPKIX PKIX parameters.
* @param certPathCerts The certificates on the certification path.
* @return A <code>Set</code> with all keys of possible CRL issuer
* certificates.
* @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
* some error occurs.
*/
protected static Set processCRLF(X509CRL crl, Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, ExtendedPKIXParameters paramsPKIX, List certPathCerts) throws AnnotatedException {
// (f)
// get issuer from CRL
X509CertStoreSelector selector = new X509CertStoreSelector();
try {
byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
selector.setSubject(issuerPrincipal);
} catch (IOException e) {
throw new AnnotatedException("Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
}
// get CRL signing certs
Collection coll;
try {
coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores());
coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores()));
coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores()));
} catch (AnnotatedException e) {
throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
}
coll.add(defaultCRLSignCert);
Iterator cert_it = coll.iterator();
List validCerts = new ArrayList();
List validKeys = new ArrayList();
while (cert_it.hasNext()) {
X509Certificate signingCert = (X509Certificate) cert_it.next();
/*
* CA of the certificate, for which this CRL is checked, has also
* signed CRL, so skip the path validation, because is already done
*/
if (signingCert.equals(defaultCRLSignCert)) {
validCerts.add(signingCert);
validKeys.add(defaultCRLSignKey);
continue;
}
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);
/*
* if signingCert is placed not higher on the cert path a
* dependency loop results. CRL for cert is checked, but
* signingCert is needed for checking the CRL which is dependent
* on checking cert because it is higher in the cert path and so
* signing signingCert transitively. so, revocation is disabled,
* forgery attacks of the CRL are detected in this outer loop
* for all other it must be enabled to prevent forgery attacks
*/
if (certPathCerts.contains(signingCert)) {
params.setRevocationEnabled(false);
} else {
params.setRevocationEnabled(true);
}
List certs = builder.build(params).getCertPath().getCertificates();
validCerts.add(signingCert);
validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0));
} catch (CertPathBuilderException e) {
throw new AnnotatedException("Internal error.", e);
} catch (CertPathValidatorException e) {
throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
Set checkKeys = new HashSet();
AnnotatedException lastException = null;
for (int i = 0; i < validCerts.size(); i++) {
X509Certificate signCert = (X509Certificate) validCerts.get(i);
boolean[] keyusage = signCert.getKeyUsage();
if (keyusage != null && (keyusage.length < 7 || !keyusage[CRL_SIGN])) {
lastException = new AnnotatedException("Issuer certificate key usage extension does not permit CRL signing.");
} else {
checkKeys.add(validKeys.get(i));
}
}
if (checkKeys.isEmpty() && lastException == null) {
throw new AnnotatedException("Cannot find a valid issuer certificate.");
}
if (checkKeys.isEmpty() && lastException != null) {
throw lastException;
}
return checkKeys;
}
use of com.github.zhenwei.core.asn1.x509.KeyUsage 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 com.github.zhenwei.core.asn1.x509.KeyUsage in project nhin-d by DirectProject.
the class KeyUsageExtensionField method injectReferenceValue.
/**
* {@inheritDoc}
*/
@Override
public void injectReferenceValue(X509Certificate value) throws PolicyProcessException {
this.certificate = value;
final DERObject exValue = getExtensionValue(value);
if (exValue == null) {
if (isRequired())
throw new PolicyRequiredException("Extention " + getExtentionIdentifier().getDisplay() + " is marked as required by is not present.");
else {
this.policyValue = PolicyValueFactory.getInstance(0);
return;
}
}
final KeyUsage keyUsage = new KeyUsage((DERBitString) exValue);
final byte[] data = keyUsage.getBytes();
final int intValue = (data.length == 1) ? data[0] & 0xff : (data[1] & 0xff) << 8 | (data[0] & 0xff);
this.policyValue = PolicyValueFactory.getInstance(intValue);
}
use of com.github.zhenwei.core.asn1.x509.KeyUsage in project poi by apache.
the class TestSignatureInfo method initKeyPair.
private void initKeyPair(String alias, String subjectDN) throws Exception {
final char[] password = "test".toCharArray();
File file = new File("build/test.pfx");
KeyStore keystore = KeyStore.getInstance("PKCS12");
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
keystore.load(fis, password);
fis.close();
} else {
keystore.load(null, password);
}
if (keystore.isKeyEntry(alias)) {
Key key = keystore.getKey(alias, password);
x509 = (X509Certificate) keystore.getCertificate(alias);
keyPair = new KeyPair(x509.getPublicKey(), (PrivateKey) key);
} else {
keyPair = PkiTestUtils.generateKeyPair();
Date notBefore = cal.getTime();
Calendar cal2 = (Calendar) cal.clone();
cal2.add(Calendar.YEAR, 1);
Date notAfter = cal2.getTime();
KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature);
x509 = PkiTestUtils.generateCertificate(keyPair.getPublic(), subjectDN, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, keyUsage);
keystore.setKeyEntry(alias, keyPair.getPrivate(), password, new Certificate[] { x509 });
FileOutputStream fos = new FileOutputStream(file);
keystore.store(fos, password);
fos.close();
}
}
use of com.github.zhenwei.core.asn1.x509.KeyUsage in project robovm by robovm.
the class RFC3280CertPathUtilities method processCRLF.
/**
* Obtain and validate the certification path for the complete CRL issuer.
* If a key usage extension is present in the CRL issuer's certificate,
* verify that the cRLSign bit is set.
*
* @param crl CRL which contains revocation information for the certificate
* <code>cert</code>.
* @param cert The attribute certificate or certificate to check if it is
* revoked.
* @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
* @param defaultCRLSignKey The public key of the issuer certificate
* <code>defaultCRLSignCert</code>.
* @param paramsPKIX paramsPKIX PKIX parameters.
* @param certPathCerts The certificates on the certification path.
* @return A <code>Set</code> with all keys of possible CRL issuer
* certificates.
* @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
* some error occurs.
*/
protected static Set processCRLF(X509CRL crl, Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, ExtendedPKIXParameters paramsPKIX, List certPathCerts) throws AnnotatedException {
// (f)
// get issuer from CRL
X509CertStoreSelector selector = new X509CertStoreSelector();
try {
byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
selector.setSubject(issuerPrincipal);
} catch (IOException e) {
throw new AnnotatedException("Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
}
// get CRL signing certs
Collection coll;
try {
coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores());
coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores()));
coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores()));
} catch (AnnotatedException e) {
throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
}
coll.add(defaultCRLSignCert);
Iterator cert_it = coll.iterator();
List validCerts = new ArrayList();
List validKeys = new ArrayList();
while (cert_it.hasNext()) {
X509Certificate signingCert = (X509Certificate) cert_it.next();
/*
* CA of the certificate, for which this CRL is checked, has also
* signed CRL, so skip the path validation, because is already done
*/
if (signingCert.equals(defaultCRLSignCert)) {
validCerts.add(signingCert);
validKeys.add(defaultCRLSignKey);
continue;
}
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);
/*
* if signingCert is placed not higher on the cert path a
* dependency loop results. CRL for cert is checked, but
* signingCert is needed for checking the CRL which is dependent
* on checking cert because it is higher in the cert path and so
* signing signingCert transitively. so, revocation is disabled,
* forgery attacks of the CRL are detected in this outer loop
* for all other it must be enabled to prevent forgery attacks
*/
if (certPathCerts.contains(signingCert)) {
params.setRevocationEnabled(false);
} else {
params.setRevocationEnabled(true);
}
List certs = builder.build(params).getCertPath().getCertificates();
validCerts.add(signingCert);
validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0));
} catch (CertPathBuilderException e) {
throw new AnnotatedException("Internal error.", e);
} catch (CertPathValidatorException e) {
throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
Set checkKeys = new HashSet();
AnnotatedException lastException = null;
for (int i = 0; i < validCerts.size(); i++) {
X509Certificate signCert = (X509Certificate) validCerts.get(i);
boolean[] keyusage = signCert.getKeyUsage();
if (keyusage != null && (keyusage.length < 7 || !keyusage[CRL_SIGN])) {
lastException = new AnnotatedException("Issuer certificate key usage extension does not permit CRL signing.");
} else {
checkKeys.add(validKeys.get(i));
}
}
if (checkKeys.isEmpty() && lastException == null) {
throw new AnnotatedException("Cannot find a valid issuer certificate.");
}
if (checkKeys.isEmpty() && lastException != null) {
throw lastException;
}
return checkKeys;
}
Aggregations