title: ASN1 parsing with swift
body: <p>I think I get the basic idea behind ASN.1 parsing. Walk the bytes, interpret them and do something useful with them. Alas I am stuck on the implementation.</p>
  
  <p>Apple has no sample code (that I could find), probably for security reasons. OpenSSL is not very well documented, so I can only guess at what the functions actually do. The only <a href="http://swiftrien.blogspot.be/2015/05/osx-receipt-validation-in-swift-part-1.html" rel="nofollow">sample code in swift</a> I did find doesn't handle case 17 (the in-app purchases), which is the one thing I am interested in. </p>
  
  <p>I tried figuring out where in the data stream the pointer is located, but I always get the same nonsensical result of 49.</p>
  
  <pre><code>    let receiptContents = NSData(contentsOfURL: receiptLocation)!
  
      let receiptBIO = BIO_new(BIO_s_mem())
      BIO_write(receiptBIO, receiptContents.bytes, Int32(receiptContents.length))
      contents = d2i_PKCS7_bio(receiptBIO, nil)
  
      //parsing
      var currentIndex    = UnsafePointer&lt;UInt8&gt;()
      var endIndex        = UnsafePointer&lt;UInt8&gt;()
  
      let octets      = pkcs7_d_data(pkcs7_d_sign(self.contents).memory.contents)
  
      var ptr = UnsafePointer&lt;UInt8&gt;(octets.memory.data)
      let end = ptr.advancedBy(Int(octets.memory.length))
      println(ptr.memory) //always 49 ???
      println(end.memory) //always 0 ???
      println(octets.memory.length)
  </code></pre>
  
  <p>I tried parsing the NSData myself, but well, what is the type of the binaire data?</p>
  
  <pre><code>    receiptContents = NSData(contentsOfURL: receiptLocation)!
  
      //get bytes
      let count = receiptContents.length / sizeof(UInt8)
      var bytes = [UInt8](count: count, repeatedValue: 0)
      receiptContents.getBytes(&amp;bytes, length:count * sizeof(UInt8))
  
      //parsing
      for index in 0...5
      {
          let value = Int(bytes[index])
          println(value)
      }
  </code></pre>
  
  <p>I get this output: 
  48
  130
  21
  57
  6
  9</p>
  
  <p>but if understand the ASN.1 format correctly, it's supposed to start with a value of 17 (set), then 3 bytes for the length (Int24?), then a value of 16 (first sequence), sequence length (1 byte), sequence type (1 byte), sequence payload, (repeat).</p>
  
  <p>Other types like Int32, Int16 makes even less sense to me.</p>
  
  <p>Not sure how to proceed here. Any suggestions?</p>