[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: AW: [iaik-jce] verify() a SignedContent createaNullPointerException



At 12:44 20.10.00 +0200, you wrote:
>May you provide whole the source sample (and a stack trace output)?
>
>Regards,
>Dieter Bratko

Thanks for your answer!
Yes I do...

The whole class is:

In the main() function I create a MimeMessage to test the encrypt and
decrypt functions.

class SMIMECryptoMail
{
  /**
  * The Mailcap-File ("mailcap") for the registration of the
DataContentHandler
  * from IAIK-S/MIME.
  */
   public final static String mailcapFileName =
"c:/programme/jbuilder3/myclasses/SMIMEMail/mailcap";

   private String ksFilename = null;
   private String ksPassword = null;
   private String pkPassword = null;

   private KeyStore keyStore = null;

   private X509Certificate myCertificate;
   private PrivateKey myPrivateKey;

   public void SMIMECryptoMail()
   {

   }


   /**
   *  The KeyStore will be initialized.
   *  Before you can encrypt and decrypt a MimeMessage you
   *  must initialize the KeyStore <br><br>
   *
   *  @arg filename The Filename of the KeyStore.
   *  @arg ksPswd The Password wich protects the KeyStore.
   *  @arg pkPswd The Password wich protects the Private Key.
   */
   public void initializeKeyStore(String filename, String ksPswd, String
pkPswd) throws MissingKeyStoreException, MissingPasswordException
   {
     ksFilename = filename;
     ksPassword = ksPswd;
     pkPassword = pkPswd;
     keyStore = null;

         Security.insertProviderAt(new IAIK(), 1);

     try
     {

       MailcapCommandMap mc = new MailcapCommandMap(mailcapFileName);
       CommandMap.setDefaultCommandMap(mc);
     }
     catch(Exception ex)
     {
       System.out.println(ex.getMessage());
     }

     SMimeParameters.useNewContentTypes(true);

     if(!existsKeyStore(ksFilename))
     {
       throw new MissingKeyStoreException("File does not exist!");
     }
     else
     {
       if( ksPassword == null || ksPassword.compareTo("") == 0)
       {
         throw new MissingPasswordException("KeyStore Password is not
set!");
       }
       else
       if(pkPassword == null || pkPassword.compareTo("")==0)
       {
         throw new MissingPasswordException("PrivateKey Password is not
set!");
       }

       try
       {
         keyStore = KeyStore.getInstance("IAIKKeyStore","IAIK");
         keyStore.load(new FileInputStream(ksFilename),
ksPassword.toCharArray());
       }
       catch(Exception ex)
       {
         System.out.println(ex.getMessage());
       }
     }


   }

   private boolean existsKeyStore(String filename)
   {
     String dirKS = null;

     try
     {
       BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));

       // Get the User Directory
       if(dirKS == null || dirKS == "" || dirKS ==" ")
         dirKS = System.getProperty("user.dir");

       File fileKS = new File(dirKS, ksFilename);

       if(fileKS.exists())
       {
         return true;
       }
       else
       {
         return false;
       }
     }
     catch (Exception ex)
     {
       System.out.println(ex.getMessage());
     }

     return false;
   }

   /**
   *  This function sign and encrypt a MIME-Message.<br><br>
   *
   *  @param msg The function expect a MimeMessage.
   *
   *  @return The encrypted MimeMessage is returned.
   */

   public MimeMessage encryptAndSignMessage(MimeMessage msg) throws
MissingKeyStoreException, MessagingException
   {
     X509Certificate customerCerts[];
     X509Certificate[] signerCertChain = new X509Certificate[1];

     boolean multipart = false;

     InternetAddress[] fromWho = (InternetAddress[])msg.getFrom();
     String fromEmail = fromWho[0].toString();

     if(keyStore == null || ksPassword == null || ksPassword.compareTo("")
== 0)
       throw new MissingKeyStoreException("KeyStore not initialized!");
       try
       {
         myPrivateKey = (PrivateKey)keyStore.getKey(fromEmail,
pkPassword.toCharArray());

         Address[] recipientsList = msg.getAllRecipients();
         customerCerts = new X509Certificate[recipientsList.length];
         int le = customerCerts.length;
         int j = 0;
         Object test;



         for(int i=0; i<le;i++)
         {
           System.out.println("- "+recipientsList[i].toString());
           customerCerts[i] =
(X509Certificate)keyStore.getCertificate(recipientsList[i].toString());

           if(customerCerts[i] == null) throw new
KeyStoreException("Unknown Recipient!");
         }

         signerCertChain[0] =
(X509Certificate)keyStore.getCertificate(fromEmail);

         // Sign the Message
         SignedContent sc;

         Object _content = msg.getDataHandler().getContent();

         if(_content instanceof MimeMultipart)
         {
           // MimeMultipart
           sc = new SignedContent(false, SignedContent.SIGNED_DATA);
           MimeMultipart sMultipart = new SMimeMultipart();
           sMultipart = (SMimeMultipart)_content;
           sc.setContent(sMultipart);
           multipart = true;
         }
         else if(_content instanceof String)
         {
           sc = new SignedContent(false);

           MimeMultipart sMultipart = new SMimeMultipart();
           MimeBodyPart mbp = new SMimeBodyPart();

           mbp.setText((String)_content);

           sMultipart.addBodyPart(mbp);

           sc.setContent(sMultipart);
         }
         else
         {
          // kein bekannter ContentTyp
          throw new MessagingException("Unknown Content Type!");
         }

         try
         {
           sc.setCertificates(signerCertChain);
           sc.setSigner((RSAPrivateKey)myPrivateKey,signerCertChain[0]);
         }
         catch (SignatureException ex)
         {
           throw new MessagingException("Creation of signatur failed: " +
ex.getMessage());
         }
         catch (InvalidKeyException ex)
         {
           throw new MessagingException("Private Key Error: " +
ex.getMessage());
         }

         // Encrypt the Message
         EncryptedContent ec = new EncryptedContent(sc);

         for(int i=0;i<customerCerts.length;i++)
         {
           // add the Recipient
           ec.addRecipient(customerCerts[i], AlgorithmID.rsaEncryption);
         }

         // Set the Encryption Algorithm
         AlgorithmID contentEA = AlgorithmID.rc2_CBC;
         ec.setEncryptionAlgorithm(contentEA, 128);

         // the Content of the MimeMessage-Object is a SignedContent-Object:
         msg.setContent(ec, ec.getContentType());

         // Update the Header of the Message
         ec.setHeaders(msg);

       }
       catch(KeyStoreException ex)
       {
         throw new MessagingException("Message not signed and encrypted: "
+ ex.getMessage());
       }
       catch(Exception ex)
       {
         ex.printStackTrace();
       }



     return msg;
   }

   /**
   *  This function decrypt the message
   *
   *
   */

   public MimeMessage decryptMessage(MimeMessage msg) throws IOException,
MissingKeyStoreException
   {
      X509Certificate signer;

     try
     {
       InternetAddress[] fromWho = (InternetAddress[])msg.getFrom();
       String fromEmail = fromWho[0].toString();

       myPrivateKey = (PrivateKey)keyStore.getKey(MyOwnCertificate.EMAIL,
pkPassword.toCharArray());

       EncryptedContent ec = (EncryptedContent)msg.getContent();

       X509Certificate myCertif =
(X509Certificate)keyStore.getCertificate(MyOwnCertificate.EMAIL);
       X509Certificate sendCert =
(X509Certificate)keyStore.getCertificate(fromEmail);

       PublicKey pks = (PublicKey)sendCert.getPublicKey();

       int recipientIndex = ec.getRecipientInfoIndex(myCertif);
       if(recipientIndex == -1)
         throw new Exception("RecipientInfo not found!");


       try
       {
         System.out.println("Decrypt Content-Encryption-Key...");
         ec.decryptSymmetricKey((RSAPrivateKey)myPrivateKey,
recipientIndex);
       }
       catch (InvalidKeyException ex)
       {
         throw new MessagingException("Private Key Error: " +
ex.getMessage());
       }
       catch (SMimeException ex)
       {
         throw new MessagingException("Encrypt Error: " + ex.getMessage());
       }

       SignedContent sc = (SignedContent)ec.getContent();

       MimeMultipart mp = (MimeMultipart)sc.getContent();
       msg.setContent(mp);

       try
       {
         signer = sc.verify();   // I've tried sc.verify(pk) but its the
same exception.
         System.out.println("Signatur o.k. von: "+signer.getSubjectDN());
       }
       catch(SignatureException ex)
       {
         System.out.println("Signatur Error!");
       }


      }
      catch(Exception ex)
      {
         ex.printStackTrace();
      }

     return msg;
     }


   public static void main(String[] args)
   {
     // test

     String from = "sno@odyssey.com";      // Sender
     String to = "sno@hotmail.net"; // Empfänger
     String host = "mail";                     // Name des Mail-Servers
     try
     {

      Properties props = new Properties();
      props.put("mail.smtp.host", host);
      Session session = Session.getDefaultInstance(props, null);

      MimeMessage msg = new MimeMessage(session);

      msg.setFrom(new InternetAddress(from));

      InternetAddress[] recipients = {new InternetAddress(to)};
            msg.setRecipients(Message.RecipientType.TO, recipients);

            msg.setSentDate(new Date());
            // Subject
            msg.setSubject("Nachwuchs");
      msg.setText("Du bist Vater eines gesunden Jungen geworden!");

      SMIMECryptoMail scm = new SMIMECryptoMail();

      scm.initializeKeyStore("smime.keystore","mobilist1","mobilist1");
      try
      {
       msg = scm.encryptAndSignMessage(msg);

       System.out.println("Sende signierte und verschluesselte
Nachricht...");
       Transport.send(msg);

       System.out.println("DEBUG");
       // Decrypten

       scm.initializeKeyStore("smime1.keystore","mobilist1","mobilist1");

       msg = scm.decryptMessage(msg);
       Transport.send(msg);
      }
      catch(MissingKeyStoreException ex)
      {
         ex.printStackTrace();
      }
     }
     catch(Exception ex)
     {
       ex.printStackTrace();
     }

   }
  }


The stack trace output is:

java.lang.NullPointerException
         at iaik.security.smime.SignedContent.verify(Unknown Source)
         at
SMIMEMail.SMIMECryptoMail.decryptMessage(SMIMECryptoMail.java:320)
         at SMIMEMail.SMIMECryptoMail.main(SMIMECryptoMail.java:380)

---

Regards

Sven


--
Mailinglist-archive at
http://jcewww.iaik.at/mailarchive/iaik-jce/jcethreads.html

To unsubscribe send an email to listserv@iaik.at with the folowing content:
UNSUBSCRIBE iaik-jce