import javax.mail.internet.MimeMultipart; //导入方法依赖的package包/类
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 certList = new ArrayList();
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);
}
}