📄 sendsignedmail.java
字号:
package cn.edu.scut.smimeapi;
import cn.edu.scut.certmgr.*;
import java.security.*;
import java.security.cert.*;
import java.util.ArrayList;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.IssuerAndSerialNumber;
import org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute;
import org.bouncycastle.asn1.smime.SMIMECapability;
import org.bouncycastle.asn1.smime.SMIMECapabilityVector;
import org.bouncycastle.asn1.smime.SMIMEEncryptionKeyPreferenceAttribute;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.mail.smime.SMIMESignedGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.Enumeration;
/**
* <p>Title: </p>
*log4j.properties
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
*
* @author lyh
* @version 1.0
*/
public class SendSignedMail extends SendMail
{
static
{
/* Add BC */
Security.addProvider(new BouncyCastleProvider());
MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mailcap.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
mailcap.addMailcap("application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
mailcap.addMailcap("application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
mailcap.addMailcap("application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
mailcap.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");
CommandMap.setDefaultCommandMap(mailcap);
}
/**
* Return a MimeMessage which has been Signed by local keystore.
*
* @param cert the X509Certificate to be carried with the message.
* @param privatekey the PrivateKey which to be used to sign the message.
* @param msg the MimeMessage to be signed .
* @return the MimeMessage which has been signed by PrivateKey.
* @throws Exception
*/
public MimeMessage CreateSignedMail(PrivateKey privatekey,X509Certificate cert,MimeMessage msg)
throws Exception
{
if (privatekey == null)
{
throw new Exception("cannot find private key for create a signed mail!");
}
// create some smime capabilities in case someone wants to respond
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 SMIMECapabilitiesAttribute(capabilities));
// add an encryption key preference for encrypted responses -
// normally this would be different from the signing certificate...
attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
new IssuerAndSerialNumber(new X509Name( ( (X509Certificate) cert).
getIssuerDN().getName()),
( (X509Certificate) cert). getSerialNumber())));
// create the generator for creating an smime/signed message
SMIMESignedGenerator signer = new SMIMESignedGenerator();
//
// add a signer to the generator - this specifies we are using SHA1 and
// adding the smime attributes above to the signed attributes that
// will be generated as part of the signature. The encryption algorithm
// used is taken from the key
//
signer.addSigner(privatekey, (X509Certificate) cert,
"DSA".equals(privatekey.getAlgorithm()) ?
SMIMESignedGenerator.DIGEST_SHA1 :
SMIMESignedGenerator.DIGEST_MD5,
new AttributeTable(attributes), null);
/* 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);
//Sign the message
MimeMultipart mm = signer.generate(msg, "BC");
MimeMessage signedMessage = new MimeMessage(session);
/* Set all original MIME headers in the signed message */
Enumeration headers = msg.getAllHeaderLines();
while (headers.hasMoreElements()) {
signedMessage.addHeaderLine( (String) headers.nextElement());
}
/* Set the content of the signed message */
signedMessage.setContent(mm);
signedMessage.saveChanges();
return signedMessage;
}
/**
* Return a MimeMessage which has been Signed by USB_Token .
*
* @param cert the X509Certificate to be carried with the message.
* @param TokenKey the TokenPrivateKey which to be used to sign the message.
* @param msg the MimeMessage to be signed .
* @return the MimeMessage which has been signed by USB_Token PrivateKey.
* @throws Exception
*/
public MimeMessage CreateSignedMailByToken(TokenPrivateKey TokenKey,X509Certificate cert,MimeMessage msg)
throws Exception
{
if (TokenKey == null)
{
throw new Exception("cannot find TokenPrivate key for create a signed mail!");
}
// create some smime capabilities in case someone wants to respond
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 SMIMECapabilitiesAttribute(capabilities));
// add an encryption key preference for encrypted responses -
// normally this would be different from the signing certificate...
attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
new IssuerAndSerialNumber(new X509Name( ( (X509Certificate) cert).
getIssuerDN().getName()),
( (X509Certificate) cert). getSerialNumber())));
// create the generator for creating an smime/signed message
SMIMESignedGenerator signer = new SMIMESignedGenerator();
//
// add a signer to the generator - this specifies we are using SHA1 and
// adding the smime attributes above to the signed attributes that
// will be generated as part of the signature. The encryption algorithm
// used is taken from the key
//
signer.addSigner(TokenKey.getPrivateKey(), (X509Certificate) cert,
"DSA".equals(TokenKey.getPrivateKey().getAlgorithm()) ?
SMIMESignedGenerator.DIGEST_SHA1 :
SMIMESignedGenerator.DIGEST_MD5,
new AttributeTable(attributes), null);
/* 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);
//Sign the message
MimeMultipart mm = signer.generate(msg, TokenKey.getProvider());
MimeMessage signedMessage = new MimeMessage(session);
/* Set all original MIME headers in the signed message */
Enumeration headers = msg.getAllHeaderLines();
while (headers.hasMoreElements()) {
signedMessage.addHeaderLine( (String) headers.nextElement());
}
/* Set the content of the signed message */
signedMessage.setContent(mm);
signedMessage.saveChanges();
return signedMessage;
}
/*
public static void main(String args[])
throws Exception
{
try
{
// create a simple message
SendSignedMail ssm=new SendSignedMail();
ssm.setAccount("smtp.163.com","waitfor_mylove@163.com","198097");
MimeMessage msg=ssm.CreateMail("waitfor_mylove@163.com","waitfor_mylove@163.com","test signed mail By token","hello,i love you!");
// String afile="E:\\test.zip";
// MimeMessage msg=ssm.CreateMailWithAttchment("yhliu@saturn.tanglab.net","yhliu@saturn.tanglab.net","test send mail","hello,world!",afile);
ProviderConfiguration pConfig = new ProviderConfiguration("Config.xml");
//=============epass2000 keystore
// ConfigFileItem configItem = pConfig.getConfigItem(1);
// KeyStoreManager ksMgr = new KeyStoreManager(configItem, "1234".toCharArray());//密码
//===================Local KeyStore
ConfigFileItem configItem = pConfig.getConfigItem(0);
KeyStoreManager ksMgr = new KeyStoreManager(configItem, "tanglab".toCharArray());//密码
KeyStoreCertificates storeCerts = ksMgr.getAllCertificates();
String Certalias=null;
for(int i=0;i<storeCerts.itemCount();i++)
{
if(storeCerts.getCertItem(i).hasPrivateKey())
{
String alias = storeCerts.getCertItem(i).getAlias();
Certalias = alias;
}
}
Certificate cert = ksMgr.getCertificate(Certalias);
Key key=ksMgr.getKey(Certalias,"tanglab".toCharArray());
MimeMessage SignedMessage=ssm.CreateSignedMail((PrivateKey)key,(X509Certificate)cert,msg);
// TokenPrivateKey tpk=ksMgr.getTokenKey(Certalias,null);
// MimeMessage SignedMessage=ssm.CreateSignedMailByToken(tpk,(X509Certificate)cert,msg);
ssm.Send(SignedMessage);
}
catch (Exception ex)
{
System.err.println("发送签名邮件发生异常:"+ex);
}
}
*/
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -