use of org.nhindirect.stagent.cert.X509CertificateEx in project nhin-d by DirectProject.
the class SMIMECryptographerImpl method createSignatureEntity.
protected MimeMultipart createSignatureEntity(byte[] entity, Collection<X509Certificate> signingCertificates) {
MimeMultipart retVal = null;
try {
final MimeBodyPart signedContent = new MimeBodyPart(new ByteArrayInputStream(entity));
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(x509CertificateObjectsIdent);
signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
final List<X509Certificate> certList = new ArrayList<X509Certificate>();
final DirectSignedDataGenerator generator = sigFactory.createInstance();
for (X509Certificate signer : signingCertificates) {
if (signer instanceof X509CertificateEx) {
generator.addSigner(((X509CertificateEx) signer).getPrivateKey(), signer, this.m_digestAlgorithm.getOID(), createAttributeTable(signedAttrs), null);
certList.add(signer);
}
}
final CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderNameForTypeAndAlgorithm("CertStore", "Collection"));
generator.addCertificatesAndCRLs(certsAndcrls);
final CMSProcessableBodyPart content = new CMSProcessableBodyPart(signedContent);
final CMSSignedData signedData = generator.generate(content);
final String header = "signed; protocol=\"application/pkcs7-signature\"; micalg=" + CryptoAlgorithmsHelper.toDigestAlgorithmMicalg(this.m_digestAlgorithm);
//String encodedSig = Base64.encodeBase64String(signedData.getEncoded());
final String encodedSig = StringUtils.newStringUtf8(Base64.encodeBase64(signedData.getEncoded(), true));
retVal = new MimeMultipart(header.toString());
final MimeBodyPart sig = new MimeBodyPart(new InternetHeaders(), encodedSig.getBytes("ASCII"));
sig.addHeader("Content-Type", "application/pkcs7-signature; name=smime.p7s; smime-type=signed-data");
sig.addHeader("Content-Disposition", "attachment; filename=\"smime.p7s\"");
sig.addHeader("Content-Description", "S/MIME Cryptographic Signature");
sig.addHeader("Content-Transfer-Encoding", "base64");
retVal.addBodyPart(signedContent);
retVal.addBodyPart(sig);
} catch (MessagingException e) {
throw new MimeException(MimeError.InvalidMimeEntity, e);
} catch (IOException e) {
throw new SignatureException(SignatureError.InvalidMultipartSigned, e);
} catch (Exception e) {
throw new NHINDException(MimeError.Unexpected, e);
}
return retVal;
}
use of org.nhindirect.stagent.cert.X509CertificateEx in project nhin-d by DirectProject.
the class SMIMECryptographerImpl method decrypt.
/**
* Decrypts an entity with the provided certificate's private key.
* @param encryptedEntity The entity that will be decrypted.
* @param decryptingCertificate The certificate whose private key will be used to decrypt the message.
* @return A MimeEntity containing the decrypted part.
*/
public MimeEntity decrypt(MimeEntity encryptedEntity, X509CertificateEx decryptingCertificate) {
if (encryptedEntity == null || decryptingCertificate == null) {
throw new IllegalArgumentException();
}
if (!decryptingCertificate.hasPrivateKey()) {
throw new IllegalArgumentException("Certificate has no private key");
}
encryptedEntity.verifyContentType(SMIMEStandard.EncryptedContentTypeHeaderValue);
encryptedEntity.verifyTransferEncoding(MimeStandard.TransferEncodingBase64);
Collection<X509CertificateEx> certs = new ArrayList<X509CertificateEx>();
certs.add(decryptingCertificate);
MimeEntity retVal = this.decrypt(encryptedEntity, certs);
//
return retVal;
}
use of org.nhindirect.stagent.cert.X509CertificateEx in project nhin-d by DirectProject.
the class StripP12Passphrase method stripP12File.
/*
* Main strip operation of removing the password and passphrase and creating a new p12 file.
*/
private static void stripP12File() {
FileOutputStream outStr = null;
try {
byte[] p12Data = loadFileData(p12File);
if (p12Data != null) {
X509CertificateEx p12Cert = certFromData(p12Data);
if (p12Cert == null)
return;
File outFile = getPKCS12OutFile();
KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
localKeyStore.load(null, null);
char[] emptyPass = "".toCharArray();
localKeyStore.setKeyEntry("privCert", p12Cert.getPrivateKey(), emptyPass, new java.security.cert.Certificate[] { p12Cert });
outStr = new FileOutputStream(outFile);
localKeyStore.store(outStr, emptyPass);
System.out.println("Created pcks12 file " + createFile.getAbsolutePath());
}
} catch (Exception e) {
System.out.println("Could not create p12 file " + e.getMessage());
} finally {
IOUtils.closeQuietly(outStr);
}
}
use of org.nhindirect.stagent.cert.X509CertificateEx in project nhin-d by DirectProject.
the class CertCommands method importPrivateCert.
@Command(name = "AddPrivateCert", usage = IMPORT_PRIVATE_CERT_USAGE)
public void importPrivateCert(String[] args) {
final String fileLoc = StringArrayUtil.getRequiredValue(args, 0);
final String passPhrase = StringArrayUtil.getOptionalValue(args, 1, "");
try {
final byte[] certBytes = FileUtils.readFileToByteArray(new File(fileLoc));
final byte[] insertBytes = (passPhrase == null || passPhrase.isEmpty()) ? certBytes : CertUtils.pkcs12ToStrippedPkcs12(certBytes, passPhrase);
final X509Certificate cert = CertUtils.toX509Certificate(insertBytes);
org.nhind.config.Certificate addCert = new org.nhind.config.Certificate();
addCert.setData(certBytes);
addCert.setOwner(CryptoExtensions.getSubjectAddress(cert));
addCert.setPrivateKey(cert instanceof X509CertificateEx);
addCert.setStatus(EntityStatus.ENABLED);
proxy.addCertificates(new org.nhind.config.Certificate[] { addCert });
System.out.println("Successfully imported private certificate.");
} catch (IOException e) {
System.out.println("Error reading file " + fileLoc + " : " + e.getMessage());
return;
} catch (Exception e) {
System.out.println("Error importing certificate " + fileLoc + " : " + e.getMessage());
}
}
use of org.nhindirect.stagent.cert.X509CertificateEx 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++;
}
}
}
Aggregations