Digital signature and verification in php
1. First, generate a pair of public key and private key with php.
$ RES = OpenSSL _ pkey _ new();
openssl_pkey_export($res,$ pri);
$ d = OpenSSL _ pkey _ get _ details($ RES);
$ pub = $ d[' key '];
var_dump($pri,$ pub);
Output pem string with private key and public key in turn, for example:
String (9 16) "-Start private key-
miicdwibadangbgkqhkig 9 w 0 baqefaascamewggjdageaaogbaks 124 okan X5 JH 1Q
wset i80 B4 zyylyussatvs 7 ZG+gslaox 24 tknwiy 5 cud kfk/5 qejjz 0s 8 ljrsycg
to 9 lkwqtqrky 8 bbx vcqqs 3 vxrqz 4 on 9 bmcgsylmk 6 vqxt 9 nnjpk 6 abmje 7 z 35+8z
ttldubyamacyqrsydfbsnbgwbdagbaaecgybvoljpfmmcw 3 El 6 alhi pw 5 QJ
7 kmxdxnqmssxmvdln 4 iv 5 f 24 zm 2 jdydxmn+ST 3 fjeblefcpcoiq 5 uik x2 bno 3
f 9g 0 yt+quox dz 4 lk 6 JV 1 nfuazdcnbm 7 cxfe 7 bdregyirg 4 zxivp 4 l 0 y2 zbmdftmg
lkkxb 2m 1 p3pk 53 ubwqjbanupqpxfqjdhvaa 3 vot+ui 8 ohmlbw/vyh 6 ii 1 glwmfyq
vs 2 laakj 9d 1 hqlyzvw+enezbnzznpumj G5 aj/wkuqascqqdhiffs 7 Yb 1 rbhfjmrt
ZL 4 zxuvx 1 hvjtno 2 tezwpnigpya+qhcauddep 5c 9 q//n+D+ztkbkecxpovruhsi
ko 9 jakeal 3 LHD 98 uymvehvurwummlfsw 9 slsn 7 WC 9 awd 6 mwbw 5g 8 oxtx 5 joy+
ru 1 sq52d 7 rse Zr 40 fvhjtxowmudfaqjac8e+a2 epf/yenet JL 6 N2 re 8y+0 otdlwr
a 72 dph xy 6 vtm IPD 9 rho iz 2 MDR ZF 5 uk 7 fg 0 mio BMW 1 slw vx93 labiqjbalxpeona
B4 dqkrkfqchtyrwoercc 1y 6 fytfnj+crbzdicmfc 2 1 hxj 6 hky 2m 6/xgi 3 RAE 5 l+B
mmlSmN 1enhoCUqc=
-End private key-
"
String (272) "-Start public key-
MIG fma 0 gcsqgsib 3 dqebaqua 4 gnadcbiqkbgqcrndukjaj 1+y 4 dumlb 4 vng+Gc
mjwferalb 0u 2 rvhwkikmdueyjcfimuxfhsnyv+ubcy 2 devc 40 umahraps 5 mee0ky
mpaqv 1 qkeet 1 v0as+KJ/w5 nbksizcur 0 mbfttzyazomgziro 89+FVM 00y 8 hvg 2g ja
HGKq7GA34AUjQYMGwwIDAQAB
-End public key-
"
2. Keep your private key and make the public key public to others. If you need to sign some data to prove that it was sent by you, you need to use the private key:
$ RES = OpenSSL _ pkey _ get _ private($ pri);
if (openssl_sign('hello ',$out,$res))
var _ dump(base64 _ encode($ out));
In the above example, $pri is your private key and' hello' is the data to be signed. If the signature is successful, the final output is a base64 encoded signature, as shown in the following figure:
j 19H+C/NQEcyowezOQ+gmgi 2 uopjnxyj+kwpkezj 5 u 4 qard 3c 4 qhfffiosypwjtj 4 ljryoipnqm 6 ICJ 2 nmdgfn/p/pp7il+xgz 2 auwdoxkjfgic/ PGC 95 C 9 slh 04 TC 6 qsuv 5 IMD 9 rjbyv+ieokmlfm 9 cmtn 2 hgag 9 VQ 1s =
3. If someone receives your data "hello" and signature string and wants to verify whether it comes from you, please use your public key for verification:
$ SIG = base64 _ decode($ SIG);
$ RES = OpenSSL _ pkey _ get _ public($ pubkey);
if (openssl_verify('hello ',$sig,$ RES)= = 1)
; //Passed verification
In the above example, the initial $sig is your signature encoded in base64, and $pubkey is your public key.
This signature in php uses RSA algorithm; Digital signature can be used in systems such as single sign-on.