Erlang rsa 加 解密和签名的方法

 使用私钥签名就用公钥验签,反正就对调 (注:sha为sha1加密方式)

RSA签名 成sign内容

-spec gen_rsa_sign(MsgBin, DigestType, KeyBin) -> binary() when
    MsgBin :: binary(),
    DigestType :: 'md5' | 'sha' | 'sha224' | 'sha256' | 'sha384' | 'sha512',
    PrivateKeyFilePath :: name_all()  :: string() | atom() | deep_list() | (RawFilename :: binary())..
gen_rsa_private_sign(MsgBin, DigestType, PrivateKeyFilePath) ->
    {ok, KeyBin} = file:read_file(PrivateKeyFilePath),
    [Entry] = public_key:pem_decode(KeyBin),
    RSAPriKey = public_key:pem_entry_decode(Entry),
    SignBin = public_key:sign(MsgBin, DigestType, RSAPriKey),
    base64:encode(SignBin). 

 RSA签名校验sign内容的一致性

 -spec check_rsa_sign(DataBin, Sign, RsaKeyFilePath, DigestType) -> boolean when
    DataBin :: binary(), 
    Sign :: binary(),
    RsaKeyFilePath:: name_all()  :: string() | atom() | deep_list() | (RawFilename :: binary())..
    DigestType :: 'md5' | 'sha' | 'sha224' | 'sha256' | 'sha384' | 'sha512'.
check_rsa_sign(DataBin, Sign, RsaKeyFilePath, DigestType) ->
    {ok, KeyBin} = file:read_file(RsaKeyFilePath),
    [Entry] = public_key:pem_decode(KeyBin),
    RSAKeyBin = public_key:pem_entry_decode(Entry),
    Base64Sign = base64:decode(Sign),
    public_key:verify(DataBin, DigestType, Base64Sign, RSAKeyBin).

 RSA 加解/密

%% @doc     私钥加密
rsa_private_key_encode(Data, PrivateKeyFilePath) ->
    PriKey = get_rsa_key_str(PrivateKeyFilePath),
    base64:encode(public_key:encrypt_private(util:to_binary(Data), PriKey)).
%% @doc     私钥解密
rsa_private_key_decode(Signature, PrivateKeyFilePath) ->
    PriKey = get_rsa_key_str(PrivateKeyFilePath),
    public_key:decrypt_private(base64:decode(Signature), PriKey).

%% @doc     公钥加密
rsa_public_key_encode(Data, PublicKeyFilePath) ->
    PubKey = get_rsa_key_str(PublicKeyFilePath),
    base64:encode(public_key:encrypt_public(util:to_binary(Data), PubKey)).
%% @doc     公钥解密
rsa_public_key_decode(Signature, PublicKeyFilePath) ->
    PubKey = get_rsa_key_str(PublicKeyFilePath),
    public_key:decrypt_public(base64:decode(Signature), PubKey).
%% @fun 拿密钥内容
get_rsa_key_str(PublicKeyFilePath) ->
    {ok, PemBin} = file:read_file(PublicKeyFilePath),
    [Entry] = public_key:pem_decode(PemBin),
    public_key:pem_entry_decode(Entry).
 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值