From 3adb2d33ec4c9768c7e2be387076d0609925d560 Mon Sep 17 00:00:00 2001 From: anlicheng Date: Sun, 19 Feb 2023 15:35:10 +0800 Subject: [PATCH] fix rsa --- apps/iot/src/iot_cipher_rsa.erl | 10 ++++++--- apps/iot/src/iot_mock.erl | 40 ++++++++++++++++++++++++++++++++- rebar.config | 4 ++-- 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/apps/iot/src/iot_cipher_rsa.erl b/apps/iot/src/iot_cipher_rsa.erl index 613ba3a..4b30393 100644 --- a/apps/iot/src/iot_cipher_rsa.erl +++ b/apps/iot/src/iot_cipher_rsa.erl @@ -14,9 +14,13 @@ %% 解密数据 decode(EncBin) when is_binary(EncBin) -> - PrivateKey = private_key(), - public_key:decrypt_private(EncBin, PrivateKey). + %PrivateKey = private_key(), + %public_key:decrypt_private(EncBin, PrivateKey). + ok. %% 解密数据 encode(Data, PublicKey) when is_binary(Data), is_binary(PublicKey) -> - ok. \ No newline at end of file + PubBin = <<"-----BEGIN PUBLIC KEY-----\n", PublicKey/binary, "-----END PUBLIC KEY-----">>, + [Pub] = public_key:pem_decode(PubBin), + PubKey = public_key:pem_entry_decode(Pub), + public_key:encrypt_public(Data, PubKey). \ No newline at end of file diff --git a/apps/iot/src/iot_mock.erl b/apps/iot/src/iot_mock.erl index d18f6f2..846b17c 100644 --- a/apps/iot/src/iot_mock.erl +++ b/apps/iot/src/iot_mock.erl @@ -12,6 +12,7 @@ %% API -export([insert_hosts/0]). +-export([rsa_encode/1]). insert_hosts() -> lists:foreach(fun(Id0) -> @@ -24,4 +25,41 @@ insert_hosts() -> }, host_model:add_host(Host) - end, lists:seq(1, 100)). \ No newline at end of file + end, lists:seq(1, 100)). + + +rsa_encode(Data) when is_binary(Data) -> + %% 读取相关配置 + PublicPemFile = "/tmp/keys/public.pem", + + %% 私钥保存解析后的 + {ok, PubBin} = file:read_file(PublicPemFile), + lager:debug("pub bin is: ~p", [PubBin]), + [Pub] = public_key:pem_decode(PubBin), + lager:debug("pub pem bin is: ~p", [Pub]), + PubKey = public_key:pem_entry_decode(Pub), + lager:debug("the public key is: ~p", [PubKey]), + + EncData = public_key:encrypt_public(Data, PubKey), + lager:debug("enc data is: ~p", [EncData]), + + rsa_decode(EncData), + + ok. + +rsa_decode(EncData) when is_binary(EncData) -> + %% 读取相关配置 + PublicPemFile = "/tmp/keys/pri.pem", + + %% 私钥保存解析后的 + {ok, PubBin} = file:read_file(PublicPemFile), + lager:debug("pub bin is: ~p", [PubBin]), + [Pub] = public_key:pem_decode(PubBin), + lager:debug("pub pem bin is: ~p", [Pub]), + PubKey = public_key:pem_entry_decode(Pub), + lager:debug("the public key is: ~p", [PubKey]), + + PlainData = public_key:decrypt_private(EncData, PubKey), + lager:debug("plain data is: ~p", [PlainData]), + + ok. \ No newline at end of file diff --git a/rebar.config b/rebar.config index adfa6eb..089d748 100644 --- a/rebar.config +++ b/rebar.config @@ -13,8 +13,8 @@ [iot, sasl]}, - % {mode, dev}, - {mode, prod}, + {mode, dev}, + %{mode, prod}, %% automatically picked up if the files %% exist but can be set manually, which