This article mainly introduces PHP docking Java reality plus sign verification example, interested in the friend's reference, I hope to help you.
My implementation of the method, mainly to the Java generated key to PHP can recognize the key in PEM format, the other add-sign, check the use of call OpenSSL built-in signature method.
The key generated by Java is primarily a string, whereas the PEM format key is a 64-bit line with the following header and footer file formats, and PHP then obtains the relative PEM format string.
PEM format key
-----Begin public Key-----//64chars row (multiline)-----END public Key----------BEGIN RSA PRIVATE Key-----//64chars Row (multiline)----- END RSA PRIVATE KEY-----
1.java key to PEM-formatted PHP code
/** * Format the string format Public private key as a PEM format public key * @param $secret _key * @param $type * @return string */public static function Format_secret_ke Y ($secret _key, $type) { //64 English characters followed by line feed "\ n", followed by line break "\ n" $key = (WordWrap ($secret _key, (+), "\ n", true). " \ n "; Add PEM format Header and tail if ($type = = ' pub ') { $pem _key = "-----BEGIN public key-----\ n". $key. "-----END public KEY-----\ n"; } else if ($type = = ' pri ') { $pem _key = "-----BEGIN RSA PRIVATE key-----\ n". $key. "-----END RSA PRIVATE KEY-----\ n"; } else{ Echo (' Public private key type illegal '); Exit (); } return $PEM _key;}
2. Add Sign
/** * RSA plus * @param $paramStr * @param $priKey * @return string */public static function sign ($PARAMSTR, $priKey) { $s IGN = "; Convert the string format Public private key to PEM format Public private key $priKeyPem = Signutil::format_secret_key ($priKey, ' pri '); Convert to OpenSSL key, must be a private key without pkcs8 conversion $res = Openssl_get_privatekey ($priKeyPem); Call OpenSSL built-in signature method, generate signature $sign openssl_sign ($paramStr, $sign, $res); Release Resource Openssl_free_key ($res); Base64 encoded signature $signBase = Base64_encode ($sign); URL encoded signature $sign = UrlEncode ($signBase); return $sign;}
3. Verification
/** * RSA Verification * @param $PARAMSTR * @param $sign * @param $pubKey * @return bool */public static function Verify ($PARAMSTR, $ Sign, $pubKey) { //Convert string format Public private key to PEM format Public private key $pubKeyPem = Signutil::format_secret_key ($pubKey, ' Pub '); The conversion to the OpenSSL key must be a public key that is not pkcs8 converted $res = Openssl_get_publickey ($pubKeyPem); URL decoding signature $signUrl = UrlDecode ($sign); Base64 decoding signature $signBase = Base64_decode ($SIGNURL); Call OpenSSL built-in method verification, return bool value $result = (bool) openssl_verify ($PARAMSTR, $signBase, $res); Release Resource Openssl_free_key ($res); Returns whether the resource was successfully returned $result;}
The above is the whole content of this article, I hope that everyone's study has helped.