日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java rsa 117_java实现RSA非对称加密解密

發布時間:2023/12/2 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java rsa 117_java实现RSA非对称加密解密 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

之前寫過一篇java實現AES對稱加密解密

在對密碼加密傳輸的場景下 RSA非對稱加密解密可能會更加適合。

原理就是后臺生成一對公鑰和私鑰,公鑰給前端用來加密,后臺用私鑰去解密,保證了傳輸過程中就算被截獲也避免密碼泄露。

下面是代碼:

package com.zhaohy.app.utils;

import java.io.BufferedReader;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.security.KeyFactory;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.Signature;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import javax.crypto.CipherInputStream;

import org.apache.commons.codec.binary.Base64;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class RSAUtil {

/**

* RSA最大加密明文大小

*/

private static final int MAX_ENCRYPT_BLOCK = 117;

/**

* RSA最大解密密文大小

*/

private static final int MAX_DECRYPT_BLOCK = 128;

/**

* 獲取密鑰對

*

* @return 密鑰對

*/

public static KeyPair getKeyPair() throws Exception {

KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

generator.initialize(1024);

return generator.generateKeyPair();

}

/**

* 獲取私鑰

*

* @param privateKey 私鑰字符串

* @return

*/

public static PrivateKey getPrivateKey(String privateKey) throws Exception {

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);

return keyFactory.generatePrivate(keySpec);

}

/**

* 獲取公鑰

*

* @param publicKey 公鑰字符串

* @return

*/

public static PublicKey getPublicKey(String publicKey) throws Exception {

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());

X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);

return keyFactory.generatePublic(keySpec);

}

/**

* RSA加密

*

* @param data 待加密數據

* @param publicKey 公鑰

* @return

*/

public static String encrypt(String data, PublicKey publicKey) throws Exception {

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

int inputLen = data.getBytes().length;

ByteArrayOutputStream out = new ByteArrayOutputStream();

int offset = 0;

byte[] cache;

int i = 0;

// 對數據分段加密

while (inputLen - offset > 0) {

if (inputLen - offset > MAX_ENCRYPT_BLOCK) {

cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);

} else {

cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);

}

out.write(cache, 0, cache.length);

i++;

offset = i * MAX_ENCRYPT_BLOCK;

}

byte[] encryptedData = out.toByteArray();

out.close();

// 獲取加密內容使用base64進行編碼,并以UTF-8為標準轉化成字符串

// 加密后的字符串

return new String(Base64.encodeBase64String(encryptedData));

}

/**

* RSA解密

*

* @param data 待解密數據

* @param privateKey 私鑰

* @return

*/

public static String decrypt(String data, PrivateKey privateKey) throws Exception {

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.DECRYPT_MODE, privateKey);

byte[] dataBytes = Base64.decodeBase64(data);

int inputLen = dataBytes.length;

ByteArrayOutputStream out = new ByteArrayOutputStream();

int offset = 0;

byte[] cache;

int i = 0;

// 對數據分段解密

while (inputLen - offset > 0) {

if (inputLen - offset > MAX_DECRYPT_BLOCK) {

cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);

} else {

cache = cipher.doFinal(dataBytes, offset, inputLen - offset);

}

out.write(cache, 0, cache.length);

i++;

offset = i * MAX_DECRYPT_BLOCK;

}

byte[] decryptedData = out.toByteArray();

out.close();

// 解密后的內容

return new String(decryptedData, "UTF-8");

}

/**

* 簽名

*

* @param data 待簽名數據

* @param privateKey 私鑰

* @return 簽名

*/

public static String sign(String data, PrivateKey privateKey) throws Exception {

byte[] keyBytes = privateKey.getEncoded();

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

PrivateKey key = keyFactory.generatePrivate(keySpec);

Signature signature = Signature.getInstance("MD5withRSA");

signature.initSign(key);

signature.update(data.getBytes());

return new String(Base64.encodeBase64(signature.sign()));

}

/**

* 驗簽

*

* @param srcData 原始字符串

* @param publicKey 公鑰

* @param sign 簽名

* @return 是否驗簽通過

*/

public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {

byte[] keyBytes = publicKey.getEncoded();

X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

PublicKey key = keyFactory.generatePublic(keySpec);

Signature signature = Signature.getInstance("MD5withRSA");

signature.initVerify(key);

signature.update(srcData.getBytes());

return signature.verify(Base64.decodeBase64(sign.getBytes()));

}

/**

* 文件解密

*

* @param publicKeyStr

* @param srcFileName

* @param destFileName

*/

public static void decryptFileBig(String publicKeyStr, String srcFileName, String destFileName) {

Cipher cipher = null;

InputStream is = null;

OutputStream out = null;

try {

X509EncodedKeySpec encodedKey = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyStr));

KeyFactory keyf = KeyFactory.getInstance("RSA");

PublicKey pubKey = keyf.generatePublic(encodedKey);

cipher = Cipher.getInstance("RSA", new BouncyCastleProvider());

cipher.init(Cipher.DECRYPT_MODE, pubKey);

File f = new File(srcFileName);

is = new FileInputStream(f);

out = new FileOutputStream(destFileName);

int blockSize = cipher.getBlockSize();

int size = Integer.valueOf(String.valueOf(f.length()));

byte[] decryptByte = new byte[size];

is.read(decryptByte);

//分別對各塊數據進行解密

int j = 0;

while ((decryptByte.length - j * blockSize) > 0) {

out.write(cipher.doFinal(decryptByte, j * blockSize, blockSize));

j++;

}

} catch (Exception e) {

System.out.println(e);

} finally {

if (null != out) {

try {

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != is) {

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

/**

* 加密大文件

* @param privateKeyStr

* @param srcFileName

* @param destFileName

*/

public static void encryptFileBig(String privateKeyStr, String srcFileName, String destFileName) {

if (privateKeyStr == null) {

new Exception("加密私鑰為空, 請設置");

}

Cipher cipher = null;

InputStream is = null;

OutputStream out = null;

CipherInputStream cis = null;

try {

// 使用默認RSA

PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(

Base64.decodeBase64(privateKeyStr));

KeyFactory keyf = KeyFactory.getInstance("RSA");

PrivateKey priKey = keyf.generatePrivate(priPKCS8);

cipher = Cipher.getInstance("RSA", new BouncyCastleProvider());

cipher.init(Cipher.ENCRYPT_MODE, priKey);

int blockSize = cipher.getBlockSize();

is = new FileInputStream(srcFileName);

File f = new File(srcFileName);

int size = Integer.valueOf(String.valueOf(f.length()));

byte[] encryptByte = new byte[size];

is.read(encryptByte);

out = new FileOutputStream(destFileName);

int outputBlockSize = cipher.getOutputSize(encryptByte.length);

int leavedSize = encryptByte.length % blockSize;

int blocksNum = leavedSize == 0 ? encryptByte.length / blockSize : encryptByte.length / blockSize + 1;

byte[] cipherData = new byte[blocksNum * outputBlockSize];

for (int i = 0; i < blocksNum; i++) {

if ((encryptByte.length - i * blockSize) > blockSize) {

cipher.doFinal(encryptByte, i * blockSize, blockSize, cipherData,i * outputBlockSize);

} else {

cipher.doFinal(encryptByte, i * blockSize, encryptByte.length - i * blockSize,cipherData, i * outputBlockSize);

}

}

out.write(cipherData);

} catch (Exception e) {

System.out.println(e);

} finally {

if (null != cis) {

try {

cis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != is) {

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != out) {

try {

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

/**

* RSA文件簽名

*

* @param filePath

* @param privateKey

* @param encode

* @return

*/

public static String signFile(String filePath, String privateKey, String encode) {

FileInputStream fis = null;

InputStreamReader isr = null;

BufferedReader bfr = null;

try {

PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));

KeyFactory keyf = KeyFactory.getInstance("RSA");

PrivateKey priKey = keyf.generatePrivate(priPKCS8);

java.security.Signature signature = java.security.Signature.getInstance("SHA1WithRSA");

signature.initSign(priKey);

fis = new FileInputStream(new File(filePath));

isr = new InputStreamReader(fis, encode);

bfr = new BufferedReader(isr);

String lineTxt = "";

while (!AppFrameworkUtil.isBlank(lineTxt = bfr.readLine())) {

signature.update(lineTxt.getBytes(encode));

}

byte[] signed = signature.sign();

String ret = new String(Base64.encodeBase64(signed));

System.out.println("signed:" + ret);

return ret;

} catch (Exception e) {

System.out.println(e);

} finally {

if (bfr != null) {

try {

bfr.close();

} catch (IOException e) {

}

}

if (isr != null) {

try {

isr.close();

} catch (IOException e) {

}

}

if (fis != null) {

try {

fis.close();

} catch (IOException e) {

}

}

}

return null;

}

/**

* RSA文件驗簽名檢查

* @param content 待簽名數據

* @param sign 簽名值

* @param publicKey 分配給開發商公鑰

* @param encode 字符集編碼

* @return 布爾值

*/

public static boolean doCheckFile(String filePath, String sign, String publicKey, String encode) {

FileInputStream fis = null;

InputStreamReader isr = null;

BufferedReader bfr = null;

try {

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

byte[] encodedKey = Base64.decodeBase64(publicKey);

PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

java.security.Signature signature = java.security.Signature.getInstance("SHA1WithRSA");

signature.initVerify(pubKey);

fis = new FileInputStream(new File(filePath));

isr = new InputStreamReader(fis, "UTF-8");

bfr = new BufferedReader(isr);

String lineTxt = "";

while (!AppFrameworkUtil.isBlank(lineTxt = bfr.readLine())) {

signature.update(lineTxt.getBytes(encode));

}

boolean bverify = signature.verify(Base64.decodeBase64(sign));

return bverify;

} catch (Exception e) {

System.out.println(e);

} finally {

if (bfr != null) {

try {

bfr.close();

} catch (IOException e) {

}

}

if (isr != null) {

try {

isr.close();

} catch (IOException e) {

}

}

if (fis != null) {

try {

fis.close();

} catch (IOException e) {

}

}

}

return false;

}

public static void main(String[] args) {

try {

// 生成密鑰對

KeyPair keyPair = getKeyPair();

String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));

String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));

System.out.println("私鑰:" + privateKey);

System.out.println("公鑰:" + publicKey);

// RSA加密

String data = "123秘密啊";

String encryptData = encrypt(data, getPublicKey(publicKey));

System.out.println("加密后內容:" + encryptData);

// RSA解密

String decryptData = decrypt(encryptData, getPrivateKey(privateKey));

System.out.println("解密后內容:" + decryptData);

// RSA簽名

String sign = sign(data, getPrivateKey(privateKey));

System.out.println("sign==" + sign);

// RSA驗簽

boolean result = verify(data, getPublicKey(publicKey), sign);

System.out.println("驗簽結果:" + result);

/****大文件加簽驗簽****/

//加簽驗簽

String fileSign = signFile("/home/zhaohy/Documents/test.doc", privateKey, "UTF-8");

System.out.println("fileSign==" + fileSign);

boolean checkFileBoolean = doCheckFile("/home/zhaohy/Documents/test.doc", fileSign, publicKey, "UTF-8");

System.out.println("大文件校驗簽名結果:" + checkFileBoolean);

//加密解密

encryptFileBig(privateKey, "/home/zhaohy/Documents/test.txt", "/home/zhaohy/Documents/test.dat");

decryptFileBig(publicKey, "/home/zhaohy/Documents/test.dat", "/home/zhaohy/Documents/test1.txt");

} catch (Exception e) {

e.printStackTrace();

System.out.print("加解密異常");

}

}

}

運行結果:

私鑰:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALpLjdbsu172ftiv3eUC/JghSSzNRlp8p9Ilr8XlK/gl3gaPFFo1BAHWWyb9MhoTdE5BvES6E/eW5gVKby8olLa6ILbh9UYif0SKWca7pTt2nqn2Cd8v29/94ZF9i+yMoime3wuS7QxJEHG7qCqps7KVNtP/4/628lq1jB6B3DrPAgMBAAECgYBUtCGrxTt0dBM8psn3ZKJA8XF6A2OnpOIRNL109zxEucL3rHqOgWhvBW2wjpMHNC0/n7fgb9LAUkYHxc5D3OmwXAhvgRzDmMTeoaikrLeJpxX9NQ4TU3CFcL9YabQ+rjB6yMgfbmmA0B/odxpzIZd6ypHq91ogI/rfP4McaX7NwQJBAO9Qm4SoOn/0SzfOE+PjnIyLkDqW2kFRJv+c/4Z0H/yPOIjytHhe6hQQ8KHT2azOP+SeAWbjb152a5Rp/E8da/8CQQDHSKDBSGZuN/Qyk1eGJ80T9+GSQI0oYQfZcHYNUkAKrWceHISL5jMrUXWHSlKjFC5E7RsqQKMn72xisrlLcXExAkEA7YAB11VdOT8opulNtAxfgNvA92RelhQDsAoPTVBRrkQ0xzSXBh6sD93/8ZpdnLHTlv94RLPSAt1jRpcoXxvD4QJBALtv00uYVkdqt3NuZE8ZVmlmp7KQpnQJN4HLpi2HZBbm2+tVdVHEVfJzbrCuNiWO0KohvYAzRYJFTlNSuLd93rECQDcgPHh0qBOW22ggxiqpfbLIURvPAT9urp8NuTM0K0rW3mC2me55yPSDQ7jL1t9vwYkfahc0GUl1V1Cq/449AHU=

公鑰:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6S43W7Lte9n7Yr93lAvyYIUkszUZafKfSJa/F5Sv4Jd4GjxRaNQQB1lsm/TIaE3ROQbxEuhP3luYFSm8vKJS2uiC24fVGIn9EilnGu6U7dp6p9gnfL9vf/eGRfYvsjKIpnt8Lku0MSRBxu6gqqbOylTbT/+P+tvJatYwegdw6zwIDAQAB

加密后內容:R7GqGE2r51PmJAt3wtKhsbqfFzeobvzqFlAp8Tv0+3HkevsUF2a+/ZO7Sn53cKGwXIkOkDQN0S/pk/Eacd8Wk1wXKTKx57eSaQJFv/HQ5nDUfvtMWIg0IcHNmHyNBfDPVe/MiMkKf23/a/EyEfCQEzsCQyHLyHoTg34a1SNXTLs=

解密后內容:123秘密啊

sign==p8JR0aserak6iPltfAJx/mlvlp5Ox5NcpvRo7R1rxDItekMhyF82RVizgMqsmEBpWzW9Qkxm6AWzjzEr+XhR7u4KhxEO7euTHC9NGJ0TAtDKqtAsfFaZi8ZyY4MkHnSCFZVMcWMR3GhZ8ALJGe/lSstNSEp8H9lQE8u2o2oYiiw=

驗簽結果:true

signed:aavuNSCwaT2jZ6XrlAbSJNLBDalkWZ1t0tnQnveUw+3exlpcvRu0xotAlrW0V4voLLeRydLgIjwCwq1YxqFyKcYlOuORzorlmihjSXBZf0GZoJIlTIaUZ8/TJV+CRFObFnnEQ+8QAbRs4b7AB6nv1A2bxMeKulS0OTPxSkSFTdM=

fileSign==aavuNSCwaT2jZ6XrlAbSJNLBDalkWZ1t0tnQnveUw+3exlpcvRu0xotAlrW0V4voLLeRydLgIjwCwq1YxqFyKcYlOuORzorlmihjSXBZf0GZoJIlTIaUZ8/TJV+CRFObFnnEQ+8QAbRs4b7AB6nv1A2bxMeKulS0OTPxSkSFTdM=

大文件校驗簽名結果:true

可以看到加密解密成功,里面最后加密解密文件自測只對txt或html等文本文件有效,doc或者excel加密文件后解密出來的東西亂碼。

總結

以上是生活随笔為你收集整理的java rsa 117_java实现RSA非对称加密解密的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。