📄 readencryptedmail.java
字号:
package cn.edu.scut.smimeapi;
import java.io.*;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import javax.mail.internet.*;
import javax.mail.Multipart;
import org.bouncycastle.cms.RecipientId;
import org.bouncycastle.cms.RecipientInformation;
import org.bouncycastle.cms.RecipientInformationStore;
import org.bouncycastle.mail.smime.SMIMEEnveloped;
import org.bouncycastle.mail.smime.SMIMEUtil;
import javax.mail.Message;
import cn.edu.scut.certmgr.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.PrivateKey;
/**
* a class that reads an encrypted email.
*/
public class ReadEncryptedMail extends ReceiveMail
{
/**
* Return a String Cert alias which is to be used to get private key .
*
* @param KeyStoreManager ksm the keyStrore object to manager the key.
* @param RecipientId rid the RecipientId which is relate to the receiver .
* @throws Exception
*/
public String GetCertaliasByRId(KeyStoreManager ksm,RecipientId rid) throws
KeyStoreException,IOException
{
String Certalias=null;
try
{
KeyStoreCertificates ksc = ksm.getAllCertificates();
for(int i=0;i<ksc.itemCount();i++)
{
if(ksc.getCertItem(i).hasPrivateKey())
{
String alias = ksc.getCertItem(i).getAlias();
X509Certificate cert =(X509Certificate) ksm.getCertificate(alias);
if (cert instanceof X509Certificate)
{
if (Arrays.equals(cert.getIssuerX500Principal().getEncoded(),rid.getIssuerAsBytes()))
{
if(cert.getSerialNumber().equals(rid.getSerialNumber()))
{
Certalias=alias;
}
}
}
}
}
}
catch (KeyStoreException ek)
{
throw new KeyStoreException("KeyStoreException:"+ek);
}
catch (IOException ioe)
{
throw new IOException("IOException:"+ioe);
}
return Certalias;
}
/**
* Return a MimeBodyPart which has been descrpted from the EncryptedMsg by usb token .
*
* @param MimeMessage EncryptedMsg, the message which has been Encrypted.
* @param char[] userpin the password which is relate to usb token .
* @throws Exception
*/
public MimeBodyPart ReadEncryptedMailAutoByToken(MimeMessage EncryptedMsg,char[] userpin)
throws Exception
{
if (!EncryptedMsg.isMimeType("application/pkcs7-mime"))
{ //非加密邮件
throw new Exception("It is not a Encrypted message!");
}
MimeBodyPart res=null; //解密后的邮件正文
ProviderConfiguration pConfig = new ProviderConfiguration("Config.xml");
//============= Get private key from epass2000 USB token
ConfigFileItem configItem = pConfig.getConfigItem(1);
KeyStoreManager ksMgr = new KeyStoreManager(configItem, userpin);//密码
SMIMEEnveloped m = new SMIMEEnveloped( (MimeMessage) EncryptedMsg);
RecipientInformationStore recipients = m.getRecipientInfos();
Collection c= recipients.getRecipients();
Iterator it = c.iterator();
//
// check each recipient
//
String Certalias=null;
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
RecipientId recId =recipient.getRID();
try
{
Certalias =GetCertaliasByRId(ksMgr,recId);
}
catch(KeyStoreException ex4)
{
System.err.println("Get Cert's alias error:"+ex4);
throw new KeyStoreException(ex4);
}
try
{
TokenPrivateKey tpk=ksMgr.getTokenKey(Certalias,null);
res = SMIMEUtil.toMimeBodyPart(recipient.getContentByToken(tpk.getPrivateKey(),
tpk.getProvider()));
}
catch (Exception ex3)
{
System.err.println("Decrypetd the mail error:"+ex3);
continue;
}
}
if (res==null)
{
throw new NullPointerException("the mail not decypted success!");
}
return res;
}
/**
* Return a MimeBodyPart which has been descrpted from the EncryptedMsg by LocalKey .
*
* @param MimeMessage EncryptedMsg, the message which has been Encrypted.
* @param char[] userpin the password which is relate to LocalKeyStore .
* @throws Exception
*/
public MimeBodyPart ReadEncryptedMailAutoByLocalKey(MimeMessage EncryptedMsg,char[] userpin)
throws Exception
{
if (!EncryptedMsg.isMimeType("application/pkcs7-mime"))
{ //非加密邮件
throw new Exception("It is not a Encrypted message!");
}
MimeBodyPart res=null; //解密后的邮件正文
ProviderConfiguration pConfig = new ProviderConfiguration("Config.xml");
//============= Get private key from LocalKeyStore
ConfigFileItem configItem = pConfig.getConfigItem(0);
KeyStoreManager ksMgr = new KeyStoreManager(configItem, userpin);//密码
SMIMEEnveloped m = new SMIMEEnveloped( (MimeMessage) EncryptedMsg);
RecipientInformationStore recipients = m.getRecipientInfos();
Collection c= recipients.getRecipients();
Iterator it = c.iterator();
//
// check each recipient
//
String Certalias=null;
while (it.hasNext())
{
RecipientInformation recipient = (RecipientInformation)it.next();
RecipientId recId =recipient.getRID();
try
{
Certalias =GetCertaliasByRId(ksMgr,recId);
}
catch(KeyStoreException ex4)
{
System.err.println("Get Cert's alias error:"+ex4);
}
try
{
Key pkey=ksMgr.getKey(Certalias,userpin);
res = SMIMEUtil.toMimeBodyPart(recipient.getContent(pkey,"BC"));
}
catch (Exception ex3)
{
System.err.println("Decrypetd the mail error:"+ex3);
continue;
}
}
if (res==null)
{
throw new NullPointerException("the mail not decypted success!");
}
return res;
}
/**
* Return a MimeBodyPart which has been descrpted from the EncryptedMsg by Localkey .
*
* @param MimeMessage EncryptedMsg, the message which has been Encrypted.
* @param PrivateKey privatekey, the key which is to be used to descrpted the msg.
* @param X509Certificate cert the certificate to generate a suitable recipient identifier
* @throws Exception
*/
public MimeBodyPart ReadEncryptedMailByLocalkey
(MimeMessage EncryptedMsg,PrivateKey privatekey,X509Certificate cert)
throws Exception
{
// use the certificate to generate a
// suitable recipient identifier
RecipientId recId = new RecipientId();
recId.setSerialNumber(cert.getSerialNumber());
recId.setIssuer(cert.getIssuerX500Principal().getEncoded());
// handle with message
if (!EncryptedMsg.isMimeType("application/pkcs7-mime"))
{ //非加密邮件
throw new Exception("It is not a Encrypte message!");
}
SMIMEEnveloped m = new SMIMEEnveloped( (MimeMessage) EncryptedMsg);
RecipientInformationStore recipients = m.getRecipientInfos();
RecipientInformation recipient = recipients.get(recId);
MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(privatekey,
"BC"));
if (res==null)
{
throw new NullPointerException("the mail not decypted success!");
}
return res;
}
/**
* Return a MimeBodyPart which has been descrpted from the EncryptedMsg by USB_Token .
*
* @param MimeMessage EncryptedMsg, the message which has been Encrypted.
* @param TokenPrivateKey TokenKey, the key which is to be used to descrpted the msg.
* @param X509Certificate cert, the certificate to generate a suitable recipient identifier
* @throws Exception
*/
public MimeBodyPart ReadEncryptedMailByToken
(MimeMessage EncryptedMsg,TokenPrivateKey TokenKey,X509Certificate cert)
throws Exception
{
// use the certificate to generate a
// suitable recipient identifier
RecipientId recId = new RecipientId();
recId.setSerialNumber(cert.getSerialNumber());
recId.setIssuer(cert.getIssuerX500Principal().getEncoded());
// handle with message
if (!EncryptedMsg.isMimeType("application/pkcs7-mime"))
{ //非加密邮件
throw new Exception("It is not a Encrypte message!");
}
SMIMEEnveloped m = new SMIMEEnveloped( (MimeMessage) EncryptedMsg);
RecipientInformationStore recipients = m.getRecipientInfos();
RecipientInformation recipient = recipients.get(recId);
MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContentByToken(TokenKey.getPrivateKey(),
TokenKey.getProvider()));
if (res==null)
{
throw new NullPointerException("the mail not decypted success!");
}
return res;
}
/*
public static void main(String args[])
throws Exception
{
//receive mail from the pop3 host
try
{
MimeBodyPart body=null;
ReadEncryptedMail recmail=new ReadEncryptedMail();
Message[] msg = recmail.getMail("202.38.212.1", "yhliu", "yhliu");
System.out.println("您好,共收到"+msg.length+"封邮件");
ProviderConfiguration pConfig = new ProviderConfiguration("Config.xml");
//=============epass2000
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;
}
}
X509Certificate cert =(X509Certificate) ksMgr.getCertificate(Certalias);
PrivateKey prikey=(PrivateKey)ksMgr.getKey(Certalias,"tanglab".toCharArray());
//TokenPrivateKey tpk=ksMgr.getTokenKey(Certalias,null);
// handle with message
for (int i = 0; i <msg.length; i++)//msg.length
{
try
{
if (msg[i].isMimeType("application/pkcs7-mime"))
{ //加密邮件
System.out.println("您好,这是一封加密邮件");
// recmail.ReadEncryptedMailAutoByToken( (MimeMessage) msg[i],"1234".toCharArray());
// recmail.ReadEncryptedMailByToken( (MimeMessage) msg[i],tpk, cert);
body=recmail.ReadEncryptedMailByLocalkey((MimeMessage) msg[i],prikey,cert);
Object cont = body.getContent();
System.out.println("邮件内容如下:");
if (cont instanceof String)
{
System.out.println((String) cont);
}
else if (cont instanceof Multipart)
{
Multipart mp = (Multipart) cont;
System.out.println(recmail.handleMultipart(mp));
}
}
else
{
System.out.println("It is not an encrpted mail");
}
System.out.println("-----------------------------------------");
}
catch (Exception ex)
{
System.err.println("邮件无法解密,可能数字证书不正确!"+ex);
}
}
}
catch (Exception ex)
{
System.err.println("收取加密邮件发生异常:"+ex);
}
}
*/
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -