首页 > 代码库 > Erlang中的RSA签名

Erlang中的RSA签名

RSA签名校验

-spec check_rsa_sign(DataBin, Sign, RSAPublicKeyBin, DigestType) -> boolean when
    DataBin :: binary(), 
    Sign :: binary(),
    RSAPublicKeyBin :: binary()
    DigestType :: ‘md5‘ | ‘sha‘ | ‘sha224‘ | ‘sha256‘ | ‘sha384‘ | ‘sha512‘.
check_rsa_sign(DataBin, Sign, RSAPublicKeyBin, DigestType) ->
    PemEntries = public_key:pem_decode(RSAPublicKeyBin),
    RSAPubKey = public_key:pem_entry_decode(hd(PemEntries)),
    Base64Sign = base64:decode(Sign),
    public_key:verify(DataBin, DigestType, Base64Sign, RSAPubKey).

产生RSA签名

-spec gen_rsa_sign(MsgBin, DigestType, KeyBin) -> binary() when
    MsgBin :: binary(),
    DigestType :: ‘md5‘ | ‘sha‘ | ‘sha224‘ | ‘sha256‘ | ‘sha384‘ | ‘sha512‘,
    KeyBin :: binary().
gen_rsa_sign(MsgBin, DigestType, KeyBin) ->
    [Entry] = public_key:pem_decode(KeyBin),
    RSAPriKey = public_key:pem_entry_decode(Entry),
    SignBin = public_key:sign(MsgBin, DigestType, RSAPriKey),
    base64:encode(SignBin).

示例

-define(RSA_PUBLIC_KEY, <<"-----BEGIN PUBLIC KEY-----\nXXXRSA_PUBLIC_KEYXXX\n-----END PUBLIC KEY-----">>).
-define(RSA_PRIVATE_KEY, <<"-----BEGIN RSA PRIVATE KEY-----\nXXXRSA_PRIVATE_KEYXXX\n-----END RSA PRIVATE KEY-----">>).

test() ->
    DataBin = make_data(),
    gen_rsa_sign(DataBin, ‘md5‘, ?RSA_PRIVATE_KEY),
    check_rsa_sign(DataBin, Sign, ?RSA_PUBLIC_KEY, ‘md5‘).

 

Erlang中的RSA签名