Picon

Getting an error when the readObject method from ASN1InputStream class is called J2ME

Could anybody help me, please?

 

De: Vázquez Rodríguez Gabriel
Enviado el: martes, 03 de julio de 2012 12:14 p.m.
Para: 'dev-crypto-request-TtFiPYkqHGexCSWobqctBA@public.gmane.org'
Asunto: Getting an error when the readObject method from ASN1InputStream class is called

 

Hello guys,

 

I am trying to include the BouncyCastle API into my J2ME project using NetBeans. However, I have had some trouble. First, I could not compile the application using NetBeans because the .jad file was so large. In this case, I read a post where a developer changed the obfuscation level in the project properties section. The application compiled, but, unfortunately, I got a rare message when the application was executed. The error message says:

 

 

TRACE: <at java.lang.NullPointerException:   0>, Exception caught in Display class

java.lang.NullPointerException:   0

       at hello.HelloMIDlet.testDataFieldMidlet(), bci=9

       at hello.HelloMIDlet.commandAction(), bci=60

       at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46

       at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74

       at com.sun.midp.chameleon.layers.SoftButtonLayer.soft2(), bci=173

       at com.sun.midp.chameleon.layers.SoftButtonLayer.keyInput(), bci=78

       at com.sun.midp.chameleon.CWindow.keyInput(), bci=38

       at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handleKeyEvent(), bci=17

       at com.sun.midp.lcdui.DisplayEventListener.process(), bci=277

       at com.sun.midp.events.EventQueue.run(), bci=179

       at java.lang.Thread.run(Thread.java:680)

 

1300058432 - CORE - ERROR - 1 - Unknown event.

 

 

Tracing the error, I found the application crashed when the readObject method from ASN1InputStream class is called.

Now, I am stuck. I have read some posts, but I cannot fix the problem. Therefore, I am wondering if you could help me with this problematic.

Perhaps my project configuration is wrong, I do not know. Could you recommend or suggest me some ideas?

 

Thanks in advance, I look forward to your reply.

Best regards,

Gabriel…

 

 

P.S. I include a piece of my source code.

 

 

public PublicKey() throws IOException {

 

    byte[]certificate = Base64.decode(

        "MIIC7jCCAnigAwIBAgIJAJJM3dvU1CwxMA0GCSqGSIb3DQEBBQUAMIGOMQswCQYD"

        + "VQQGEwJNWDENMAsGA1UECAwERC5GLjEZMBcGA1UEBwwQQ2l1ZGFkIGRlIE1leGlj"

        + "bzEYMBYGA1UECgwPQmFuY28gZGUgTWV4aWNvMQ0wCwYDVQQLDAREU09QMRUwEwYD"

        + "VQQDDAxub21icmUgY29tdW4xFTATBgkqhkiG9w0BCQIMBnZhcmlvczAeFw0xMDA1"

        + "MjQyMTQxMDRaFw0xMzAyMTcyMTQxMDRaMIGOMQswCQYDVQQGEwJNWDENMAsGA1UE"

        + "CAwERC5GLjEZMBcGA1UEBwwQQ2l1ZGFkIGRlIE1leGljbzEYMBYGA1UECgwPQmFu"

        + "Y28gZGUgTWV4aWNvMQ0wCwYDVQQLDAREU09QMRUwEwYDVQQDDAxub21icmUgY29t"

        + "dW4xFTATBgkqhkiG9w0BCQIMBnZhcmlvczCBoTANBgkqhkiG9w0BAQEFAAOBjwAw"

        + "gYsCgYMKrIH3TzKPnmh/4gDbA6UNJizEzhTli+lDCG/l9zbMUUGWcLcb8GCnfLsM"

        + "4w4n5u+cxNULDZjiQv4Lcfbbn3/eJp/Azdn+zbvnIUcvea8IGuMWYZdzcy/mM1fn"

        + "59XHYwuxhMo4u879Pps97TkPpG8DLUqBvhDqhZMQEYM/zgQdMO2gnwIDAQABo3Ew"

        + "bzAdBgNVHQ4EFgQUF+c2UXJ8wMkzRKsxA2D0SZ5UzQkwDwYDVR0TBAgwBgEB/wIB"

        + "ATALBgNVHQ8EBAMCAeYwEQYJYIZIAYb4QgEBBAQDAgEGMB0GA1UdEQQWMBSBEmRp"

        + "ckBkZS5taWVudHJhcy5laDANBgkqhkiG9w0BAQUFAANhALj4HxxISuLsC2Wz2q5M"

        + "7Hf3k0LKoqzYFaZvYp1RsUteC7u5MlclH2zVmuCE2vGFk5qmq3aGASmksYqVtkYp"

        + "4mL9pu3xOpN3ilQsoEr0f1pLh7B1xxbL5lbZ9MGlbwjwgQ=="

    );

 

    ByteArrayInputStream bIn = new ByteArrayInputStream(certificate);

    ASN1InputStream      aIn = new ASN1InputStream(bIn);

    ASN1Sequence         seq = (ASN1Sequence) aIn.readObject();  // Here crashes =(

 

    this.certificate         = Certificate.getInstance(seq);

    ASN1Primitive  primitive = this.certificate.getSubjectPublicKeyInfo().parsePublicKey();

    this.key                 = RSAPublicKey.getInstance(primitive);

 

    aIn.close();

    bIn.close();

}



ADVERTENCIA. Este correo se envía del Banco de México y puede contener información confidencial o reservada, si usted no es el destinatario del mismo, por favor notifique al remitente inmediatamente y borre este mensaje y cualquier copia del mismo, así como los archivos adjuntos. Debido a que las comunicaciones por internet no son seguras, en el caso de que usted no sea el destinatario de este correo, Banco de México no acepta responsabilidad u obligación alguna por el contenido del mismo. La información de este mensaje, incluyendo, en su caso, los archivos adjuntos, se encuentra protegida por la ley. Su reproducción, parcial o total, revisión, uso, revelación, y/o distribución indebida o no autorizada puede constituir un delito y/o contravenir diversas disposiciones legales. Con independencia de lo anterior, el Banco de México se reserva el derecho de ejercer las acciones que correspondan, entre otros, por daños y perjuicios, con motivo del empleo indebido y/o no autorizado de la propia información. Banco de México, ha tomado precauciones para prevenir que el presente correo no esté infectado por virus, por lo que no acepta, entre otros, responsabilidad alguna por daños o pérdidas causadas por el uso del mismo o de los archivos adjuntos.


°°°°
NOTICE. This message is being sent from Banco de México and may contain confidential or privileged information, if you are not the intended recipient, please advise the sender immediately and delete this message, and any copies of it, including its attachments. As internet communications are not secure, in case you are not the intended receiver, Banco de México does not accept any responsibility for the content of this message. All information contained in this message, including attached files, is protected by Mexican law. Partial or total reproduction, modification, use, disclosure, and/or inappropriate or unauthorized distribution of any information without the prior consent of the sender may be prosecuted under Mexican law. Banco de México reserves the right to pursue in any form of legal action, including any damages, that could result from the inappropriate or unauthorized use of the information contained herein. Banco de México has taken reasonable precautions to prevent viruses from being present in this e-mail. We do not accept responsibility for any loss or damages arising from the use of this e-mail or its attachments. °°°°
Smith, Bill (Tridium | 3 Jul 22:22 2012

ASN1Object Parsing Question

When parsing an ASN1Object and you get back an octet string, is there a way to know when to stop recursing into
it? I've found when parsing things like the Subject Alternative Name extension, sometimes it stops when
it gets to the id, other times it goes deeper and returns something like a DERApplicationSpecific object.
I suspect that the leading bytes are invalid (this causing it to stop at the id) or match another object type
(in this case a DERApplicationSpecific object).

The code in ASN1Dump, always stops at the top octet string. Using something like
(http://lapo.it/asn1js/) seems to stop at the appropriate point. I've included my sample code as well.

import java.io.FileReader;
import java.io.IOException;
import java.security.Security;
import java.security.cert.CertificateEncodingException;
import java.util.Enumeration;

import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1GeneralizedTime;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.ASN1String;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.ASN1UTCTime;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.jce.provider.X509CertificateObject;
import org.bouncycastle.openssl.PEMReader;

public class ASN1Decoder
{

  /**
   *  <at> param args
   *  <at> throws Exception 
   */
  public static void main(String[] args) 
    throws Exception
  {
    if (args.length < 1)
    {
      usage();
      return;
    }

    for (int i = 0; i < args.length; i++)
    {
      ASN1Decoder.dump(args[i]);
    }
  }

  public static void usage()
  {
    System.err.println("Usage: java ASN1Decoder <pemfile>");
  }

  public static void dump(String path) throws IOException, CertificateEncodingException
  {
    ASN1Object asn1 = null;

    PEMReader reader = new PEMReader(new FileReader(path));
    Object obj = reader.readObject();

    if (obj instanceof X509CertificateObject)
    {
      byte[] encoded = ((X509CertificateObject) obj).getEncoded();
      asn1 = ASN1Primitive.fromByteArray(encoded);
    }

    if (asn1 != null)
      //System.err.println(ASN1Dump.dumpAsString(asn1, true));
      dump(asn1);
  }

  private static void dump(ASN1Object obj)
  {
    StringBuffer buf = new StringBuffer();
    dump(obj, buf, 0);
    System.err.println(buf.toString());
  }

  private static void dump(ASN1Object obj, StringBuffer buf, int depth)  
  {
    indent(buf, depth);
    if (obj == null)
    {
      buf.append("Null").append(NL);
    }
    else if (obj instanceof DERBitString)
    {
      buf.append("DERBitString : ").append(((DERBitString)obj).getBytes().length * 8).append(" bits").append(NL);
    }
    else if (obj instanceof ASN1String)
    {
      buf.append("ASN1String : ").append(((ASN1String)obj).getString()).append(NL);
    }
    else if (obj instanceof ASN1UTCTime)
    {
      buf.append("ASN1UTCTime : ").append(((ASN1UTCTime)obj).getTime()).append(NL);
    }
    else if (obj instanceof ASN1GeneralizedTime)
    {
      buf.append("ASN1GeneralizedTime : ").append(((ASN1GeneralizedTime)obj).getTime()).append(NL);
    }
    else if (obj instanceof ASN1ObjectIdentifier)
    {
      buf.append("ASN1ObjectIdentifier : ").append(OidMap.get(((ASN1ObjectIdentifier)obj).getId())).append(NL);
    }
    else if (obj instanceof ASN1Integer)
    {
      buf.append("ASN1Integer : ").append(((ASN1Integer)obj).getValue().toString()).append(NL);
    }
    else if (obj instanceof ASN1Boolean)
    {
      buf.append("ASN1Boolean : ").append(((ASN1Boolean)obj).isTrue() ? "true" : "false").append(NL);
    }
    else if (obj instanceof ASN1OctetString)
    {
      buf.append("ASN1OctetString").append(NL);
      ASN1OctetString octObj = (ASN1OctetString)obj;
      try
      {
        ASN1InputStream aIn = new ASN1InputStream(octObj.getOctetStream());
        ASN1Primitive dobj = aIn.readObject();
        dump(dobj, buf, depth + 1);
      }
      catch(Exception e)
      {
        indent(buf, depth + 1);
        buf.append(ByteArrayUtil.toHexString(octObj.getOctets(), ":")).append(NL);
      }
    }
    else if (obj instanceof ASN1TaggedObject)
    {
      buf.append("ASN1TaggedObject").append(NL);
      dump(((ASN1TaggedObject)obj).getObject(), buf, depth + 1);
    }
    else if (obj instanceof ASN1Sequence)
    {
      buf.append("ASN1Sequence").append(NL);

      Enumeration objs = ((ASN1Sequence)obj).getObjects();
      while (objs.hasMoreElements())
      {
        Object o = objs.nextElement();
        if (o == null || o instanceof DERNull)
        {
          indent(buf, depth + 1);
          buf.append("DERNull").append(NL);
        }
        else if (o instanceof ASN1Primitive)
        {
          dump((ASN1Primitive)o, buf, depth + 1);
        }
        else
        {
          dump(((ASN1Encodable)o).toASN1Primitive(), buf, depth + 1);
        }
      }
    }
    else if (obj instanceof ASN1Set)
    {
      buf.append("ASN1Set").append(NL);

      Enumeration objs = ((ASN1Set)obj).getObjects();
      while (objs.hasMoreElements())
      {
        Object o = objs.nextElement();
        if (o == null || o instanceof DERNull)
        {
          indent(buf, depth + 1);
          buf.append(NL);
        }
        else if (o instanceof ASN1Primitive)
        {
          dump((ASN1Primitive)o, buf, depth + 1);
        }
        else
        {
          dump(((ASN1Encodable)o).toASN1Primitive(), buf, depth + 1);
        }
      }
    }
    else
    {
      buf.append(obj.getClass().getName()).append(NL);
    }      
  }

  private static void indent(StringBuffer buf, int depth)
  {
    for (int i = 0; i < depth; i++)
      buf.append("  ");
  }

  private static String NL = "\n";
  static
  {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  }
}

Regards, 
Bill

------------------------------------------
Bill Smith
Tridium, Inc.

Sidney Markowitz | 4 Jul 07:12 2012

Is XTS-AES mode implemented?

Looking for a Java implementation of XTS-AES mode (as used in IEEE P1619), I
found reference to it being in Bouncycastle, but searching the doc and the
source code indicates the person who posted that was mistaken.

All I found in a search of the dev-bouncycastle mailing list archives was a
three year old request to have it done which never got a reply.

http://bouncy-castle.1462172.n4.nabble.com/Feature-request-modern-modes-of-operation-tp1463793.html

Am I not noticing some Java implementation, or some way to get XTS mode in
Bouncycastle by combining already existing facilities?

Is there a reason why nobody has seemed interested in doing it that would
indicate that I should just not bother with it?

Would there be interest in the code if I contributed an implementation?

What I'm considering it for is to encrypt a file that is meant to be read
using random access to blocks. XTS-AES mode is supposed to be the best mode
for full disk encryption. If I understand it correctly, random block access to
a file would have the same security properties. Does anyone have a contrary
view of it?

Thanks,

Sidney Markowitz
http://www.sidney.com

Lamchith M C | 5 Jul 11:45 2012
Picon

Blackberry using J2ME distribution

Hi,

I have been trying to use J2ME distribution of bouncycastle  to Creates a signed CMS message. Classes like JcaContentSignerBuilder are not available under the J2ME distribution. So i believe i have use bcpkix-jdk11-147.zip. But then the blackberry java will not have the corresponding java.security classes. So is possible to achieve it only using J2ME distribution of bouncycastle. Am i missing something. Please provide some help.

--

Regards,
Lamchith

Fabrizio Gulino | 5 Jul 12:41 2012

Cryptographic message syntax (CMS) and light-weight api

Hi,
I have to implement the Cryptographic message syntax (CMS) management 
using only the light-weight api because we don't want to ask to our 
users to download the unrestricted policy files for the Sun JCE.

For instance what I've to do is the same I've done using the provider:
  public byte[] createAttoEncoded(byte[] bout, Certificate cert) throws 
Exception {
         byte[] encoded = null;

         try {
            Security.addProvider(new 
org.bouncycastle.jce.provider.BouncyCastleProvider());

             CMSEnvelopedDataGenerator gen = new 
CMSEnvelopedDataGenerator();
             gen.addKeyTransRecipient((X509Certificate) cert);  
//gen.addRecipientInfoGenerator(new 
BcRSAKeyTransRecipientInfoGenerator(new 
X509CertificateHolder(cert.getEncoded())));

             CMSProcessableByteArray processable = new 
CMSProcessableByteArray(bout);
             CMSEnvelopedData envData = gen.generate(processable, 
CMSEnvelopedDataGenerator.DES_EDE3_CBC, "BC");
             encoded = envData.getEncoded();
             return encoded;
         } catch (Exception e) {
             throw e;
         }
     }

Is there someone that could tell me where I can find some examples or 
specific documentation?
Now I'm trying to understand the source code of the class 
CMSEnvelopedDataGenerator but I would like to know if there is a better 
start point.

Many thanks to all

--

-- 
Fabrizio Gulino
Email assistenza: assistenza@...
Email personale:  fabrizio@...

Progetto Archivio S.r.l
www.progettoarchivio.it
P.I. 08901040017
Tel +39.121.30.35.44
Mob +39.328.29.70.842
Fax +39.121.30.35.45
Via F.G. Bona n.75
10064 Pinerolo (TO)

Smith, Bill (Tridium | 5 Jul 18:05 2012

RE: ASN1Object Parsing Question

I dug into this quite a bit this morning. Here is what I've found out:

In the case of the javascript decoder below, in addition to grabbing the next byte in an octet string as the
tag, it also grabs the second byte as the length and validates that it matches the parent length (+ 2).
Obviously this could still be fooled. I guess the real answer is knowing the context of the data you're
parsing based on the oid as you are parsing it, and treating everything else (at least in the case of octet
strings) as just octet strings and not breaking them down more.

Does this seem like a reasonable assessment?

Bill

> -----Original Message-----
> From: Smith, Bill (Tridium)
> Sent: Tuesday, July 03, 2012 4:23 PM
> To: dev-crypto@...
> Subject: [dev-crypto] ASN1Object Parsing Question
> 
> When parsing an ASN1Object and you get back an octet string, is there a
> way to know when to stop recursing into it? I've found when parsing
> things like the Subject Alternative Name extension, sometimes it stops
> when it gets to the id, other times it goes deeper and returns something
> like a DERApplicationSpecific object. I suspect that the leading bytes
> are invalid (this causing it to stop at the id) or match another object
> type (in this case a DERApplicationSpecific object).
> 
> The code in ASN1Dump, always stops at the top octet string. Using
> something like (http://lapo.it/asn1js/) seems to stop at the appropriate
> point. I've included my sample code as well.
> 
> 
> import java.io.FileReader;
> import java.io.IOException;
> import java.security.Security;
> import java.security.cert.CertificateEncodingException;
> import java.util.Enumeration;
> 
> import org.bouncycastle.asn1.ASN1Boolean;
> import org.bouncycastle.asn1.ASN1Encodable;
> import org.bouncycastle.asn1.ASN1GeneralizedTime;
> import org.bouncycastle.asn1.ASN1InputStream;
> import org.bouncycastle.asn1.ASN1Integer;
> import org.bouncycastle.asn1.ASN1Object;
> import org.bouncycastle.asn1.ASN1ObjectIdentifier;
> import org.bouncycastle.asn1.ASN1OctetString;
> import org.bouncycastle.asn1.ASN1Primitive;
> import org.bouncycastle.asn1.ASN1Sequence;
> import org.bouncycastle.asn1.ASN1Set;
> import org.bouncycastle.asn1.ASN1String;
> import org.bouncycastle.asn1.ASN1TaggedObject;
> import org.bouncycastle.asn1.ASN1UTCTime;
> import org.bouncycastle.asn1.DERBitString;
> import org.bouncycastle.asn1.DERNull;
> import org.bouncycastle.jce.provider.X509CertificateObject;
> import org.bouncycastle.openssl.PEMReader;
> 
> public class ASN1Decoder
> {
> 
>   /**
>    *  <at> param args
>    *  <at> throws Exception
>    */
>   public static void main(String[] args)
>     throws Exception
>   {
>     if (args.length < 1)
>     {
>       usage();
>       return;
>     }
> 
>     for (int i = 0; i < args.length; i++)
>     {
>       ASN1Decoder.dump(args[i]);
>     }
>   }
> 
>   public static void usage()
>   {
>     System.err.println("Usage: java ASN1Decoder <pemfile>");
>   }
> 
>   public static void dump(String path) throws IOException,
> CertificateEncodingException
>   {
>     ASN1Object asn1 = null;
> 
>     PEMReader reader = new PEMReader(new FileReader(path));
>     Object obj = reader.readObject();
> 
>     if (obj instanceof X509CertificateObject)
>     {
>       byte[] encoded = ((X509CertificateObject) obj).getEncoded();
>       asn1 = ASN1Primitive.fromByteArray(encoded);
>     }
> 
>     if (asn1 != null)
>       //System.err.println(ASN1Dump.dumpAsString(asn1, true));
>       dump(asn1);
>   }
> 
>   private static void dump(ASN1Object obj)
>   {
>     StringBuffer buf = new StringBuffer();
>     dump(obj, buf, 0);
>     System.err.println(buf.toString());
>   }
> 
>   private static void dump(ASN1Object obj, StringBuffer buf, int depth)
>   {
>     indent(buf, depth);
>     if (obj == null)
>     {
>       buf.append("Null").append(NL);
>     }
>     else if (obj instanceof DERBitString)
>     {
>       buf.append("DERBitString :
> ").append(((DERBitString)obj).getBytes().length * 8).append("
> bits").append(NL);
>     }
>     else if (obj instanceof ASN1String)
>     {
>       buf.append("ASN1String :
> ").append(((ASN1String)obj).getString()).append(NL);
>     }
>     else if (obj instanceof ASN1UTCTime)
>     {
>       buf.append("ASN1UTCTime :
> ").append(((ASN1UTCTime)obj).getTime()).append(NL);
>     }
>     else if (obj instanceof ASN1GeneralizedTime)
>     {
>       buf.append("ASN1GeneralizedTime :
> ").append(((ASN1GeneralizedTime)obj).getTime()).append(NL);
>     }
>     else if (obj instanceof ASN1ObjectIdentifier)
>     {
>       buf.append("ASN1ObjectIdentifier :
> ").append(OidMap.get(((ASN1ObjectIdentifier)obj).getId())).append(NL);
>     }
>     else if (obj instanceof ASN1Integer)
>     {
>       buf.append("ASN1Integer :
> ").append(((ASN1Integer)obj).getValue().toString()).append(NL);
>     }
>     else if (obj instanceof ASN1Boolean)
>     {
>       buf.append("ASN1Boolean : ").append(((ASN1Boolean)obj).isTrue() ?
> "true" : "false").append(NL);
>     }
>     else if (obj instanceof ASN1OctetString)
>     {
>       buf.append("ASN1OctetString").append(NL);
>       ASN1OctetString octObj = (ASN1OctetString)obj;
>       try
>       {
>         ASN1InputStream aIn = new
> ASN1InputStream(octObj.getOctetStream());
>         ASN1Primitive dobj = aIn.readObject();
>         dump(dobj, buf, depth + 1);
>       }
>       catch(Exception e)
>       {
>         indent(buf, depth + 1);
>         buf.append(ByteArrayUtil.toHexString(octObj.getOctets(),
> ":")).append(NL);
>       }
>     }
>     else if (obj instanceof ASN1TaggedObject)
>     {
>       buf.append("ASN1TaggedObject").append(NL);
>       dump(((ASN1TaggedObject)obj).getObject(), buf, depth + 1);
>     }
>     else if (obj instanceof ASN1Sequence)
>     {
>       buf.append("ASN1Sequence").append(NL);
> 
>       Enumeration objs = ((ASN1Sequence)obj).getObjects();
>       while (objs.hasMoreElements())
>       {
>         Object o = objs.nextElement();
>         if (o == null || o instanceof DERNull)
>         {
>           indent(buf, depth + 1);
>           buf.append("DERNull").append(NL);
>         }
>         else if (o instanceof ASN1Primitive)
>         {
>           dump((ASN1Primitive)o, buf, depth + 1);
>         }
>         else
>         {
>           dump(((ASN1Encodable)o).toASN1Primitive(), buf, depth + 1);
>         }
>       }
>     }
>     else if (obj instanceof ASN1Set)
>     {
>       buf.append("ASN1Set").append(NL);
> 
>       Enumeration objs = ((ASN1Set)obj).getObjects();
>       while (objs.hasMoreElements())
>       {
>         Object o = objs.nextElement();
>         if (o == null || o instanceof DERNull)
>         {
>           indent(buf, depth + 1);
>           buf.append(NL);
>         }
>         else if (o instanceof ASN1Primitive)
>         {
>           dump((ASN1Primitive)o, buf, depth + 1);
>         }
>         else
>         {
>           dump(((ASN1Encodable)o).toASN1Primitive(), buf, depth + 1);
>         }
>       }
>     }
>     else
>     {
>       buf.append(obj.getClass().getName()).append(NL);
>     }
>   }
> 
>   private static void indent(StringBuffer buf, int depth)
>   {
>     for (int i = 0; i < depth; i++)
>       buf.append("  ");
>   }
> 
>   private static String NL = "\n";
>   static
>   {
>     Security.addProvider(new
> org.bouncycastle.jce.provider.BouncyCastleProvider());
>   }
> }
> 
> Regards,
> Bill
> 
> ------------------------------------------
> Bill Smith
> Tridium, Inc.

David Hook | 6 Jul 00:49 2012

Re: RE: ASN1Object Parsing Question


Yep. ASN.1 features like implicit tagging saves a few bytes, but makes 
it almost impossible to work out what's actually in a stream unless you 
have a clear idea of the context.

Regards,

David

On 06/07/12 02:05, Smith, Bill (Tridium) wrote:
> I dug into this quite a bit this morning. Here is what I've found out:
>
> In the case of the javascript decoder below, in addition to grabbing the next byte in an octet string as the
tag, it also grabs the second byte as the length and validates that it matches the parent length (+ 2).
Obviously this could still be fooled. I guess the real answer is knowing the context of the data you're
parsing based on the oid as you are parsing it, and treating everything else (at least in the case of octet
strings) as just octet strings and not breaking them down more.
>
> Does this seem like a reasonable assessment?
>
> Bill
>
>> -----Original Message-----
>> From: Smith, Bill (Tridium)
>> Sent: Tuesday, July 03, 2012 4:23 PM
>> To: dev-crypto@...
>> Subject: [dev-crypto] ASN1Object Parsing Question
>>
>> When parsing an ASN1Object and you get back an octet string, is there a
>> way to know when to stop recursing into it? I've found when parsing
>> things like the Subject Alternative Name extension, sometimes it stops
>> when it gets to the id, other times it goes deeper and returns something
>> like a DERApplicationSpecific object. I suspect that the leading bytes
>> are invalid (this causing it to stop at the id) or match another object
>> type (in this case a DERApplicationSpecific object).
>>
>> The code in ASN1Dump, always stops at the top octet string. Using
>> something like (http://lapo.it/asn1js/) seems to stop at the appropriate
>> point. I've included my sample code as well.
>>
>>
>> import java.io.FileReader;
>> import java.io.IOException;
>> import java.security.Security;
>> import java.security.cert.CertificateEncodingException;
>> import java.util.Enumeration;
>>
>> import org.bouncycastle.asn1.ASN1Boolean;
>> import org.bouncycastle.asn1.ASN1Encodable;
>> import org.bouncycastle.asn1.ASN1GeneralizedTime;
>> import org.bouncycastle.asn1.ASN1InputStream;
>> import org.bouncycastle.asn1.ASN1Integer;
>> import org.bouncycastle.asn1.ASN1Object;
>> import org.bouncycastle.asn1.ASN1ObjectIdentifier;
>> import org.bouncycastle.asn1.ASN1OctetString;
>> import org.bouncycastle.asn1.ASN1Primitive;
>> import org.bouncycastle.asn1.ASN1Sequence;
>> import org.bouncycastle.asn1.ASN1Set;
>> import org.bouncycastle.asn1.ASN1String;
>> import org.bouncycastle.asn1.ASN1TaggedObject;
>> import org.bouncycastle.asn1.ASN1UTCTime;
>> import org.bouncycastle.asn1.DERBitString;
>> import org.bouncycastle.asn1.DERNull;
>> import org.bouncycastle.jce.provider.X509CertificateObject;
>> import org.bouncycastle.openssl.PEMReader;
>>
>> public class ASN1Decoder
>> {
>>
>>    /**
>>     *  <at> param args
>>     *  <at> throws Exception
>>     */
>>    public static void main(String[] args)
>>      throws Exception
>>    {
>>      if (args.length < 1)
>>      {
>>        usage();
>>        return;
>>      }
>>
>>      for (int i = 0; i < args.length; i++)
>>      {
>>        ASN1Decoder.dump(args[i]);
>>      }
>>    }
>>
>>    public static void usage()
>>    {
>>      System.err.println("Usage: java ASN1Decoder <pemfile>");
>>    }
>>
>>    public static void dump(String path) throws IOException,
>> CertificateEncodingException
>>    {
>>      ASN1Object asn1 = null;
>>
>>      PEMReader reader = new PEMReader(new FileReader(path));
>>      Object obj = reader.readObject();
>>
>>      if (obj instanceof X509CertificateObject)
>>      {
>>        byte[] encoded = ((X509CertificateObject) obj).getEncoded();
>>        asn1 = ASN1Primitive.fromByteArray(encoded);
>>      }
>>
>>      if (asn1 != null)
>>        //System.err.println(ASN1Dump.dumpAsString(asn1, true));
>>        dump(asn1);
>>    }
>>
>>    private static void dump(ASN1Object obj)
>>    {
>>      StringBuffer buf = new StringBuffer();
>>      dump(obj, buf, 0);
>>      System.err.println(buf.toString());
>>    }
>>
>>    private static void dump(ASN1Object obj, StringBuffer buf, int depth)
>>    {
>>      indent(buf, depth);
>>      if (obj == null)
>>      {
>>        buf.append("Null").append(NL);
>>      }
>>      else if (obj instanceof DERBitString)
>>      {
>>        buf.append("DERBitString :
>> ").append(((DERBitString)obj).getBytes().length * 8).append("
>> bits").append(NL);
>>      }
>>      else if (obj instanceof ASN1String)
>>      {
>>        buf.append("ASN1String :
>> ").append(((ASN1String)obj).getString()).append(NL);
>>      }
>>      else if (obj instanceof ASN1UTCTime)
>>      {
>>        buf.append("ASN1UTCTime :
>> ").append(((ASN1UTCTime)obj).getTime()).append(NL);
>>      }
>>      else if (obj instanceof ASN1GeneralizedTime)
>>      {
>>        buf.append("ASN1GeneralizedTime :
>> ").append(((ASN1GeneralizedTime)obj).getTime()).append(NL);
>>      }
>>      else if (obj instanceof ASN1ObjectIdentifier)
>>      {
>>        buf.append("ASN1ObjectIdentifier :
>> ").append(OidMap.get(((ASN1ObjectIdentifier)obj).getId())).append(NL);
>>      }
>>      else if (obj instanceof ASN1Integer)
>>      {
>>        buf.append("ASN1Integer :
>> ").append(((ASN1Integer)obj).getValue().toString()).append(NL);
>>      }
>>      else if (obj instanceof ASN1Boolean)
>>      {
>>        buf.append("ASN1Boolean : ").append(((ASN1Boolean)obj).isTrue() ?
>> "true" : "false").append(NL);
>>      }
>>      else if (obj instanceof ASN1OctetString)
>>      {
>>        buf.append("ASN1OctetString").append(NL);
>>        ASN1OctetString octObj = (ASN1OctetString)obj;
>>        try
>>        {
>>          ASN1InputStream aIn = new
>> ASN1InputStream(octObj.getOctetStream());
>>          ASN1Primitive dobj = aIn.readObject();
>>          dump(dobj, buf, depth + 1);
>>        }
>>        catch(Exception e)
>>        {
>>          indent(buf, depth + 1);
>>          buf.append(ByteArrayUtil.toHexString(octObj.getOctets(),
>> ":")).append(NL);
>>        }
>>      }
>>      else if (obj instanceof ASN1TaggedObject)
>>      {
>>        buf.append("ASN1TaggedObject").append(NL);
>>        dump(((ASN1TaggedObject)obj).getObject(), buf, depth + 1);
>>      }
>>      else if (obj instanceof ASN1Sequence)
>>      {
>>        buf.append("ASN1Sequence").append(NL);
>>
>>        Enumeration objs = ((ASN1Sequence)obj).getObjects();
>>        while (objs.hasMoreElements())
>>        {
>>          Object o = objs.nextElement();
>>          if (o == null || o instanceof DERNull)
>>          {
>>            indent(buf, depth + 1);
>>            buf.append("DERNull").append(NL);
>>          }
>>          else if (o instanceof ASN1Primitive)
>>          {
>>            dump((ASN1Primitive)o, buf, depth + 1);
>>          }
>>          else
>>          {
>>            dump(((ASN1Encodable)o).toASN1Primitive(), buf, depth + 1);
>>          }
>>        }
>>      }
>>      else if (obj instanceof ASN1Set)
>>      {
>>        buf.append("ASN1Set").append(NL);
>>
>>        Enumeration objs = ((ASN1Set)obj).getObjects();
>>        while (objs.hasMoreElements())
>>        {
>>          Object o = objs.nextElement();
>>          if (o == null || o instanceof DERNull)
>>          {
>>            indent(buf, depth + 1);
>>            buf.append(NL);
>>          }
>>          else if (o instanceof ASN1Primitive)
>>          {
>>            dump((ASN1Primitive)o, buf, depth + 1);
>>          }
>>          else
>>          {
>>            dump(((ASN1Encodable)o).toASN1Primitive(), buf, depth + 1);
>>          }
>>        }
>>      }
>>      else
>>      {
>>        buf.append(obj.getClass().getName()).append(NL);
>>      }
>>    }
>>
>>    private static void indent(StringBuffer buf, int depth)
>>    {
>>      for (int i = 0; i < depth; i++)
>>        buf.append("  ");
>>    }
>>
>>    private static String NL = "\n";
>>    static
>>    {
>>      Security.addProvider(new
>> org.bouncycastle.jce.provider.BouncyCastleProvider());
>>    }
>> }
>>
>> Regards,
>> Bill
>>
>> ------------------------------------------
>> Bill Smith
>> Tridium, Inc.
>
>

David Hook | 6 Jul 00:51 2012

Re: Cryptographic message syntax (CMS) and light-weight api


Have a look at:

http://www.bouncycastle.org/wiki/display/JA1/BC+Version+2+APIs

There are test classes which show how to use the lightweight APIs in the 
source tree as well.

Regards,

David

On 05/07/12 20:41, Fabrizio Gulino wrote:
> Hi,
> I have to implement the Cryptographic message syntax (CMS) management 
> using only the light-weight api because we don't want to ask to our 
> users to download the unrestricted policy files for the Sun JCE.
>
> For instance what I've to do is the same I've done using the provider:
>  public byte[] createAttoEncoded(byte[] bout, Certificate cert) throws 
> Exception {
>         byte[] encoded = null;
>
>         try {
>            Security.addProvider(new 
> org.bouncycastle.jce.provider.BouncyCastleProvider());
>
>             CMSEnvelopedDataGenerator gen = new 
> CMSEnvelopedDataGenerator();
>             gen.addKeyTransRecipient((X509Certificate) cert); 
> //gen.addRecipientInfoGenerator(new 
> BcRSAKeyTransRecipientInfoGenerator(new 
> X509CertificateHolder(cert.getEncoded())));
>
>             CMSProcessableByteArray processable = new 
> CMSProcessableByteArray(bout);
>             CMSEnvelopedData envData = gen.generate(processable, 
> CMSEnvelopedDataGenerator.DES_EDE3_CBC, "BC");
>             encoded = envData.getEncoded();
>             return encoded;
>         } catch (Exception e) {
>             throw e;
>         }
>     }
>
> Is there someone that could tell me where I can find some examples or 
> specific documentation?
> Now I'm trying to understand the source code of the class 
> CMSEnvelopedDataGenerator but I would like to know if there is a 
> better start point.
>
> Many thanks to all
>

David Hook | 6 Jul 00:56 2012

Re: Blackberry using J2ME distribution


You also need to have a look at:

http://www.bouncycastle.org/wiki/display/JA1/BC+Version+2+APIs

There are test classes which show how to use the lightweight APIs in the 
source tree as well. I'm a bit surprised though, the current version of 
the J2ME API ships with the necessary classes.

Regards,

David

On 05/07/12 19:45, Lamchith M C wrote:
> Hi,
>
> I have been trying to use J2ME distribution of bouncycastle  to 
> Creates a signed CMS message. Classes like JcaContentSignerBuilder are 
> not available under the J2ME distribution. So i believe i have use 
> bcpkix-jdk11-147.zip. But then the blackberry java will not have the 
> corresponding java.security classes. So is possible to achieve it only 
> using J2ME distribution of bouncycastle. Am i missing something. 
> Please provide some help.
>
> -- 
> Regards,
> Lamchith
>

eribonn.CSN1 | 6 Jul 10:58 2012
Picon

Problem with TSP

Hello all,

 

I’m trying to implement a simple timestamp server. This server will receive SHA-256 digest and will answer with a TimeStampToken (obviously) and SHA256WithRSAEncryption signature.

 

My problem is that when I send my SHA-256 digest to the server, I only get an exception because of a test in the TimeStampTokenGenerator class : it only works if the DigestCalculator is a Sha1DigestCalculator.

 

Can you explain me why it only accepts SHA1 digests ?

 

Best regards,

Eric


Gmane