聪明伶俐的铁板烧
6 月前 |
C#采用的RSACryptoServiceProvider类进行的加解密,由于该类默认是不支持私钥加密公钥解密的,需要通过BouncyCastle.Crypto.dll转换一下才可以。
代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using System.Xml;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Asn1.X509;
namespace RSADemo
/// <summary>
/// RSA加解密帮助类
/// 作者:代浩然
/// 时间:2019-1-21 18:37
/// </summary>
public class RSAHelper
/// <summary>
/// 生成公钥和私钥对
/// </summary>
public static void GeneratePublicAndPrivateKeyInfo()
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
using (StreamWriter writer = new StreamWriter("PrivateKey.xml")) //这个文件要保密...
string privateKey = rsa.ToXmlString(true);
writer.WriteLine(privateKey);
using (StreamWriter writer = new StreamWriter("PublicKey.xml"))
string publicKey = rsa.ToXmlString(false);
writer.WriteLine(publicKey);
/// <summary>
/// 用私钥给数据进行RSA加密
/// </summary>
/// <param name="xmlPrivateKey"> 私钥(XML格式字符串)</param>
/// <param name="strEncryptString">要加密的数据</param>
/// <returns> 加密后的数据 </returns>
public static string PrivateKeyEncrypt(string xmlPrivateKey, string strEncryptString)
//加载私钥
RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider();
privateRsa.FromXmlString(ReadFile(xmlPrivateKey));
//转换密钥
AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa);
IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //使用RSA/ECB/PKCS1Padding格式
//第一个参数为true表示加密,为false表示解密;第二个参数表示密钥
c.Init(true, keyPair.Private);
byte[] dataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString);
#region 分段加密
int bufferSize = (privateRsa.KeySize / 8) - 11;
byte[] buffer = new byte[bufferSize];
byte[] outBytes = null;
//分段加密
using (MemoryStream input = new MemoryStream(dataToEncrypt))
using (MemoryStream ouput = new MemoryStream())
while (true)
int readLine = input.Read(buffer, 0, bufferSize);
if (readLine <= 0)
break;
byte[] temp = new byte[readLine];
Array.Copy(buffer, 0, temp, 0, readLine);
byte[] encrypt = c.DoFinal(temp);
ouput.Write(encrypt, 0, encrypt.Length);
outBytes = ouput.ToArray();
#endregion
//byte[] outBytes = c.DoFinal(DataToEncrypt);//加密
string strBase64 = Convert.ToBase64String(outBytes);
return strBase64;
/// <summary>
/// 用公钥给数据进行RSA解密
/// </summary>
/// <param name="xmlPublicKey"> 公钥(XML格式字符串) </param>
/// <param name="strDecryptString"> 要解密数据 </param>
/// <returns> 解密后的数据 </returns>
public static string PublicKeyDecrypt(string xmlPublicKey, string strDecryptString)
//加载公钥
RSACryptoServiceProvider publicRsa = new RSACryptoServiceProvider();
publicRsa.FromXmlString(ReadFile(xmlPublicKey));
RSAParameters rp = publicRsa.ExportParameters(false);
//转换密钥
AsymmetricKeyParameter pbk = DotNetUtilities.GetRsaPublicKey(rp);
IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
//第一个参数为true表示加密,为false表示解密;第二个参数表示密钥
c.Init(false, pbk);
byte[] outBytes = null;
byte[] dataToDecrypt = Convert.FromBase64String(strDecryptString);
#region 分段解密
int keySize = publicRsa.KeySize / 8;
byte[] buffer = new byte[keySize];
using (MemoryStream input = new MemoryStream(dataToDecrypt))
using (MemoryStream output = new MemoryStream())
while (true)
int readLine = input.Read(buffer, 0, keySize);
if (readLine <= 0)
break;
byte[] temp = new byte[readLine];
Array.Copy(buffer, 0, temp, 0, readLine);
byte[] decrypt = c.DoFinal(temp);
output.Write(decrypt, 0, decrypt.Length);
outBytes = output.ToArray();
#endregion
//byte[] outBytes = c.DoFinal(DataToDecrypt);//解密
string strDec = Encoding.UTF8.GetString(outBytes);
return strDec;
/// <summary>
/// 使用公钥加密,分段加密
/// </summary>
/// <param name="content"></param>
/// <param name="privateKeyPath"></param>
/// <returns></returns>
public static string EncrytByPublic(string publicKeyPath, string strEncryptString)
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(ReadFile(publicKeyPath));
byte[] originalData = Encoding.UTF8.GetBytes(strEncryptString);
if (originalData == null || originalData.Length <= 0)
throw new NotSupportedException();
if (rsa == null)
throw new ArgumentNullException();
byte[] encryContent = null;
#region 分段加密
int bufferSize = (rsa.KeySize / 8) - 11;
byte[] buffer = new byte[bufferSize];
//分段加密
using (MemoryStream input = new MemoryStream(originalData))
using (MemoryStream ouput = new MemoryStream())
while (true)
int readLine = input.Read(buffer, 0, bufferSize);
if (readLine <= 0)
break;
byte[] temp = new byte[readLine];
Array.Copy(buffer, 0, temp, 0, readLine);
byte[] encrypt = rsa.Encrypt(temp, false);
ouput.Write(encrypt, 0, encrypt.Length);
encryContent = ouput.ToArray();
#endregion
return Convert.ToBase64String(encryContent);
/// <summary>
/// 通过私钥解密,分段解密
/// </summary>
/// <param name="content"></param>
/// <param name="privateKeyPath"></param>
/// <returns></returns>
public static string DecryptByPrivate(string privateKeyPath, string strDecryptString)
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(ReadFile(privateKeyPath));
byte[] encryptData = Convert.FromBase64String(strDecryptString);
//byte[] dencryContent = rsa.Decrypt(encryptData, false);
byte[] dencryContent = null;
#region 分段解密
if (encryptData == null || encryptData.Length <= 0)
throw new NotSupportedException();
int keySize = rsa.KeySize / 8;
byte[] buffer = new byte[keySize];
using (MemoryStream input = new MemoryStream(encryptData))
using (MemoryStream output = new MemoryStream())
while (true)
int readLine = input.Read(buffer, 0, keySize);
if (readLine <= 0)
break;
byte[] temp = new byte[readLine];
Array.Copy(buffer, 0, temp, 0, readLine);
byte[] decrypt = rsa.Decrypt(temp, false);
output.Write(decrypt, 0, decrypt.Length);
dencryContent = output.ToArray();
#endregion
return Encoding.UTF8.GetString(dencryContent);
/// <summary>
/// 读取文件
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string ReadFile(string filePath)
string content = "";
if (File.Exists(filePath))
content = File.ReadAllText(filePath);
byte[] mybyte = Encoding.UTF8.GetBytes(content);
content = Encoding.UTF8.GetString(mybyte);
return content;
/// <summary>
/// 将私钥转换成java所用的私钥字符串
/// </summary>
/// <param name="privateKeyPath">私钥文件路径</param>
/// <returns></returns>
public static string RSAPrivateKeyDotNet2Java(string privateKeyPath)
XmlDocument doc = new XmlDocument();
doc.LoadXml(ReadFile(privateKeyPath));
BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
return Convert.ToBase64String(serializedPrivateBytes);
/// <summary>
/// 将公钥转换成java所用的公钥字符串
/// </summary>
/// <param name="publicKeyPath">公钥路径</param>
/// <returns></returns>
public static string RSAPublicKeyDotNet2Java(string publicKeyPath)
XmlDocument doc = new XmlDocument();
doc.LoadXml(ReadFile(publicKeyPath));
BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
RsaKeyParameters pub = new RsaKeyParameters(false, m, p);
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
return Convert.ToBase64String(serializedPublicBytes);
2、java端代码
import java.io.*;
import java.util.Base64;
public class Base64Utils {
/** *//**
* 文件读取缓冲区大小
private static final int CACHE_SIZE = 1024;
/** *//**
* BASE64字符串解码为二进制数据
* @param base64
* @return
* @throws Exception
public static byte[] decode(String base64) throws Exception {
//return Base64.decode(base64.getBytes());
//Base64.getEncoder().encodeToString("在Java 8中,Base64编码已经成为Java类库的标准。".getBytes("utf-8"));
return Base64.getDecoder().decode(base64);
/** *//**
* 二进制数据编码为BASE64字符串
* @param bytes
* @return
* @throws Exception
public static String encode(byte[] bytes) throws Exception {
//return new String(Base64.encode(bytes));
return Base64.getEncoder().encodeToString(bytes);
/** *//**
* 将文件编码为BASE64字符串
* 大文件慎用,可能会导致内存溢出
* @param filePath 文件绝对路径
* @return
* @throws Exception
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
/** *//**
* BASE64字符串转回文件
* @param filePath 文件绝对路径
* @param base64 编码字符串
* @throws Exception
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
/** *//**
* 文件转换为二进制数组
* @param filePath 文件路径
* @return
* @throws Exception
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = null;
ByteArrayOutputStream out = null;
in = new FileInputStream(file);
out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
data = out.toByteArray();
}catch (Exception e){
e.printStackTrace();
}finally {
if (in != null){
in.close();
if (out != null){
out.close();
return data;
/** *//**
* 二进制数据写文件
* @param bytes 二进制数据
* @param filePath 文件生成目录
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
InputStream in = null;
OutputStream out = null;
in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
destFile.createNewFile();
out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
out.close();
in.close();
}catch (Exception e){
e.printStackTrace();
}finally {
if (in != null){
in.close();
if (out != null){
out.close();
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
* 非对称加密解密
public class RSAEncryptProvider {
* 加密算法RSA
public static final String KEY_ALGORITHM = "RSA";
* 签名算法
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
* 获取公钥的key
private static final String PUBLIC_KEY = "RSAPublicKey";
* 获取私钥的key
private static final String PRIVATE_KEY = "RSAPrivateKey";
* RSA最大加密明文大小
private static final int MAX_ENCRYPT_BLOCK = 117;
* RSA最大解密密文大小
private static final int MAX_DECRYPT_BLOCK = 128;
* 生成密钥对(公钥和私钥)
* @return
* @throws Exception
public static Map<String, Object> genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
* 用私钥对信息生成数字签名
* @param msg 已加密数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
public static String sign(String msg, String privateKey) throws Exception {
byte[] data = msg.getBytes();
byte[] keyBytes = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(data);
return Base64.getEncoder().encodeToString(signature.sign());
* 校验数字签名
* @param msg 已加密数据
* @param publicKey 公钥(BASE64编码)
* @param sign 数字签名
* @return
* @throws Exception
public static boolean verify(String msg, String publicKey, String sign)
throws Exception {
byte[] data = msg.getBytes();
byte[] keyBytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
return signature.verify(Base64.getDecoder().decode(sign));
* 私钥解密,进行分片解密,解密大文本
* @param encryptedDataStr 已加密数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
public static byte[] decryptByPrivateKey(byte[] encryptedDataStr, String privateKey)
throws Exception {
//byte[] encryptedData = Base64.getDecoder().decode(encryptedDataStr);
byte[] encryptedData = encryptedDataStr;
byte[] keyBytes = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.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(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
out.write(cache, 0, cache.length);
offSet = i * MAX_DECRYPT_BLOCK;
byte[] decryptedData = out.toByteArray();
out.close();
//return new String(decryptedData);
return decryptedData;
* 公钥解密,进行分片解密,解密大文本
* @param encryptedDataStr 已加密数据
* @param publicKey 公钥(BASE64编码)
* @return
* @throws Exception
public static byte[] decryptByPublicKey(byte[] encryptedDataStr, String publicKey)
throws Exception {
//byte[] encryptedData = Base64.getDecoder().decode(encryptedDataStr);
byte[] encryptedData = encryptedDataStr;
byte[] keyBytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicK);
int inputLen = encryptedData.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(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
out.write(cache, 0, cache.length);
offSet = i * MAX_DECRYPT_BLOCK;
byte[] decryptedData = out.toByteArray();
out.close();
//return new String(decryptedData);
return decryptedData;
* 公钥加密,进行分片加密,加密大文本
* @param data 源数据
* @param publicKey 公钥(BASE64编码)
* @return
* @throws Exception
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.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, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
out.write(cache, 0, cache.length);
offSet = i * MAX_ENCRYPT_BLOCK;
byte[] encryptedData = out.toByteArray();
out.close();
//String encryptedDataStr = Base64.getEncoder().encodeToString(encryptedData);
return encryptedData;
* 私钥加密,进行分片加密,加密大文本
* @param data 源数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateK);
int inputLen = data.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, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
out.write(cache, 0, cache.length);
offSet = i * MAX_ENCRYPT_BLOCK;
byte[] encryptedData = out.toByteArray();
out.close();
//String encryptedDataStr = Base64.getEncoder().encodeToString(encryptedData);
return encryptedData;
* 获取私钥
* @param keyMap 密钥对
* @return
* @throws Exception
public static String getPrivateKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return Base64.getEncoder().encodeToString(key.getEncoded());
* 获取公钥
* @param keyMap 密钥对
* @return
* @throws Exception
public static String getPublicKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Base64.getEncoder().encodeToString(key.getEncoded());
* 通过C#的RSACryptoServiceProvider类产生的公钥进行转换成java的公钥
* @param modulus
* @param exponent
* @return
public static PublicKey getPublicKey(String modulus, String exponent) {
try {
byte[] m = Base64Utils.decode(modulus);
byte[] e = Base64Utils.decode(exponent);
BigInteger b1 = new BigInteger(1,m);
BigInteger b2 = new BigInteger(1,e);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
* 通过C#的RSACryptoServiceProvider类产生的私钥进行转换成java的私钥
* @param modulus
* @param privateExponent
* @return
public PrivateKey getPrivateKey(String modulus,String privateExponent) throws Exception {
BigInteger m = new BigInteger(modulus);
BigInteger e = new BigInteger(privateExponent);
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m,e);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
public static void main(String[] args) throws Exception {
//通过C#公钥文件转换的java公钥字符串
String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYyiJ5biYwnsRE2RgqI6rEsmxySuoxRAKBPkxZwBN2+NTb4KNr8JUtaD8Fj+NV1+eEspm8MT519PJRwCxOGxf/qU3CqCnTwxoc3MrN3MwxeQ1FC2wZkEm8y8FZKWd84udULxML+7ao1bCYWeDerd2MBWvKBpEqoG28jY3yY1AGbQIDAQAB";
//通过C#私钥文件转换的java私钥字符串
String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJjKInluJjCexETZGCojqsSybHJK6jFEAoE+TFnAE3b41Nvgo2vwlS1oPwWP41XX54SymbwxPnX08lHALE4bF/+pTcKoKdPDGhzcys3czDF5DUULbBmQSbzLwVkpZ3zi51QvEwv7tqjVsJhZ4N6t3YwFa8oGkSqgbbyNjfJjUAZtAgMBAAECgYAZ5PAQymU4ij/TN0PMKH1Rlregayfjr5YJF2jTMSVbXXKdzSWFLqHpryg3JhquOsgnCinZ5jKixR+oUTxxBFB9pcduLPpiQ+91hhebSGoR/09MgqFFg0Qx5/0dAgl0GpFGXPi3B6AM/8IJ6aGtQd/SIyo7LcRU+824kVufo/Z9IQJBAMYQq4lYpJFAKPvfJEstT5v02mHr01h7pNOBYkloQs2ZShTDfXicInzVmDaQ4CXCrTZC7Ud3pJD4my//1a+FelUCQQDFey8gpeqqAnwDd6CgIhCktjvr3OFGrZdazg8A2oHg/77GRichstx19wMYgx5Tb/Ezx+9wWqog0eRgkfAunSO5AkByLBXVnGVw3T1Cw4RWWY40Zlakb55quQtwaHrRueoYPi63/WCMb+RpdW7CtYyf97KFPtssgUk50DUU3DK/dP/pAkAgz8PXz9l6n+kNBm5YzPAo/eJc4RlJDgSs4LnbcXLM+JExDmzoC3jX3M/V3ctHH71a1ihxaY8E3vrsFLNse015AkBV7cm3Z2DU9mJkYLfLR2oT0T5d6RQpGWs8hJlvVFZC6q904+1uRJq8T3zyUHvEeF3xa1C7ONd4Fm/rNf7e1/5F";
//公钥加密
String data = testPublicEncrypt("abc12345555555555554444444444" +
"4444444444444444444444444444444444444" +
"44444444444444444444444444444444444444" +
"44444444444444444444444444444444444444" +
"44444444444444444444444444444444444" +
"444444444444444444444444444444444444" +
"444444444444444444444444444444444444" +
"555555555555555555555555555555555" +
"5555555555555555555555555555555",publicKey);
System.out.println(data);
//私钥解密
data = testPrivateDencrypt(data,privateKey);
System.out.println(data);
//私钥加密
data = testPrivateEncrypt("abc12345555555555554444444444" +
"4444444444444444444444444444444444444" +
"44444444444444444444444444444444444444" +
"44444444444444444444444444444444444444" +
"44444444444444444444444444444444444" +
"444444444444444444444444444444444444" +
"444444444444444444444444444444444444" +
"555555555555555555555555555555555" +
"5555555555555555555555555555555",privateKey);
System.out.println(data);
//公钥解密
data = testPublicDecrypt(data,publicKey);
System.out.println(data);
* 测试公钥加密
* @param content 要加密的字符串
* @return
* @throws Exception
private static String testPublicEncrypt(String content,String publicKey)throws Exception{
byte[] entryData = RSAEncryptProvider.encryptByPublicKey(content.getBytes("UTF-8"), publicKey);
return Base64Utils.encode(entryData);
* 测试私钥解密
* @param content
* @return
* @throws Exception
private static String testPrivateDencrypt(String content,String privateKey)throws Exception{
byte[] dentryData = RSAEncryptProvider.decryptByPrivateKey(Base64Utils.decode(content),privateKey);
return new String(dentryData,"UTF-8");
* 测试通过私钥加密
* @param content
* @param privateKey
* @return
* @throws Exception
private static String testPrivateEncrypt(String content,String privateKey)throws Exception{
byte[] entryData = RSAEncryptProvider.encryptByPrivateKey(content.getBytes("UTF-8"), privateKey);
return Base64Utils.encode(entryData);
* 测试通过公钥解密
* @param content
* @param publicKey
* @return
* @throws Exception
private static String testPublicDecrypt(String content,String publicKey)throws Exception{
byte[] dentryData = RSAEncryptProvider.decryptByPublicKey(Base64Utils.decode(content),publicKey);
return new String(dentryData,"UTF-8");
代码下载地址:https://download.csdn.net/download/lengyue2015/10930794
Java中有很好的rsa加密与解密类库,同样这些类库也被迁移到了Android的api中,但稍有不同,在java中的base64编码和解码api与Android稍有不同,Android只是简化了一部分操作。如下就将Android中常用的加密和解密的方法总结
import java.math.BigInteger;
import java.util.Scanner;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.interfaces.R.
今天大姚给大家分享一款C#版开源、免费的Bouncy Castle密码库:BouncyCastle。BouncyCastle是一款C#版开源、免费的Bouncy Castle密码库,开发人员可以通过该项目在他们的 C# 应用程序中使用 Bouncy Castle 提供的各种密码学功能,从而加强数据的安全性和保护隐私信息。Bouncy Castle是一个流行的密码学库,提供了广泛的密码算法和协议的实现。它由澳大利亚注册的慈善组织“Bouncy Castle军团”开发,旨在提供可靠而安全的加密解决方案。
I would like to generate private key in java, save it as a 64 base encoded string in some fileand then encrypt some phrase in C# using this saved file.I know to generate keys in java and encode it wit...
KeyPairGenerator 类用于生成公钥和私钥对。密钥对生成器是使用 getInstance 工厂方法(返回一个给定类的实例的静态方法)构造的。
特定算法的密钥对生成器可以创建能够与此算法一起使用的公钥/私钥对。它还可以将特定于算法的参数与每个生成的密钥关联。
有两种生成密钥对的方式:与算法无关的方式和特定于算法的方式。两种方式的唯一区别在于...
byte[] inputArray = Convert.FromBase64String(strinput);
byte[] key = Encoding.UTF8.GetBytes(strkey);
RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作。 RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一。RSA的安全性依赖于大数的因子分解,但并没有从理论上证明破译RSA的难度与大数分解难度等价。
.NET提供常用的加密算法类,支持RSA的类是RSACryptoServiceProvid...
也是按照data 16位来分组,第一组数据与初始化向量IV异或后的结果进行加密,密得到第一组密文C1(初始化向量I为全零),第二组数据与第一组的加密结果C1异或以后的结果进行加密,得到第二组密文C2...... 最后C1C2C3......Cn即为加密结果。我们在实现可用data字节的形式,即秘钥Data为16位,加密数据Data需为16的整数倍,这两点很重要。CBC(密文分组链接方式),它的实现机制使加密的各段数据之间有了联系。观察第一块,和第三块,皆为明文块0,相同的输入产生相同的输出。
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.se
其核心思想是选择两个大素数p和q,计算它们的乘积n=p*q,并选择一个整数e作为公钥,满足e与(p-1)(q-1)互质。运行该程序后,将会生成一个名为public.key的文件和一个名为private.key的文件,其中public.key文件保存公钥,private.key文件保存私钥。这将把private.key和public.key转换为private.asc和public.asc文件,其中private.asc和public.asc文件就是RSA私钥和公钥的.asc形式。最后,输出解密后的明文。
蒜老大和油大叔想秘密研制新菜式,但是因为特殊原因,两人不能直接见面。通过以下图示方法分别处理食材,然后让外卖小哥跑腿送给对方,然后二次加工,做出新菜式,这样隐秘安全的研制了新菜式。在DH算法中,排骨是公开的公钥,蒜是蒜老大的私人密钥,油是油大叔的私人密钥。黑客没有密钥,即使他捕获了中间传递的公钥也不知道如何处理排骨。这样就保证了安全性。
最近工作中,有一个第三方接口,需要对接口参数的部分数据进行RSA加密,接口文档中提供了一个使用Java写的RSA公钥。我也是第一次接触RSA加密算法,在查阅资料中发现,使用RSA加密,同一个数据,加密的结果是不一样的。在使用C#实现RSA加密过程中,一边查资料,一边摸索,也浪费了不少的时间。第一版代码(能加密,但接口方无法解密)