/** * Get S/MIME capabilities (1.2.840.113549.1.9.15) extension value as a string. * * <pre> * SMIMECapability ::= SEQUENCE { * capabilityID OBJECT IDENTIFIER, * parameters ANY DEFINED BY capabilityID OPTIONAL } * SMIMECapabilities ::= SEQUENCE OF SMIMECapability * </pre> * * @see <a href="http://tools.ietf.org/html/rfc2633">RFC 2633</a> * @param bValue The octet string value * @return Extension value as a string * @throws IOException If an I/O problem occurs */ private String getSmimeCapabilitiesStringValue(byte[] bValue) throws IOException { SMIMECapabilities caps = SMIMECapabilities.getInstance(ASN1Primitive.fromByteArray(bValue)); String sParams = RB.getString("SmimeParameters"); StringBuilder sb = new StringBuilder(); for (Object o : caps.getCapabilities(null)) { SMIMECapability cap = (SMIMECapability) o; String sCapId = cap.getCapabilityID().getId(); String sCap = getRes(sCapId, "UnrecognisedSmimeCapability"); if (sb.length() != 0) { sb.append("<br>"); } sb.append("<ul><li>"); sb.append(MessageFormat.format(sCap, sCapId)); ASN1Encodable params; if ((params = cap.getParameters()) != null) { sb.append("<ul><li>"); sb.append(sParams); sb.append(": "); sb.append(stringify(params)); sb.append("</li></ul>"); } sb.append("</li></ul>"); } return sb.toString(); }
private static MimeMultipart signMessage(MimeBodyPart mbp) throws Exception { // Open the key store char[] pwd = "password".toCharArray(); KeyStore ks = MailsterKeyStoreFactory.loadKeyStore("PKCS12", "clients.p12", pwd); String alias = MailsterKeyStoreFactory.DEFAULT_CERT_ALIAS; Certificate[] chain = ks.getCertificateChain(alias); PrivateKey privateKey = (PrivateKey) ks.getKey(alias, pwd); ArrayList<Certificate> certList = new ArrayList<Certificate>(); for (int i = 0; i < chain.length; i++) certList.add(chain[i]); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); 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(SMIMECapability.aES256_CBC); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); SMIMESignedGenerator gen = new SMIMESignedGenerator(); gen.addSigner(privateKey, (X509Certificate) chain[0], SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null); gen.addCertificatesAndCRLs(certs); return gen.generate(mbp, "BC"); }
private ASN1EncodableVector generateSignedAttributes() { 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); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); return signedAttrs; }
@PublicAtsApi public Package sign( Package sourcePackage ) throws ActionException { try { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } KeyStore ks = getKeystore(); PrivateKey privateKey = (PrivateKey) ks.getKey(aliasOrCN, certPassword.toCharArray()); X509Certificate cer = (X509Certificate) ks.getCertificate(aliasOrCN); /* Create the SMIMESignedGenerator */ SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); ASN1EncodableVector attributes = new ASN1EncodableVector(); attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(new IssuerAndSerialNumber(new X500Name( (cer).getIssuerDN() .getName()), cer.getSerialNumber()))); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); if (signatureAlgorithm == null) { signatureAlgorithm = SignatureAlgorithm.DSA.equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA"; } SMIMESignedGenerator signer = new SMIMESignedGenerator(); JcaSimpleSignerInfoGeneratorBuilder signerGeneratorBuilder = new JcaSimpleSignerInfoGeneratorBuilder(); signerGeneratorBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME); signerGeneratorBuilder.setSignedAttributeGenerator(new AttributeTable(attributes)); signer.addSignerInfoGenerator(signerGeneratorBuilder.build(signatureAlgorithm, privateKey, cer)); /* Add the list of certs to the generator */ List<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(cer); Store<?> certs = new JcaCertStore(certList); signer.addCertificates(certs); /* Sign the message */ Session session = Session.getDefaultInstance(System.getProperties(), null); MimeMultipart mm = signer.generate(getMimeMessage(sourcePackage)); MimeMessage signedMessage = new MimeMessage(session); /* Set all original MIME headers in the signed message */ Enumeration<?> headers = getMimeMessage(sourcePackage).getAllHeaderLines(); while (headers.hasMoreElements()) { signedMessage.addHeaderLine((String) headers.nextElement()); } /* Set the content of the signed message */ signedMessage.setContent(mm); signedMessage.saveChanges(); return new MimePackage(signedMessage); } catch (Exception e) { throw new ActionException(EXCEPTION_WHILE_SIGNING, e); } }
private MimeBodyPart signMessage(MimeBodyPart bodyPart) throws Exception{ X509Certificate cert = partnershipDVO.getVerifyX509Certificate(); /* Create the SMIMESignedGenerator */ SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); ASN1EncodableVector attributes = new ASN1EncodableVector(); attributes.add(new SMIMEEncryptionKeyPreferenceAttribute( new IssuerAndSerialNumber(new X509Name(cert.getIssuerDN().getName()), cert.getSerialNumber())) ); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.setContentTransferEncoding("base64"); signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider(SECURITY_PROVIDER) .setSignedAttributeGenerator(new AttributeTable(attributes)) .build("SHA1withRSA", keyMan.getPrivateKey(), partnershipDVO.getVerifyX509Certificate())); // Add the list of certs to the generator ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); signer.addCertificates(new JcaCertStore(certList)); // Sign body part MimeMultipart mm = signer.generate(bodyPart); InternetHeaders headers = new InternetHeaders(); boolean isContentTypeFolded = new Boolean(System.getProperty("mail.mime.foldtext","true")).booleanValue(); headers.setHeader("Content-Type", isContentTypeFolded? mm.getContentType():mm.getContentType().replaceAll("\\s", " ")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mm.writeTo(baos); MimeBodyPart signedPart = new MimeBodyPart(headers, baos.toByteArray()); return signedPart; }
public void sign(X509Certificate cert, PrivateKey privateKey, String digestAlg) throws SFRMException { try { /* Create the SMIMESignedGenerator */ SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.setContentTransferEncoding("binary"); String signerDigestAlg = ""; if (digestAlg.equalsIgnoreCase(ALG_SIGN_MD5)) signerDigestAlg = "MD5withRSA"; else if (digestAlg.equalsIgnoreCase(ALG_SIGN_SHA1)) signerDigestAlg = "SHA1withRSA"; else throw new SFRMException("Encryption algorihtm error - " + digestAlg); signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder() .setProvider(SECURITY_PROVIDER) .build(signerDigestAlg, privateKey, cert)); /* Add the list of certs to the generator */ ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); // signer.addCertificatesAndCRLs(certs); signer.addCertificates(new JcaCertStore(certList)); /* Sign the body part */ MimeMultipart mm = signer.generate(bodyPart); InternetHeaders headers = new InternetHeaders(); headers.setHeader("Content-Type", mm.getContentType()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mm.writeTo(baos); this.bodyPart = new MimeBodyPart(headers, baos.toByteArray()); this.setIsSigned(true); } catch (org.bouncycastle.mail.smime.SMIMEException ex) { throw new SFRMException("Unable to sign body part", ex.getUnderlyingException()); } catch (Exception e) { throw new SFRMException("Unable to sign body part", e); } }
private String getSMIMECapabilitiesStringValue(byte[] octets) throws IOException { // @formatter:off /* SMIMECapabilities ::= SEQUENCE OF SMIMECapability SMIMECapability ::= SEQUENCE { capabilityID OBJECT IDENTIFIER, parameters ANY DEFINED BY capabilityID OPTIONAL } */ // @formatter:on StringBuilder sb = new StringBuilder(); int capabilityNr = 0; ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(octets); for (ASN1Encodable asn1Encodable : asn1Sequence.toArray()) { SMIMECapability capability = SMIMECapability.getInstance(asn1Encodable); ASN1ObjectIdentifier oid = capability.getCapabilityID(); ASN1Encodable parameters = capability.getParameters(); sb.append(MessageFormat.format(res.getString("SMIMECapability"), ++capabilityNr)); sb.append(NEWLINE); sb.append(INDENT); sb.append(MessageFormat.format(res.getString("SMIMECapability.ObjectID"), ObjectIdUtil.toString(oid))); sb.append(NEWLINE); if (parameters != null) { sb.append(INDENT); sb.append(MessageFormat.format(res.getString("SMIMECapability.Parameter"), HexUtil.getHexString(parameters.toASN1Primitive().getEncoded()))); sb.append(NEWLINE); } } return sb.toString(); }
public TestResult perform() { SMIMECapabilityVector caps = new SMIMECapabilityVector(); caps.addCapability(SMIMECapability.dES_EDE3_CBC); caps.addCapability(SMIMECapability.rC2_CBC, 128); caps.addCapability(SMIMECapability.dES_CBC); SMIMECapabilitiesAttribute attr = new SMIMECapabilitiesAttribute(caps); SMIMEEncryptionKeyPreferenceAttribute pref = new SMIMEEncryptionKeyPreferenceAttribute( new RecipientKeyIdentifier(new DEROctetString(new byte[8]), new DERGeneralizedTime("20070315173729Z"), null)); try { if (!isSameAs(attr.getEncoded(), attrBytes)) { return new SimpleTestResult(false, getName() + ": Failed attr data check"); } ByteArrayInputStream bIn = new ByteArrayInputStream(attrBytes); ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1Primitive o = aIn.readObject(); if (!attr.equals(o)) { return new SimpleTestResult(false, getName() + ": Failed equality test for attr"); } if (!isSameAs(pref.getEncoded(), prefBytes)) { return new SimpleTestResult(false, getName() + ": Failed attr data check"); } bIn = new ByteArrayInputStream(prefBytes); aIn = new ASN1InputStream(bIn); o = aIn.readObject(); if (!pref.equals(o)) { return new SimpleTestResult(false, getName() + ": Failed equality test for pref"); } return new SimpleTestResult(true, getName() + ": Okay"); } catch (Exception e) { return new SimpleTestResult(false, getName() + ": Failed - exception " + e.toString(), e); } }
public void testCompressedSHA1WithRSA() throws Exception { List certList = new ArrayList(); certList.add(origCert); certList.add(signCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); 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); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); SMIMESignedGenerator gen = new SMIMESignedGenerator(); gen.addSigner(origKP.getPrivate(), origCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null); gen.addCertificatesAndCRLs(certs); MimeMultipart smp = gen.generate(msg, "BC"); MimeMessage bp2 = new MimeMessage((Session)null); bp2.setContent(smp); bp2.saveChanges(); SMIMECompressedGenerator cgen = new SMIMECompressedGenerator(); MimeBodyPart cbp = cgen.generate(bp2, SMIMECompressedGenerator.ZLIB); SMIMECompressed cm = new SMIMECompressed(cbp); MimeMultipart mm = (MimeMultipart)SMIMEUtil.toMimeBodyPart(cm.getContent()).getContent(); SMIMESigned s = new SMIMESigned(mm); ByteArrayOutputStream _baos = new ByteArrayOutputStream(); msg.writeTo(_baos); _baos.close(); byte[] _msgBytes = _baos.toByteArray(); _baos = new ByteArrayOutputStream(); s.getContent().writeTo(_baos); _baos.close(); byte[] _resBytes = _baos.toByteArray(); assertEquals(true, Arrays.areEqual(_msgBytes, _resBytes)); certs = s.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getCertificates(selectorConverter.getCertSelector(signer.getSID())); Iterator certIt = certCollection.iterator(); X509Certificate cert = (X509Certificate)certIt.next(); assertEquals(true, signer.verify(cert, "BC")); } }