Erlang:将vapid密钥PEM文件转换为base 64字符串格式(applicationServerKey)

5ktev3wc  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(168)

嗨,我喜欢从Erlang服务器应用程序发送FCM推送通知。当用户在浏览器中订阅FCM通知时,swRegistration.pushManager.subscribe()需要一个公钥(applicationServerKey)。
所以为了得到这个密钥,我使用openssl并生成两个PEM文件私钥和公钥。

openssl ecparam -name prime256v1 -genkey -noout -out es_private_key.pem   
openssl ec -in es_private_key.pem -pubout -out es_public_key.pem

我知道你可以从firebase控制台获得私钥和公钥。但是提供的密钥不是PEM格式的,并且对jwtthis one进行签名的erlang库使用PEM文件进行签名和验证。

{ok, PrivtPem} = file:read_file("path/to/es_private_key.pem"),
Jwt = jwerl:sign([{name, <<"bob">>}], es256, PrivtPem).

因此,根据生成的PEM私钥,我可以对JWT进行签名,但我需要base64字符串格式的applicationServerKey将其添加到标头中,并在浏览器中订阅用户。
我应该将firebase控制台中的密钥转换为PEMS或将PEMS转换为firebase密钥格式。
我花了两天时间试着和Erlang一起做这件事。
我发现如何在Python中做这件事,我需要一些在Erlang中等价的东西。

raw_pub = vapid.public_key.public_bytes(
                serialization.Encoding.X962,
                serialization.PublicFormat.UncompressedPoint
            )
        print("Application Server Key = {}\n\n".format(
            b64urlencode(raw_pub)))
rn0zuynd

rn0zuynd1#

Afters days I found how to do this en Erlang.
First I used a library called base64Url from someone called Vladimir.
Then I used the code used by authors of JWERL and at the end I do base64Url encode of the ECPoint bin content.
Below the erlang code:

pem_to_string()->
{ok, key} = file:read_file("/home/keys/es_public_key.pem"),
 [SPKI] = public_key:pem_decode(Key),
  #'SubjectPublicKeyInfo'{algorithm = Der} = SPKI,
  RealSPKI = public_key:der_decode('SubjectPublicKeyInfo', Der),
  #'SubjectPublicKeyInfo'{
     subjectPublicKey = Octets,
     algorithm = #'AlgorithmIdentifier'{ parameters = Params}
    } = RealSPKI,
  ECPoint = #'ECPoint'{point = Octets}, 
{'ECPoint', Bin} = ECPoint,
base64url:encode(Bin).

I'm not specialist in cryptographic and curved keys I want only to sign push content because Google want this. So this code Gives me the 64 octets base64 encoded public key . I can use this public key in push FCM.
I hope this is useful for someone.

相关问题