📜 ⬆️ ⬇️

ASN.1 and Erlang

In the old days, when computers were large, and engineers were visionary, when the spirit of marketers was unknown to the knights of bits and terminals, in one kingdom-state, at Kalynovo Bridge, these brave men gathered and decided to think of a way to present generic data structures for transmitting them on the network, so that their beautiful ladies could communicate with each other by phone and not distract them from solving urgent problems. Since there were few marketers in those areas, the method turned out to be elegant and consuming few resources for encoding / decoding. And they called it ASN.1, or shortly X.208.

The ASN.1 protocol describes the data structure in simple and understandable language. For example, we need to describe a message that will contain a version field (an integer), a message type (enumeration), and a message body (binary data). We will get this description and save it in the SP.asn file:

 SP DEFINITIONS AUTOMATIC TAGS :: =
 BEGIN

 Message :: = SEQUENCE
 {
   version INTEGER DEFAULT 1,
   type MsgType,
   body body
 }

 MsgType :: = ENUMERATED
 {
   public (0),
   private (1),
   tralala (2)
 }

 Body :: = OCTET STRING

 END


There are many different compilers for ASN.1, both paid and free, for different programming languages, but we will focus on one of them - the compiler from the standard Erlang / OTP delivery. Run some command like this:
')
 $ erlc SP.asn


After compilation four files will be created:

Now you can run the Erlang interpreter with a clear conscience and encode the message:
 [zert @ pluto]: Habrahabr $ >> erl
 Erlang R13B01 (erts-5.7.2) [source] [smp: 2: 2] [rq: 2] [async-threads: 0] [hipe] [kernel-poll: false]

 Eshell V5.7.2 (abort with ^ G)
 1> rr ("SP.hrl").
 ['Message']
 2> {ok, Bin} = 'SP': encode ('Message', # 'Message' {version = 3, type = private, body = "Hello, ASN.1"}).
 {ok, [48,20,128,1,3,129,1,1,130,12,72,101,108,108,111,44,32,65,83,78,46,49]}


We received a list of bytes that can already be transmitted over the network, save
to disk and do other actions you can do with bytes.
Reverse to encoding action - decoding. This is done no more difficult than coding:

 3> 'SP': decode ('Message', Bin).
 {ok, # 'Message' {version = 3, type = private,
                body = "Hello, ASN.1"}}


These are the most basic ways to use the ASN.1 compiler from Erlang / OTP, reading the documentation will help you learn more about it, for example, here .

Source: https://habr.com/ru/post/64111/


All Articles