The method I implemented is mainly to convert Java-generated key into a PEM-formatted key that can be identified by PHP, while others are signed and checked by invoking OpenSSL built-in signature method.
Java generated keys are mainly strings, and the PEM format key is a 64-bit file format with the following headers and tails, and then PHP gets the corresponding PEM format string.
PEM format key
-----Begin Public Key-----
//64chars one line (multiline)
-----End Public Key-----
-----BEGIN RSA PRIVATE Key-----
/ /64chars one line (multiline)
-----end RSA PRIVATE KEY-----
1.java key into PEM format PHP code
/**
* Format the Public private key of the string format as a public private key in PEM format *
@param $secret _key
* @param $type
* @return String
* * The static function Format_secret_key ($secret _key, $type) {
//64 the English character followed by the newline character "\ n", followed by the line break "\ n"
$key = ($ 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 (' Illegal public key type ');
Exit ();
}
return $PEM _key;
}
2. Add Sign
/** *
RSA Endorsement
* @param $paramStr
* @param $priKey
* @return string/public
static function sign ( $PARAMSTR, $priKey) {
$sign = ';
Converts a string format public key into a PEM format public key
$priKeyPem = Signutil::format_secret_key ($priKey, ' pri ');
Conversion to OpenSSL key must be a private key without pkcs8 conversion
$res = Openssl_get_privatekey ($priKeyPem);
Call the OpenSSL built-in signature method to generate the signature $sign
openssl_sign ($paramStr, $sign, $res);
Release of resources
Openssl_free_key ($res);
Base64 coded Signature
$signBase-Base64_encode ($sign);
URL-coded signature
$sign = UrlEncode ($signBase);
return $sign;
}
3. Checking and verification
/** *
RSA Verification
* @param $paramStr
* @param $sign
* @param $pubKey * @return bool/Public static function Verify ($PARAMSTR, $sign, $pubKey) {
//Convert a string format public key into a PEM format public key
$pubKeyPem = Signutil::format_ Secret_key ($pubKey, ' Pub ');
Conversion to OpenSSL key must be a public key
$res = Openssl_get_publickey ($pubKeyPem) without a pkcs8 conversion;
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 of resources
Openssl_free_key ($res);
Returns whether the resource was successfully returned
$result;
}
The above PHP docking Java Reality plus sign verification of the example is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.