PHP 生成公钥私钥,加密解密,签名验签
test_encry.php
<?php //创建私钥,公钥 //create_key(); //要加密内容 $str = "test_str"; //加密 $encrypt_str = test_encrypt($str); //解密 $decrypt_str = test_decrypt($encrypt_str); //echo $decrypt_str;exit; //签名 $sign_str = sign ( $decrypt_str ); // echo $sign_str;exit; //验签 $res = verify ( $decrypt_str, $sign_str ); var_dump ( $res ); exit (); //创建秘钥对 function create_key(){ //配置信息 //配置需要用到环境配置文件 openssl.cnf,这里文件地址如下 $config_path = "D:\ApacheServer\Apache\conf\openssl.cnf"; $config = array( "digest_alg" => "sha512", "private_key_bits" => 4096, // 字节数 512 1024 2048 4096 等 ,不能加引号,此处长度与加密的字符串长度有关系 "private_key_type" => OPENSSL_KEYTYPE_RSA, // 加密类型 'config' => $config_path ); $new_key = openssl_pkey_new($config); if ( $new_key == false ){ return false; } //提取私钥 //$private_key 这里作为引用变量 openssl_pkey_export($new_key, $private_key, null, $config); //生成公钥 $public_key = openssl_pkey_get_details($new_key); // var_dump($public_key); $public_key = $public_key["key"]; //显示数据 //var_dump($public_key); //公钥 //var_dump($private_key); //私钥 file_put_contents("./testpublic.pem", $public_key); file_put_contents("./testprivate.pem", $private_key); openssl_free_key($new_key); } // 数据接收方创建一套密钥对,把公钥给发送方(一或多个发送方),发送方用公钥加密数据,发给接收方,接收方用私钥解密获取数据 // 接受方的密钥对 /** 公钥加密 @param $str 要加密的明文 */ function test_encrypt($str) { $cert_file = "./testpublic.pem"; // 读取公钥内容 $public_key = file_get_contents ( $cert_file ); // 转成openssl对象 $public_key = openssl_get_publickey ( $public_key ); // 进行加密,$encrypt_str 为引用变量 openssl_public_encrypt ( $str, $encrypt_str, $public_key ); // base64转码 $encrypt_str = base64_encode ( $encrypt_str ); return $encrypt_str; } /** 私钥解密 @param $encrypt_str 要解密的密文 */ function test_decrypt($encrypt_str) { $cert_file = "./testprivate.pem"; // 读取私钥内容 $private_key = file_get_contents ( $cert_file ); // 转成openssl对象 $private_key = openssl_get_privatekey ( $private_key ); // base64解码 $encrypt_str = base64_decode ( $encrypt_str ); openssl_private_decrypt ( $encrypt_str, $decrypt_str, $private_key ); return $decrypt_str; } // 数据发送方创建一套密钥对,把公钥给接收方,发送方用私钥签名数据,发给接收方。接收方将“解密后的明文、收到的签名、发送方生成的公钥”三个数据一起来验签,验证通过则表示发送方是真实有效的(签名就是为排除冒充发送方发信息的行为) // 发送方的密钥对(这里为方便,用同一套密钥对) /** 私钥签名 @param $plain 要签名的明文 */ function sign($plain) { // $log = new Logger(); try { // 用户私钥证书 $cert_file = "./testprivate.pem"; $priv_key = file_get_contents ( $cert_file ); $pkeyid = openssl_get_privatekey ( $priv_key ); if (! is_resource ( $pkeyid )) { return FALSE; } // compute signature openssl_sign ( $plain, $signature, $pkeyid, OPENSSL_ALGO_SHA256 ); // free the key from memory openssl_free_key ( $pkeyid ); // $log->logInfo("Signature string for:".$signature); return base64_encode ( $signature ); } catch ( Exception $e ) { // $log->logInfo("Signature attestation failure".$e->getMessage()); } } /** 公钥验签 @param $plain 验签明文 @param $signature 验签密文 */ function verify($plain, $signature) { $cert_file = "./testpublic.pem"; $signature = base64_decode ( $signature ); $cert = file_get_contents ( $cert_file ); $pubkeyid = openssl_get_publickey ( $cert ); if (! is_resource ( $pubkeyid )) { return FALSE; } $ok = openssl_verify ( $plain, $signature, $pubkeyid, OPENSSL_ALGO_SHA256 ); @openssl_free_key ( $pubkeyid ); if ($ok == 1) { return TRUE; } elseif ($ok == 0) { return FALSE; } else { return FALSE; } return FALSE; }
testprivate.pem
-----BEGIN PRIVATE KEY----- MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQDI7ysitVvgmHod BwccHcgbaKANaDyMXJ30wkJRcaygZohZJkMlExsz9lPtlPUMrkH+QkJSzzIP9Nr2 46LCKG5xDzRBzJbgcdsqjQk4sdSDGdiqOyIloHvYkQQvFRcStGjrIGswiU3NXvU3 kRG1ep1DvbsYTKYpkWkMxj9UJhgdkhoGgWgV6ij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/SE/hnuc3sLs8 2OhxQqFpyeNBLAugG8aqSviS+/KZhuivChTRd5rvfCIB/M4jZ9earxo0ThS8rMk8 pzH+NriiTc2VTf5HqN5MXrDWQ5/1tw/kIlsmQooJGWfUwFbH82DRX3GER9xmYGdy 4M48F+4XkFFDJw8vJR2ivcoaHVt9He3w7eb3oIaI1mJJFZa2oOdDyciarFOk4oQf 7arRXhQoSAYXB2Emf2eSEpQlCZd4HgebrlCUX7rI0aXVbAeEc8mls4l16XeBm5dy 6ETwaO3oc77fuKZ6pET2YoGCrmlxeauykNDrUYbbho+elR4s16r/EwHLFPsRjMXh aA0dJsKT5Cfxt22sLhDwJawXQ8sw1pbRN8FOhnh7IeigjgQb+F45JGZPy7Jt6uEA BWZt9YC+3ScwuFIjx39uuBht+V4HbKPTiZSIZYoTcKOMmQrT/8rspF8MI8o0jk+7 PSaxS8I5/4/KxNK5lqf6dZ8CAwEAAQ== -----END PUBLIC KEY-----
openssl.cnf
# # OpenSSL example configuration file. # This is mostly being used for generation of certificate requests. # # This definition stops the following lines choking if HOME isn't # defined. HOME = . RANDFILE = $ENV::HOME/.rnd # Extra OBJECT IDENTIFIER info: #oid_file = $ENV::HOME/.oid oid_section = new_oids # To use this configuration file with the "-extfile" option of the # "openssl x509" utility, name here the section containing the # X.509v3 extensions to use: # extensions = # (Alternatively, use a configuration file that has only # X.509v3 extensions in its main [= default] section.) [ new_oids ] # We can add new OIDs in here for use by 'ca', 'req' and 'ts'. # Add a simple OID like this: # testoid1=1.2.3.4 # Or use config file substitution like this: # testoid2=${testoid1}.5.6 # Policies used by the TSA examples. tsa_policy1 = 1.2.3.4.1 tsa_policy2 = 1.2.3.4.5.6 tsa_policy3 = 1.2.3.4.5.7 #################################################################### [ ca ] default_ca = CA_default # The default ca section #################################################################### [ CA_default ] dir = ./demoCA # Where everything is kept certs = $dir/certs # Where the issued certs are kept crl_dir = $dir/crl # Where the issued crl are kept database = $dir/index.txt # database index file. #unique_subject = no # Set to 'no' to allow creation of # several ctificates with same subject. new_certs_dir = $dir/newcerts # default place for new certs. certificate = $dir/cacert.pem # The CA certificate serial = $dir/serial # The current serial number crlnumber = $dir/crlnumber # the current crl number # must be commented out to leave a V1 CRL crl = $dir/crl.pem # The current CRL private_key = $dir/private/cakey.pem# The private key RANDFILE = $dir/private/.rand # private random number file x509_extensions = usr_cert # The extentions to add to the cert # Comment out the following two lines for the "traditional" # (and highly broken) format. name_opt = ca_default # Subject Name options cert_opt = ca_default # Certificate field options # Extension copying option: use with caution. # copy_extensions = copy # Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs # so this is commented out by default to leave a V1 CRL. # crlnumber must also be commented out to leave a V1 CRL. # crl_extensions = crl_ext default_days = 365 # how long to certify for default_crl_days= 30 # how long before next CRL default_md = default # use public key default MD preserve = no # keep passed DN ordering # A few difference way of specifying how similar the request should look # For type CA, the listed attributes must be the same, and the optional # and supplied fields are just that :-) policy = policy_match # For the CA policy [ policy_match ] countryName = match stateOrProvinceName = match organizationName = match organizationalUnitName = optional commonName = supplied emailAddress = optional # For the 'anything' policy # At this point in time, you must list all acceptable 'object' # types. [ policy_anything ] countryName = optional stateOrProvinceName = optional localityName = optional organizationName = optional organizationalUnitName = optional commonName = supplied emailAddress = optional #################################################################### [ req ] default_bits = 1024 default_keyfile = privkey.pem distinguished_name = req_distinguished_name attributes = req_attributes x509_extensions = v3_ca # The extentions to add to the self signed cert # Passwords for private keys if not present they will be prompted for # input_password = secret # output_password = secret # This sets a mask for permitted string types. There are several options. # default: PrintableString, T61String, BMPString. # pkix : PrintableString, BMPString (PKIX recommendation before 2004) # utf8only: only UTF8Strings (PKIX recommendation after 2004). # nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings). # MASK:XXXX a literal mask value. # WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings. string_mask = utf8only # req_extensions = v3_req # The extensions to add to a certificate request [ req_distinguished_name ] countryName = Country Name (2 letter code) countryName_default = AU countryName_min = 2 countryName_max = 2 stateOrProvinceName = State or Province Name (full name) stateOrProvinceName_default = Some-State localityName = Locality Name (eg, city) 0.organizationName = Organization Name (eg, company) 0.organizationName_default = Internet Widgits Pty Ltd # we can do this but it is not needed normally :-) #1.organizationName = Second Organization Name (eg, company) #1.organizationName_default = World Wide Web Pty Ltd organizationalUnitName = Organizational Unit Name (eg, section) #organizationalUnitName_default = commonName = Common Name (e.g. server FQDN or YOUR name) commonName_max = 64 emailAddress = Email Address emailAddress_max = 64 # SET-ex3 = SET extension number 3 [ req_attributes ] challengePassword = A challenge password challengePassword_min = 4 challengePassword_max = 20 unstructuredName = An optional company name [ usr_cert ] # These extensions are added when 'ca' signs a request. # This goes against PKIX guidelines but some CAs do it and some software # requires this to avoid interpreting an end user certificate as a CA. basicConstraints=CA:FALSE # Here are some examples of the usage of nsCertType. If it is omitted # the certificate can be used for anything *except* object signing. # This is OK for an SSL server. # nsCertType = server # For an object signing certificate this would be used. # nsCertType = objsign # For normal client use this is typical # nsCertType = client, email # and for everything including object signing: # nsCertType = client, email, objsign # This is typical in keyUsage for a client certificate. # keyUsage = nonRepudiation, digitalSignature, keyEncipherment # This will be displayed in Netscape's comment listbox. nsComment = "OpenSSL Generated Certificate" # PKIX recommendations harmless if included in all certificates. subjectKeyIdentifier=hash authorityKeyIdentifier=keyid,issuer # This stuff is for subjectAltName and issuerAltname. # Import the email address. # subjectAltName=email:copy # An alternative to produce certificates that aren't # deprecated according to PKIX. # subjectAltName=email:move # Copy subject details # issuerAltName=issuer:copy #nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem #nsBaseUrl #nsRevocationUrl #nsRenewalUrl #nsCaPolicyUrl #nsSslServerName # This is required for TSA certificates. # extendedKeyUsage = critical,timeStamping [ v3_req ] # Extensions to add to a certificate request basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment [ v3_ca ] # Extensions for a typical CA # PKIX recommendation. subjectKeyIdentifier=hash authorityKeyIdentifier=keyid:always,issuer # This is what PKIX recommends but some broken software chokes on critical # extensions. #basicConstraints = critical,CA:true # So we do this instead. basicConstraints = CA:true # Key usage: this is typical for a CA certificate. However since it will # prevent it being used as an test self-signed certificate it is best # left out by default. # keyUsage = cRLSign, keyCertSign # Some might want this also # nsCertType = sslCA, emailCA # Include email address in subject alt name: another PKIX recommendation # subjectAltName=email:copy # Copy issuer details # issuerAltName=issuer:copy # DER hex encoding of an extension: beware experts only! # obj=DER:02:03 # Where 'obj' is a standard or added object # You can even override a supported extension: # basicConstraints= critical, DER:30:03:01:01:FF [ crl_ext ] # CRL extensions. # Only issuerAltName and authorityKeyIdentifier make any sense in a CRL. # issuerAltName=issuer:copy authorityKeyIdentifier=keyid:always [ proxy_cert_ext ] # These extensions should be added when creating a proxy certificate # This goes against PKIX guidelines but some CAs do it and some software # requires this to avoid interpreting an end user certificate as a CA. basicConstraints=CA:FALSE # Here are some examples of the usage of nsCertType. If it is omitted # the certificate can be used for anything *except* object signing. # This is OK for an SSL server. # nsCertType = server # For an object signing certificate this would be used. # nsCertType = objsign # For normal client use this is typical # nsCertType = client, email # and for everything including object signing: # nsCertType = client, email, objsign # This is typical in keyUsage for a client certificate. # keyUsage = nonRepudiation, digitalSignature, keyEncipherment # This will be displayed in Netscape's comment listbox. nsComment = "OpenSSL Generated Certificate" # PKIX recommendations harmless if included in all certificates. subjectKeyIdentifier=hash authorityKeyIdentifier=keyid,issuer # This stuff is for subjectAltName and issuerAltname. # Import the email address. # subjectAltName=email:copy # An alternative to produce certificates that aren't # deprecated according to PKIX. # subjectAltName=email:move # Copy subject details # issuerAltName=issuer:copy #nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem #nsBaseUrl #nsRevocationUrl #nsRenewalUrl #nsCaPolicyUrl #nsSslServerName # This really needs to be in place for it to be a proxy certificate. proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo #################################################################### [ tsa ] default_tsa = tsa_config1 # the default TSA section [ tsa_config1 ] # These are used by the TSA reply generation only. dir = ./demoCA # TSA root directory serial = $dir/tsaserial # The current serial number (mandatory) crypto_device = builtin # OpenSSL engine to use for signing signer_cert = $dir/tsacert.pem # The TSA signing certificate # (optional) certs = $dir/cacert.pem # Certificate chain to include in reply # (optional) signer_key = $dir/private/tsakey.pem # The TSA private key (optional) default_policy = tsa_policy1 # Policy if request did not specify it # (optional) other_policies = tsa_policy2, tsa_policy3 # acceptable policies (optional) digests = md5, sha1 # Acceptable message digests (mandatory) accuracy = secs:1, millisecs:500, microsecs:100 # (optional) clock_precision_digits = 0 # number of digits after dot. (optional) ordering = yes # Is ordering defined for timestamps? # (optional, default: no) tsa_name = yes # Must the TSA name be included in the reply? # (optional, default: no) ess_cert_id_chain = no # Must the ESS cert id chain be included? # (optional, default: no)