⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 securityconfig.java

📁 一个用java写的mail.里面的代码值得我们去研究!学习。
💻 JAVA
字号:
/*** $Id: SecurityConfig.java,v 1.4 2001/05/07 12:37:22 kunugi Exp $**** Copyright (c) 2000-2001 Jeff Gay** on behalf of ICEMail.org <http://www.icemail.org>** Copyright (c) 1998-2000 by Timothy Gerard Endres** ** This program is free software.** ** You may redistribute it and/or modify it under the terms of the GNU** General Public License as published by the Free Software Foundation.** Version 2 of the license should be included with this distribution in** the file LICENSE, as well as License.html. If the license is not** included with this distribution, you may find a copy at the FSF web** site at 'www.gnu.org' or 'www.fsf.org', or you may write to the** Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA.**** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR** REDISTRIBUTION OF THIS SOFTWARE. */package org.icemail.mail.smime;import java.io.*;import java.util.*;import java.math.BigInteger;import java.security.PrivateKey;import java.security.cert.CertificateException;import java.security.SignatureException;import java.security.AlgorithmParameters;import java.security.spec.AlgorithmParameterSpec;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.security.InvalidAlgorithmParameterException;import java.security.spec.InvalidParameterSpecException;import javax.crypto.spec.RC2ParameterSpec;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*;import iaik.asn1.ASN1;import iaik.asn1.structures.Name;import iaik.asn1.structures.Attribute;import iaik.asn1.structures.ChoiceOfTime;import iaik.asn1.ASN1Object;import iaik.asn1.DerCoder;import iaik.asn1.ObjectID;import iaik.asn1.CodingException;import iaik.asn1.structures.AlgorithmID;import iaik.pkcs.PKCS7CertList;import iaik.pkcs.PKCSException;import iaik.pkcs.PKCSParsingException;import iaik.pkcs.pkcs7.ContentInfo;import iaik.pkcs.pkcs7.Data;import iaik.pkcs.pkcs7.DigestedData;import iaik.pkcs.pkcs7.EncryptedData;import iaik.pkcs.pkcs7.EnvelopedData;import iaik.pkcs.pkcs7.EncryptedContentInfo;import iaik.pkcs.pkcs7.IssuerAndSerialNumber;import iaik.pkcs.pkcs7.PKCS7Content;import iaik.pkcs.pkcs7.RecipientInfo;import iaik.pkcs.pkcs7.SignedAndEnvelopedData;import iaik.pkcs.pkcs7.SignedData;import iaik.pkcs.pkcs7.SignerInfo;import iaik.pkcs.pkcs12.NetscapeP12;import iaik.pkcs.pkcs12.MicrosoftP12;import java.security.spec.RSAPrivateKeySpec;import javax.crypto.SecretKey;import iaik.x509.X509Certificate;import com.entrust.security.exceptions.EntrustBaseException;import org.icemail.mail.Configuration;import org.icemail.smime.MissingCertificateException;import org.icemail.smime.PasswordCancelException;import org.icemail.util.AWTUtilities;import org.icemail.util.UserProperties;public class SecurityConfig{  private static SecurityConfig config = null;  private Hashtable  idTable = null;  private Hashtable  certTable = null;  public  SecurityConfig() {    this.idTable = new Hashtable();    this.certTable = new Hashtable();  }  //  // CLASS METHODS  //  public static SecurityConfig  getInstance() {    if ( SecurityConfig.config == null )      {      // HACK HACK HACK      // REVIEW      //      // Something about this app is CLOBBERING classes during      // either initialization or execution (Remember, the ICEMail      // class's instance was getting clobbered as well!). Thus,      // to make this work, we had to add this! Shees.      //      com.entrust.util.Util.initCiphers();      SecurityConfig.config = new SecurityConfig();      SecurityConfig.config.initialize();    }    return SecurityConfig.config;  }  public void  initialize() {    try {      this.loadDigitalIDs();      this.loadCertificates();    } catch ( IOException ex ) {      ex.printStackTrace();    }  }  public PrivateKey  locatePrivateKey( IssuerAndSerialNumber iasn )    throws PKCSException, PasswordCancelException {    PrivateKey result = null;    Enumeration enum = this.idTable.elements();    BigInteger serialNum = iasn.getSerialNumber();    for ( ; enum.hasMoreElements() ; ) {      DigitalIDInfo info = (DigitalIDInfo) enum.nextElement();      if ( info != null ) {        X509Certificate idCert = this.getIDCertificate( info.getEmailString() );        if ( idCert != null && serialNum.equals( idCert.getSerialNumber() ) ) {          result = info.getPrivateKey();          break;        }      }    }    return result;  }  public PrivateKey  getPrivateKey( String emailAddr ) throws PKCSException, PasswordCancelException {    PrivateKey key = null;    DigitalIDInfo info = (DigitalIDInfo)this.idTable.get( emailAddr.toLowerCase() );    if ( info != null ) {      key = info.getPrivateKey();    }    return key;  }  public X509Certificate  getIDCertificate( String emailAddr ) throws PKCSException, PasswordCancelException {    X509Certificate result = null;    DigitalIDInfo info = (DigitalIDInfo)this.idTable.get( emailAddr.toLowerCase() );    if ( info != null ) {      X509Certificate[] certs = info.getCertificateChain();      if ( certs != null ) {        result = certs[ certs.length - 1 ];      }    }    return result;  }  public X509Certificate[]  getIDCertificateChain( String emailAddr ) throws PKCSException, PasswordCancelException {    X509Certificate[] certs = null;    DigitalIDInfo info = (DigitalIDInfo)this.idTable.get( emailAddr.toLowerCase() );    if ( info != null ) {      certs = info.getCertificateChain();    }    return certs;  }  public X509Certificate  getRecipientCertificate( String emailAddr ) throws MissingCertificateException {    CertificateInfo info = (CertificateInfo)this.certTable.get( emailAddr.toLowerCase() );    if ( info == null ) {      throw new MissingCertificateException( emailAddr );    }    return info.getEmailCertificate( emailAddr );  }  public X509Certificate[]  getRecipientCertificates( InternetAddress[] recipAddrs ) throws MissingCertificateException {    X509Certificate[] result = new X509Certificate[ recipAddrs.length ];        for ( int i = 0 ; i < recipAddrs.length ; ++i ) {      String emailAddr = recipAddrs[i].getAddress();      CertificateInfo info = (CertificateInfo)this.certTable.get( emailAddr.toLowerCase() );      if ( info == null ) {        throw new MissingCertificateException( emailAddr );      }      result[i] = info.getEmailCertificate( emailAddr );    }    return result;  }  public Hashtable  getIDSTable() {    return this.idTable;  }  public Hashtable  getCertificateTable() {    return this.certTable;  }  public String  getP12EMailAddress( MicrosoftP12 mp12 ) {    // REVIEW - Shouldn't we just walk from the last to the    //          first looking for the first email we meet?    //    X509Certificate certs[] = mp12.getCertificateChain();    X509Certificate sc = certs[ certs.length - 1 ];    Name nm = (Name) sc.getSubjectDN();    String result = nm.getRDN( ObjectID.emailAddress );    return result;  }  public String  getP12EMailAddress( NetscapeP12 np12 ) {    X509Certificate certs[] = np12.getCertificateChain();    X509Certificate sc = certs[ certs.length - 1 ];    Name nm = (Name) sc.getSubjectDN();    String result = nm.getRDN( ObjectID.emailAddress );    return result;  }  public void  saveP12Tables( Hashtable idTbl, Hashtable certTbl )    throws IOException, PKCSException, PasswordCancelException {    this.idTable = (Hashtable) idTbl.clone();    this.saveDigitalIDTable( this.idTable );    this.certTable = (Hashtable) certTbl.clone();    this.saveCertificateTable( this.certTable );  }  // REVIEW I need to get rid of these references to Configuration,  //        but the only way I can see of doing that is moving to  //        the org.icemail.pref package so I can use simple Properties.  public void  saveDigitalIDTable( Hashtable tbl )    throws IOException, PKCSException, PasswordCancelException {    Configuration cfg = Configuration.getInstance();    int cnt = 0;    Enumeration enum = tbl.elements();    for ( ; enum.hasMoreElements() ; ++cnt ) {      DigitalIDInfo info = (DigitalIDInfo) enum.nextElement();      String emailStr = info.getEmailString();      if ( info != null ) {        String base64Str = null;        if ( info.isDecrypted() ) {          try {            info.encrypt();          } catch ( NoSuchAlgorithmException ex ) {            throw new PKCSException( "NoSuchAlgorithmException: " + ex.getMessage() );          }        }        if ( info.isMicrosoftP12() ) {          MicrosoftP12 mp12 = info.getMicrosoftObject();          ByteArrayOutputStream bout = new ByteArrayOutputStream();          mp12.writeTo( bout );          bout.close();          base64Str = com.entrust.util.Util.Base64Encode( bout.toByteArray() );        } else if ( info.isNetscapeP12() ) {          NetscapeP12 np12 = info.getNetscapeObject();          ByteArrayOutputStream bout = new ByteArrayOutputStream();          np12.writeTo( bout );          bout.close();          base64Str = com.entrust.util.Util.Base64Encode( bout.toByteArray() );        }        if ( base64Str != null ) {          cfg.setProperty( "ids.type." + cnt, info.getType() );          cfg.setProperty( "ids.email." + cnt, emailStr );          cfg.setProperty( "ids.base64." + cnt, base64Str );        }      }    }    cfg.setProperty( "ids.length", cnt );  }  public void  saveCertificateTable( Hashtable tbl ) throws IOException, PKCSException {    Configuration cfg = Configuration.getInstance();    int cnt = 0;    Enumeration enum = tbl.elements();    for ( ; enum.hasMoreElements() ; ++cnt ) {      CertificateInfo info = (CertificateInfo) enum.nextElement();      String emailStr = info.getEmailString();      if ( info != null ) {        String base64Str = null;        if ( info.isCertificateChain() ) {          PKCS7CertList pkcs7certs = new PKCS7CertList();          pkcs7certs.setCertificateList( info.getCertificateChain() );          ByteArrayOutputStream bout = new ByteArrayOutputStream();          pkcs7certs.writeTo( bout );          bout.close();          base64Str = com.entrust.util.Util.Base64Encode( bout.toByteArray() );        } else {          X509Certificate cert = info.getCertificate();          ByteArrayOutputStream bout = new ByteArrayOutputStream();          cert.writeTo( bout );          bout.close();          base64Str = com.entrust.util.Util.Base64Encode( bout.toByteArray() );        }        if ( base64Str != null ) {          cfg.setProperty( "certs.ischain." + cnt, info.isCertificateChain() );          cfg.setProperty( "certs.email." + cnt, emailStr );          cfg.setProperty( "certs.base64." + cnt, base64Str );        }      }    }    cfg.setProperty( "certs.length", cnt );  }  public void  saveCertificate( String email, X509Certificate cert )    throws IOException, PKCSException {    CertificateInfo info = new CertificateInfo( email, cert );    this.certTable.put( email.toLowerCase(), info );    this.saveCertificateTable( this.certTable );  }  public void  loadDigitalIDs() throws IOException {    int numIds = UserProperties.getProperty( "ids.length", 0 );    try {      for ( int i = 0 ; i < numIds ; ++i ) {        String email = UserProperties.getProperty( "ids.email." + i, null );        if ( email == null ) {          // UNDONE Report this, it is an error!          continue;        }        String idType = UserProperties.getProperty( "ids.type." + i, null );        String base64 = UserProperties.getProperty( "ids.base64." + i, null );        if ( base64 != null && idType != null ) {          byte[] bytes64 = com.entrust.util.Util.Base64Decode( base64 );          ByteArrayInputStream bin = new ByteArrayInputStream( bytes64 );          if ( idType.equals( "P12" ) ) {            NetscapeP12 np12 = new NetscapeP12( bin );            DigitalIDInfo info = new DigitalIDInfo( email, null, np12 );            this.idTable.put( email.toLowerCase(), info );          } else if ( idType.equals( "PFX" ) ) {            MicrosoftP12 mp12 = new MicrosoftP12( bin );            DigitalIDInfo info = new DigitalIDInfo( email, null, mp12 );            this.idTable.put( email.toLowerCase(), info );          }        }      }    } catch ( EntrustBaseException ex ) {      ex.printStackTrace();      throw new IOException( "PKCSParsingException: " + ex.getMessage() );    } catch ( PKCSParsingException ex ) {      ex.printStackTrace();      throw new IOException( "PKCSParsingException: " + ex.getMessage() );    } catch ( PKCSException ex ) {      ex.printStackTrace();      throw new IOException( "PKCSException: " + ex.getMessage() );    }  }  public void  loadCertificates() throws IOException {    int numCerts = UserProperties.getProperty( "certs.length", 0 );    try {      for ( int i = 0 ; i < numCerts ; ++i ) {        String email = UserProperties.getProperty( "certs.email." + i, null );        if ( email == null ) {          // UNDONE Report this, it is an error!          continue;        }        boolean isChain = UserProperties.getProperty( "certs.ischain." + i, false );        String base64 = UserProperties.getProperty( "certs.base64." + i, null );        if ( base64 != null ) {          byte[] bytes64 = com.entrust.util.Util.Base64Decode( base64 );          ByteArrayInputStream bin = new ByteArrayInputStream( bytes64 );          if ( isChain ) {            PKCS7CertList pkcs7certs = new PKCS7CertList( bin );            CertificateInfo info =              new CertificateInfo( email, pkcs7certs.getCertificateList() );            this.certTable.put( email.toLowerCase(), info );          } else {            try {              X509Certificate cert = new X509Certificate( bin );              CertificateInfo info = new CertificateInfo( email, cert );              this.certTable.put( email.toLowerCase(), info );            } catch ( CertificateException ex ) {              ex.printStackTrace();            }          }        }      }    } catch ( EntrustBaseException ex ) {      ex.printStackTrace();      throw new IOException( "PKCSParsingException: " + ex.getMessage() );    } catch ( PKCSParsingException ex ) {      ex.printStackTrace();      throw new IOException( "PKCSParsingException: " + ex.getMessage() );    } catch ( PKCSException ex ) {      ex.printStackTrace();      throw new IOException( "PKCSException: " + ex.getMessage() );    }  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -