使用私钥签名就用公钥验签,反正就对调 (注: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).