use of com.github.zhenwei.core.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 com.github.zhenwei.core.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 com.github.zhenwei.core.asn1.x509.Certificate in project oxAuth by GluuFederation.
the class CRLCertificateVerifier method getCrlUri.
public String getCrlUri(X509Certificate certificate) throws IOException {
ASN1Primitive obj;
try {
obj = getExtensionValue(certificate, Extension.cRLDistributionPoints.getId());
} catch (IOException ex) {
log.error("Failed to get CRL URL", ex);
return null;
}
if (obj == null) {
return null;
}
CRLDistPoint distPoint = CRLDistPoint.getInstance(obj);
DistributionPoint[] distributionPoints = distPoint.getDistributionPoints();
for (DistributionPoint distributionPoint : distributionPoints) {
DistributionPointName distributionPointName = distributionPoint.getDistributionPoint();
if (DistributionPointName.FULL_NAME != distributionPointName.getType()) {
continue;
}
GeneralNames generalNames = (GeneralNames) distributionPointName.getName();
GeneralName[] names = generalNames.getNames();
for (GeneralName name : names) {
if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
continue;
}
DERIA5String derStr = DERIA5String.getInstance((ASN1TaggedObject) name.toASN1Primitive(), false);
return derStr.getString();
}
}
return null;
}
use of com.github.zhenwei.core.asn1.x509.Certificate in project poi by apache.
the class PkiTestUtils method createOcspResp.
public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis) throws Exception {
DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());
// request
//create a nonce to avoid replay attack
BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
Extensions exts = new Extensions(ext);
OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
ocspReqBuilder.addRequest(certId);
ocspReqBuilder.setRequestExtensions(exts);
OCSPReq ocspReq = ocspReqBuilder.build();
SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded());
BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
basicOCSPRespBuilder.setResponseExtensions(exts);
// request processing
Req[] requestList = ocspReq.getRequestList();
for (Req ocspRequest : requestList) {
CertificateID certificateID = ocspRequest.getCertID();
CertificateStatus certificateStatus = CertificateStatus.GOOD;
if (revoked) {
certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
}
basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
}
// basic response generation
X509CertificateHolder[] chain = null;
if (!ocspResponderCertificate.equals(issuerCertificate)) {
// TODO: HorribleProxy can't convert array input params yet
chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), issuerHolder };
}
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(ocspResponderPrivateKey);
BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));
OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);
return ocspResp;
}
use of com.github.zhenwei.core.asn1.x509.Certificate 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();
}
}
Aggregations