Skip to content

Instantly share code, notes, and snippets.

@baileysh9
Last active February 17, 2017 17:05
Show Gist options
  • Save baileysh9/4386ea92b047d97c7285 to your computer and use it in GitHub Desktop.
Save baileysh9/4386ea92b047d97c7285 to your computer and use it in GitHub Desktop.
Parsing Product Ids from Receipt in Swift
func getProductIdFromReceipt(_ data:Data) -> String? //Swift 2: func getProductIdFromReceipt(data:NSData) -> String?
{
//Swift 2: var p = UnsafePointer<UInt8>(data.bytes)
//Swift 3
var p : UnsafePointer? = (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count)
let dataLength = data.length
var type:Int32 = 0
var tag:Int32 = 0
var length = 0
let end = p! + dataLength
ASN1_get_object(&p, &length, &type, &tag, end - p!)
if type != V_ASN1_SET {
return nil
}
var integer: UnsafeMutablePointer<ASN1_INTEGER>
while p! < end
{
// Expecting an attribute sequence
ASN1_get_object(&p, &length, &type, &tag, end - p!)
if type != V_ASN1_SEQUENCE {
print("ASN1 error: expected an attribute sequence")
}
var attr_type = 0
// The attribute is an integer
ASN1_get_object(&p, &length, &type, &tag, end - p!)
if type != V_ASN1_INTEGER {
print("ASN1 error: attribute not an integer")
return nil
}
integer = c2i_ASN1_INTEGER(nil, &p, length)
attr_type = ASN1_INTEGER_get(integer)
ASN1_INTEGER_free(integer)
// The version is an integer
ASN1_get_object(&p, &length, &type, &tag, end - p!)
if type != V_ASN1_INTEGER {
print("ASN1 error: version not an integer")
return nil
}
integer = c2i_ASN1_INTEGER(nil, &p, length);
ASN1_INTEGER_free(integer);
// The attribute value is an octet string
ASN1_get_object(&p, &length, &type, &tag, end - p!)
if type != V_ASN1_OCTET_STRING {
print("ASN1 error: value not an octet string")
return nil
}
//For Product Id
if attr_type == 1702
{
if type == V_ASN1_OCTET_STRING
{
ASN1_get_object(&p, &length, &type, &tag, end - p!)
//Swift 2: let productId = NSString(bytes: p!, length: length, encoding: NSUTF8StringEncoding)
let productId = NSString(bytes: p!, length: length, encoding: String.Encoding.utf8.rawValue)
return productId as? String
}
}
//Swift 2: p = p.advancedBy(length)
p = p!.advanced(by: length)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment