use of java.security.cert.CollectionCertStoreParameters in project cloudstack by apache.
the class CertServiceImpl method validateChain.
private void validateChain(final List<Certificate> chain, final Certificate cert) {
final List<Certificate> certs = new ArrayList<Certificate>();
final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();
// adding for self signed certs
certs.add(cert);
certs.addAll(chain);
for (final Certificate c : certs) {
if (!(c instanceof X509Certificate)) {
throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");
}
final X509Certificate xCert = (X509Certificate) c;
anchors.add(new TrustAnchor(xCert, null));
}
final X509CertSelector target = new X509CertSelector();
target.setCertificate((X509Certificate) cert);
PKIXBuilderParameters params = null;
try {
params = new PKIXBuilderParameters(anchors, target);
params.setRevocationEnabled(false);
params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
final CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
builder.build(params);
} catch (final InvalidAlgorithmParameterException | CertPathBuilderException | NoSuchAlgorithmException e) {
throw new IllegalStateException("Invalid certificate chain", e);
} catch (final NoSuchProviderException e) {
throw new CloudRuntimeException("No provider for certificate validation", e);
}
}
use of java.security.cert.CollectionCertStoreParameters in project jdk8u_jdk by JetBrains.
the class NoExtensions method doBuild.
private void doBuild(X509Certificate userCert) throws Exception {
// get the set of trusted CA certificates (only one in this instance)
HashSet trustAnchors = new HashSet();
X509Certificate trustedCert = getTrustedCertificate();
trustAnchors.add(new TrustAnchor(trustedCert, null));
// put together a CertStore (repository of the certificates and CRLs)
ArrayList certs = new ArrayList();
certs.add(trustedCert);
certs.add(userCert);
CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
CertStore certStore = CertStore.getInstance("Collection", certStoreParams);
// specify the target certificate via a CertSelector
X509CertSelector certSelector = new X509CertSelector();
certSelector.setCertificate(userCert);
// seems to be required
certSelector.setSubject(userCert.getSubjectDN().getName());
// build a valid cerificate path
CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
certPathBuilderParams.addCertStore(certStore);
certPathBuilderParams.setRevocationEnabled(false);
CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);
// get and show cert path
CertPath certPath = result.getCertPath();
// System.out.println(certPath.toString());
}
use of java.security.cert.CollectionCertStoreParameters in project nhin-d by DirectProject.
the class SplitProviderDirectSignedDataGenerator_generateTest method setupSigningInfo.
protected void setupSigningInfo(DirectSignedDataGenerator gen) throws Exception {
final ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
final SMIMECapabilityVector caps = new SMIMECapabilityVector();
caps.addCapability(SMIMECapability.dES_EDE3_CBC);
caps.addCapability(SMIMECapability.rC2_CBC, 128);
caps.addCapability(SMIMECapability.dES_CBC);
caps.addCapability(new DERObjectIdentifier("1.2.840.113549.1.7.1"));
caps.addCapability(SMIMECryptographerImpl.x509CertificateObjectsIdent);
signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
// setup the certificates
if (signerCert == null)
signerCert = TestUtils.getInternalCert("user1");
final List<X509Certificate> certList = new ArrayList<X509Certificate>();
// add certificate
gen.addSigner(((X509CertificateEx) signerCert).getPrivateKey(), signerCert, DigestAlgorithm.SHA256.getOID(), SMIMECryptographerImpl.createAttributeTable(signedAttrs), null);
certList.add(signerCert);
final CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderNameForTypeAndAlgorithm("CertStore", "Collection"));
gen.addCertificatesAndCRLs(certsAndcrls);
}
use of java.security.cert.CollectionCertStoreParameters in project nhin-d by DirectProject.
the class SigTest method testCreateVerifySig.
public void testCreateVerifySig() throws Exception {
X509CertificateEx internalCert = TestUtils.getInternalCert("user1");
X509Certificate caCert = TestUtils.getExternalCert("cacert");
String testMessage = TestUtils.readResource("MultipartMimeMessage.txt");
MimeMessage entity = EntitySerializer.Default.deserialize(testMessage);
Message message = new Message(entity);
MimeEntity entityToSig = message.extractEntityForSignature(true);
// Serialize message out as ASCII encoded...
byte[] messageBytes = EntitySerializer.Default.serializeToBytes(entityToSig);
MimeBodyPart partToSign = null;
try {
partToSign = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
} catch (Exception e) {
}
SMIMESignedGenerator gen = new SMIMESignedGenerator();
ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
SMIMECapabilityVector caps = new SMIMECapabilityVector();
caps.addCapability(SMIMECapability.dES_EDE3_CBC);
caps.addCapability(SMIMECapability.rC2_CBC, 128);
caps.addCapability(SMIMECapability.dES_CBC);
caps.addCapability(new DERObjectIdentifier("1.2.840.113549.1.7.1"));
caps.addCapability(PKCSObjectIdentifiers.x509Certificate);
signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
List certList = new ArrayList();
gen.addSigner(internalCert.getPrivateKey(), internalCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null);
//SMIMESignedGenerator.DIGEST_SHA1, null, null);
certList.add(internalCert);
MimeMultipart retVal = null;
CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderName());
gen.addCertificatesAndCRLs(certsAndcrls);
_certStores.add(certsAndcrls);
_signers.add(new Signer(internalCert.getPrivateKey(), internalCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null));
retVal = generate(partToSign, CryptoExtensions.getJCEProviderName());
for (int i = 0; i < 10; ++i) {
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
retVal.writeTo(oStream);
oStream.flush();
byte[] serialzedBytes = oStream.toByteArray();
//System.out.println(new String(serialzedBytes, "ASCII") + "\r\n\r\n\r\n\r\n\r\n");
ByteArrayDataSource dataSource = new ByteArrayDataSource(serialzedBytes, retVal.getContentType());
MimeMultipart verifyMM = new MimeMultipart(dataSource);
CMSSignedData signed = null;
//CMSSignedData signeddata = new CMSSignedData(new CMSProcessableBodyPartInbound(verifyMM.getBodyPart(0)), verifyMM.getBodyPart(1).getInputStream());
CMSSignedData signeddata = new CMSSignedData(new CMSProcessableBodyPartInbound(partToSign), verifyMM.getBodyPart(1).getInputStream());
int verified = 0;
CertStore certs = signeddata.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
SignerInformationStore signers = signeddata.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext()) {
SignerInformation signer = (SignerInformation) it.next();
Collection certCollection = certs.getCertificates(signer.getSID());
Attribute dig = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
DERObject hashObj = dig.getAttrValues().getObjectAt(0).getDERObject();
byte[] signedHash = ((ASN1OctetString) hashObj).getOctets();
System.out.print("value of signedHash: \r\n\tvalue: ");
for (byte bt : signedHash) {
System.out.print(bt + " ");
}
System.out.println();
Iterator certIt = certCollection.iterator();
try {
assertTrue(signer.verify(internalCert, CryptoExtensions.getJCEProviderName()));
} catch (Exception e) {
e.printStackTrace();
}
byte[] bytes = signer.getContentDigest();
/*
X509Certificate cert = (X509Certificate)certIt.next();
if (signer.verify(cert.getPublicKey()))
{
verified++;
}
*/
verified++;
}
}
}
use of java.security.cert.CollectionCertStoreParameters in project sic by belluccifranco.
the class AfipWebServiceSOAPClient method crearCMS.
public byte[] crearCMS(byte[] p12file, String p12pass, String signer, String service, long ticketTime) {
PrivateKey pKey = null;
X509Certificate pCertificate = null;
byte[] asn1_cms = null;
CertStore cstore = null;
try {
KeyStore ks = KeyStore.getInstance("pkcs12");
InputStream is;
is = Utilidades.convertirByteArrayToInputStream(p12file);
ks.load(is, p12pass.toCharArray());
is.close();
pKey = (PrivateKey) ks.getKey(signer, p12pass.toCharArray());
pCertificate = (X509Certificate) ks.getCertificate(signer);
ArrayList<X509Certificate> certList = new ArrayList<>();
certList.add(pCertificate);
if (Security.getProvider("BC") == null) {
Security.addProvider(new BouncyCastleProvider());
}
cstore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | InvalidAlgorithmParameterException | NoSuchProviderException ex) {
LOGGER.error(ex.getMessage());
throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_certificado_error"));
}
String loginTicketRequest_xml = this.crearTicketRequerimientoAcceso(service, ticketTime);
try {
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
generator.addSigner(pKey, pCertificate, CMSSignedDataGenerator.DIGEST_SHA1);
generator.addCertificatesAndCRLs(cstore);
CMSProcessable data = new CMSProcessableByteArray(loginTicketRequest_xml.getBytes());
CMSSignedData signed = generator.generate(data, true, "BC");
asn1_cms = signed.getEncoded();
} catch (IllegalArgumentException | CertStoreException | CMSException | NoSuchAlgorithmException | NoSuchProviderException | IOException ex) {
LOGGER.error(ex.getMessage());
throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_firmando_certificado_error"));
}
return asn1_cms;
}
Aggregations