linux
[linux] 使用openssl实现rsa非对称加密 -凯发ag旗舰厅登录网址下载
简单定义:公钥和私钥,加密和解密使用的是两个不同的密钥,所以是非对称
系统:ubuntu 14.04
软件:openssl java php
生成公钥私钥
使用命令生成私钥:
openssl genrsa -out rsa_private_key.pem 1024参数:genrsa 生成密钥 -out 输出到文件 rsa_private_key.pem 文件名 1024 长度
从私钥中提取公钥:
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem参数: rsa 提取公钥 -in 从文件中读入 rsa_private_key.pem 文件名 -pubout 输出 -out 到文件 rsa_public_key.pem 文件名
shell加解密
新建一个readme.txt 内容是taoshihan
使用公钥加密:
openssl rsautl -encrypt -in readme.txt -inkey rsa_public_key.pem -pubin -out hello.en参数: rsautl 加解密 -encrypt 加密 -in 从文件输入 readme.txt 文件名 -inkey 输入的密钥 rsa_public_key.pem 上一步生成的公钥 -pubin 表名输入是公钥文件 -out输出到文件 hello.en 输出文件名
使用私钥解密:
openssl rsautl -decrypt -in hello.en -inkey rsa_private_key.pem -out hello.de参数: -decrypt 解密 -in 从文件输入 hello.en 上一步生成的加密文件 -inkey 输入的密钥 rsa_private_key.pem 上一步生成的私钥 -out输出到文件 hello.de 输出的文件名
cat hello.de // taoshihan
php加解密
$profile="taoshihan"; echo "加密前:{$profile}\n"; //公钥加密 $public_key=file_get_contents("rsa_public_key.pem"); $pub_key = openssl_pkey_get_public($public_key); openssl_public_encrypt($profile,$encrypted,$pub_key); $encrypted=base64_encode($encrypted);//因为加密后是乱码,所以base64一下 echo "加密后:\n"; echo $encrypted."\n";//私钥解密 $private_key=file_get_contents("rsa_private_key.pem"); $pi_key = openssl_pkey_get_private($private_key); openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key); echo "解密后:\n"; echo $decrypted."\n";新建rsa.php的文件
执行后结果:
加密前:taoshihan 加密后: shjsdltceurvfo0ocenqhgl9rxrqrm3vuprqchhuvodx1ldjc2o2sivjjpqfpwokf1wa tqdyil9yjq0/2dqap4zaqi1tcnsxdugn2iuzq88g7b5esi7r/iwkcx527ple95ebvfmw/d65tlysci5rclcp3krow2fqdqz3d3nkai= 解密后: taoshihan
java加解密:
准备jar包 bcprov-ext-jdk15on-156.jar
wget http://www.bouncycastle.org/download/bcprov-ext-jdk15on-156.jarrsaencrypt.java 文件
import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.io.fileinputstream; import java.io.fileoutputstream; import java.security.invalidkeyexception; import java.security.keyfactory; import java.security.keypair; import java.security.keypairgenerator; import java.security.nosuchalgorithmexception; import java.security.securerandom; import java.security.interfaces.rsaprivatekey; import java.security.interfaces.rsapublickey; import java.security.spec.invalidkeyspecexception; import java.security.spec.pkcs8encodedkeyspec; import java.security.spec.x509encodedkeyspec; import java.security.keyfactory; import java.security.interfaces.rsaprivatekey; import java.security.spec.rsaprivatekeyspec;import org.bouncycastle.asn1.asn1sequence; import org.bouncycastle.asn1.pkcs.rsaprivatekeystructure;import javax.crypto.badpaddingexception; import javax.crypto.cipher; import javax.crypto.illegalblocksizeexception; import javax.crypto.nosuchpaddingexception;import org.bouncycastle.jce.provider.bouncycastleprovider;import sun.misc.base64decoder; import sun.misc.base64encoder;public class rsaencrypt {/*** 私钥*/private rsaprivatekey privatekey;/*** 公钥*/private rsapublickey publickey;/*** 字节数据转字符串专用集合*/private static final char[] hex_char= {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};/*** 获取私钥* @return 当前的私钥对象*/public rsaprivatekey getprivatekey() {return privatekey;}/*** 获取公钥* @return 当前的公钥对象*/public rsapublickey getpublickey() {return publickey;}/*** 随机生成密钥对*/public void genkeypair(){keypairgenerator keypairgen= null;try {keypairgen= keypairgenerator.getinstance("rsa");} catch (nosuchalgorithmexception e) {e.printstacktrace();}keypairgen.initialize(1024, new securerandom());keypair keypair= keypairgen.generatekeypair();this.privatekey= (rsaprivatekey) keypair.getprivate();this.publickey= (rsapublickey) keypair.getpublic();}/*** 从文件中输入流中加载公钥* @param in 公钥输入流* @throws exception 加载公钥时产生的异常*/public void loadpublickey(inputstream in) throws exception{try {bufferedreader br= new bufferedreader(new inputstreamreader(in));string readline= null;stringbuilder sb= new stringbuilder();while((readline= br.readline())!=null){if(readline.charat(0)=='-'){continue;}else{sb.append(readline);sb.append('\r');}}loadpublickey(sb.tostring());} catch (ioexception e) {throw new exception("公钥数据流读取错误");} catch (nullpointerexception e) {throw new exception("公钥输入流为空");}}/*** 从字符串中加载公钥* @param publickeystr 公钥数据字符串* @throws exception 加载公钥时产生的异常*/public void loadpublickey(string publickeystr) throws exception{try {base64decoder base64decoder= new base64decoder();byte[] buffer= base64decoder.decodebuffer(publickeystr);keyfactory keyfactory= keyfactory.getinstance("rsa");x509encodedkeyspec keyspec= new x509encodedkeyspec(buffer);this.publickey= (rsapublickey) keyfactory.generatepublic(keyspec);} catch (nosuchalgorithmexception e) {throw new exception("无此算法");} catch (invalidkeyspecexception e) {throw new exception("公钥非法");} catch (ioexception e) {throw new exception("公钥数据内容读取错误");} catch (nullpointerexception e) {throw new exception("公钥数据为空");}}/*** 从文件中加载私钥* @param keyfilename 私钥文件名* @return 是否成功* @throws exception */public void loadprivatekey(inputstream in) throws exception{try {bufferedreader br= new bufferedreader(new inputstreamreader(in));string readline= null;stringbuilder sb= new stringbuilder();while((readline= br.readline())!=null){if(readline.charat(0)=='-'){continue;}else{sb.append(readline);sb.append('\r');}}loadprivatekey(sb.tostring());} catch (ioexception e) {throw new exception("私钥数据读取错误");} catch (nullpointerexception e) {throw new exception("私钥输入流为空");}}public void loadprivatekey(string privatekeystr) throws exception{try {base64decoder base64decoder= new base64decoder();byte[] buffer= base64decoder.decodebuffer(privatekeystr);rsaprivatekeystructure asn1privkey = new rsaprivatekeystructure((asn1sequence) asn1sequence.frombytearray(buffer));rsaprivatekeyspec rsaprivkeyspec = new rsaprivatekeyspec(asn1privkey.getmodulus(), asn1privkey.getprivateexponent());keyfactory keyfactory= keyfactory.getinstance("rsa");rsaprivatekey prikey=(rsaprivatekey) keyfactory.generateprivate(rsaprivkeyspec);this.privatekey=prikey;// pkcs8encodedkeyspec keyspec= new pkcs8encodedkeyspec(buffer);// keyfactory keyfactory= keyfactory.getinstance("rsa");//this.privatekey= (rsaprivatekey) keyfactory.generateprivate(keyspec);} catch (nosuchalgorithmexception e) {throw new exception("无此算法");} catch (invalidkeyspecexception e) {throw new exception("私钥非法");} catch (ioexception e) {throw new exception("私钥数据内容读取错误");} catch (nullpointerexception e) {throw new exception("私钥数据为空");}}/*** 加密过程* @param publickey 公钥* @param plaintextdata 明文数据* @return* @throws exception 加密过程中的异常信息*/public byte[] encrypt(rsapublickey publickey, byte[] plaintextdata) throws exception{if(publickey== null){throw new exception("加密公钥为空, 请设置");}cipher cipher= null;try {cipher= cipher.getinstance("rsa/ecb/pkcs1padding", new bouncycastleprovider());cipher.init(cipher.encrypt_mode, publickey);byte[] output= cipher.dofinal(plaintextdata);return output;} catch (nosuchalgorithmexception e) {throw new exception("无此加密算法");} catch (nosuchpaddingexception e) {e.printstacktrace();return null;}catch (invalidkeyexception e) {throw new exception("加密公钥非法,请检查");} catch (illegalblocksizeexception e) {throw new exception("明文长度非法");} catch (badpaddingexception e) {throw new exception("明文数据已损坏");}}/*** 解密过程* @param privatekey 私钥* @param cipherdata 密文数据* @return 明文* @throws exception 解密过程中的异常信息*/public byte[] decrypt(rsaprivatekey privatekey, byte[] cipherdata) throws exception{if (privatekey== null){throw new exception("解密私钥为空, 请设置");}cipher cipher= null;try {cipher= cipher.getinstance("rsa/ecb/pkcs1padding", new bouncycastleprovider());cipher.init(cipher.decrypt_mode, privatekey);byte[] output= cipher.dofinal(cipherdata);return output;} catch (nosuchalgorithmexception e) {throw new exception("无此解密算法");} catch (nosuchpaddingexception e) {e.printstacktrace();return null;}catch (invalidkeyexception e) {throw new exception("解密私钥非法,请检查");} catch (illegalblocksizeexception e) {throw new exception("密文长度非法");} catch (badpaddingexception e) {throw new exception("密文数据已损坏");} }/*** 字节数据转十六进制字符串* @param data 输入数据* @return 十六进制内容*/public static string bytearraytostring(byte[] data){stringbuilder stringbuilder= new stringbuilder();for (int i=0; i带包编译和执行
javac -cp bcprov-ext-jdk15on-156.jar rsaencrypt.java java -cp .:bcprov-ext-jdk15on-156.jar rsaencrypt执行结果:
加载公钥成功 加载私钥成功 加密前: taoshihan 加密后: tt1p5xnamzkkvjgn1cvgeib7u cp27xw93jqquzyc2up/rjl4mx da8mxkva1a/i64sutb7qd//8 gbss4bzy/dhrlitytt2/qjjqufyd5/aa1m1qkubulwy4/c5so5dm6wrrnjolsifuby rfh4b6hp1 taqgbrdum/xex6osj9i= 解密后: taoshihan
shell使用公钥加密,php使用私钥解密
shell:
openssl rsautl -encrypt -in readme.txt -inkey rsa_public_key.pem -pubin|base64加密后的字符串lnj50odiofcp adrtai943hosjddtg3umfukt0ni7dhujxcm nalbh08wvqrtyk9w8zoqota3qh6 pzmjt4wsi0yfngiuwygoygsotpursqmbact3dm2y5mekqzbklrhn s 9jrtmef1vubues8wn6rod uhxi vdwq utrjrro9u=php:
php $encrypted="lnj50odiofcp adrtai943hosjddtg3umfukt0ni7dhujxcm nalbh08wvqrtyk9w8zoqota3qh6 pzmjt4wsi0yfngiuwygoygsotpursqmbact3dm2y5mekqzbklrhn s 9jrtmef1vubues8wn6rod uhxi vdwq utrjrro9u="; echo $encrypted."\n";//私钥解密 $private_key=file_get_contents("rsa_private_key.pem"); $pi_key = openssl_pkey_get_private($private_key); openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key); echo "解密后:\n"; echo $decrypted."\n";执行结果:
lnj50odiofcp adrtai943hosjddtg3umfukt0ni7dhujxcm nalbh08wvqrtyk9w8zoqota3qh6 pzmjt4wsi0yfngiuwygoygsotpursqmbact3dm2y5mekqzbklrhn s 9jrtmef1vubues8wn6rod uhxi vdwq utrjrro9u= 解密后: taoshihan
java使用公钥加密,php解密:
拿上一步java生成的加密后字符串
php $encrypted="tt1p5xnamzkkvjgn1cvgeib7u cp27xw93jqquzyc2up/rjl4mx da8mxkva1a/i64sutb7qd//8 gbss4bzy/dhrlitytt2/qjjqufyd5/aa1m1qkubulwy4/c5so5dm6wrrnjolsifuby rfh4b6hp1 taqgbrdum/xex6osj9i="; echo $encrypted."\n";//私钥解密 $private_key=file_get_contents("rsa_private_key.pem"); $pi_key = openssl_pkey_get_private($private_key); openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key); echo "解密后:\n"; echo $decrypted."\n";执行结果:
tt1p5xnamzkkvjgn1cvgeib7u cp27xw93jqquzyc2up/rjl4mx da8mxkva1a/i64sutb7qd//8 gbss4bzy/dhrlitytt2/qjjqufyd5/aa1m1qkubulwy4/c5so5dm6wrrnjolsifuby rfh4b6hp1 taqgbrdum/xex6osj9i= 解密后: taoshihan
转载于:https://www.cnblogs.com/taoshihan/p/6340854.html
与50位技术专家面对面20年技术见证,附赠技术全景图总结
以上是凯发ag旗舰厅登录网址下载为你收集整理的[linux] 使用openssl实现rsa非对称加密的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得凯发ag旗舰厅登录网址下载网站内容还不错,欢迎将凯发ag旗舰厅登录网址下载推荐给好友。
- 上一篇:
- 下一篇: