2021-05-12 14:32:11
Linux下使用OpenSSL實現RSA非對稱加密
簡單定義:公鑰和私鑰,加密和解密使用的是兩個不同的金鑰,所以是非對稱。
系統: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
檔案到Linux公社資源站下載:
------------------------------------------分割線------------------------------------------
免費下載地址在 http://linux.linuxidc.com/
使用者名稱與密碼都是www.linuxidc.com
具體下載目錄在 /2017年資料/1月/22日/Linux下使用OpenSSL實現RSA非對稱加密/
下載方法見 http://www.linuxidc.com/Linux/2013-07/87684.htm
------------------------------------------分割線------------------------------------------
RSAEncrypt.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<data.length; i++){
//取出位元組的高四位 作為索引得到相應的十六進位制識別符號 注意無符號右移
stringBuilder.append(HEX_CHAR[(data[i] & 0xf0)>>> 4]);
//取出位元組的低四位 作為索引得到相應的十六進位制識別符號
stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
if (i<data.length-1){
stringBuilder.append(' ');
}
}
return stringBuilder.toString();
}
public static void main(String[] args){
RSAEncrypt rsaEncrypt= new RSAEncrypt();
//載入公鑰
try {
rsaEncrypt.loadPublicKey(new FileInputStream("rsa_public_key.pem"));
System.out.println("載入公鑰成功");
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.println("載入公鑰失敗");
}
//載入私鑰
try {
rsaEncrypt.loadPrivateKey(new FileInputStream("rsa_private_key.pem"));
System.out.println("載入私鑰成功");
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.println("載入私鑰失敗");
}
//測試字串
String encryptStr= "taoshihan";
System.out.println("加密前:");
System.out.println(encryptStr);
try {
//加密
byte[] cipher = rsaEncrypt.encrypt(rsaEncrypt.getPublicKey(), encryptStr.getBytes());
//解密
byte[] plainText = rsaEncrypt.decrypt(rsaEncrypt.getPrivateKey(), cipher);
BASE64Encoder encode = new BASE64Encoder();
String buffer= encode.encode(cipher);
System.out.println("加密後:");
System.out.println(new String(buffer));
System.out.println("解密後:");
System.out.println(new String(plainText));
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
帶包編譯和執行
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
更多OpenSSL相關內容可以檢視以下的有用連結:
使用 OpenSSL 命令列構建 CA 及證書 http://www.linuxidc.com/Linux/2015-10/124682.htm
Ubuntu安裝OpenSSL http://www.linuxidc.com/Linux/2015-10/124001.htm
通過OpenSSL提供FTP+SSL/TLS認證功能,並實現安全資料傳輸 http://www.linuxidc.com/Linux/2013-05/84986.htm
Linux下使用OpenSSL生成證書 http://www.linuxidc.com/Linux/2015-05/117034.htm
利用OpenSSL簽署多域名證書 http://www.linuxidc.com/Linux/2014-10/108222.htm
在OpenSSL中新增自定義加密演算法 http://www.linuxidc.com/Linux/2015-08/121749.htm
相關文章