decode ASN.1 encoded OID's

Discussion of open issues, suggestions and bugs regarding network security and data protection solution - SecureBridge
Post Reply
vanmeir
Posts: 13
Joined: Thu 19 May 2011 09:34
Location: The Netherlands
Contact:

decode ASN.1 encoded OID's

Post by vanmeir » Wed 26 Aug 2015 12:35

Hello everyone,

I'm currently building a module for reading the Dutch Vehicle Registration Card.
In order to validate the digital signature(s) against the certificate I have to get an OID from the SmartCard which tells me what algorithm to use.
That field comes as an ASN.1 encoded OID field.

Can I decode that info to get the 'human' readable info with SecureBridge so I can decide which algorithm I should use?

The TScOid class does not have a (class-) function for that nor can I find other functions for that in any of the SecureBridge units.

Best reagards,
Frans

vanmeir
Posts: 13
Joined: Thu 19 May 2011 09:34
Location: The Netherlands
Contact:

Re: decode ASN.1 encoded OID's

Post by vanmeir » Wed 26 Aug 2015 14:46

Hello all,

because I was in a hurry I explored the Internet and found some C# code.
Based on that I created my own solution.
In case someone might need it....

Code: Select all

interface

type
  TScOidHelper =  class helper for TScOid
    class function Decode(const ASN1Oid: AnsiString): AnsiString; overload;
    class function Decode(const ASN1OidStr: TStream): AnsiString; overload;
    class function DecodeValue(const Str: TStream): AnsiString;
  end;

implementation

{ TscOisHelper }

class function TScOidHelper.Decode(const ASN1Oid: AnsiString): AnsiString;
var
  LStream: TMemoryStream;
begin
  LStream := TMemoryStream.Create;
  try
    LStream.Write(TBytes(ASN1Oid), Length(ASN1Oid));
    LStream.Position := 0;

    Result := Decode(LStream);
  finally
    LStream.Free;
  end;
end;

class function TScOidHelper.Decode(const ASN1OidStr: TStream): AnsiString;
var
  b: Byte;
  v: LongWord;
begin
  v := 0;

  ASN1OidStr.Read(b, 1);

  Result := (b div 40).ToString + '.' + (b mod 40).ToString;

  while ASN1OidStr.Position < ASN1OidStr.Size do
  try
    Result := Result + '.' + DecodeValue(ASN1OidStr);
  except
    on E:Exception do
      raise Exception.Create('Failed to decode OID value: ' + e.Message);
  end;
end;

class function TScOidHelper.DecodeValue(const Str: TStream): AnsiString;
var
  b: Byte;
  i: Integer;
  v: LongWord;
begin
  v := 0;

  while Str.Position < Str.Size do
  begin
    Str.Read(b, 1);

    v := v shl 7;
    v := v + LongWord(b and $7f);

    if (b and $80) = 0 then
      Exit(v.ToString);
  end;

  raise Exception.Create('Error decoding OID value');
end;


Dimon
Devart Team
Posts: 2910
Joined: Mon 05 Mar 2007 16:32

Re: decode ASN.1 encoded OID's

Post by Dimon » Fri 28 Aug 2015 15:12

It is good to see that the problem has been solved.

Post Reply