RSA加解密工具类

Java 实现

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.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

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

/**
* RSA 加解密工具类
*
* @author ZT ** 秘钥对可以在在线生成网站获取(http://web.chacuo.net/netrsakeypair)
* 在线生成非对称加密公钥私钥对、在线生成公私钥对、RSA Key pair create、生成RSA密钥对 选择秘钥位数:1024
* 秘钥格式:PKCS#8
*
*/
public class RSACryptUtil {

/**
* 获取公钥
*
* @return
*/
public static String getPubliceKey() {
// rsa_public_key.pem内容
String publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLK6Hw+RE///HKM1zukQTao/ybdm7RpbQ2bvDTHtDWysx46vIC4wosNZwP3bmxEpzq8f6B3jZeqtcoxCWfVNi1S1FNjyKpC55xmjzrCTNUe9mSgKwyoGU/kHpR4FyXTgP02XkuDXXJrODlDQQg0UNrgbkA9BboLxdxkZLsp1tshQIDAQAB";

publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCssD8md1gI0kA6TVOQtggtvBrSH+N/q5/+grs7LSXT2P7UzVeuN1SdETZdt+386D/3K/k8aJmQILc0HoEjHUIopbdEP318odCnmytveenZCdCtq8/9n1HUcmAUDEVS03F6z51DUvjMfKKSqdc66vhagVciamOmFQNdZJu3jZXjlQIDAQAB";
return publickey;
}

/**
* 获取私钥
*
* @return
*/
public static String getPrivateKey() {
String privatekey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMsrofD5ET//8cozXO6RBNqj/Jt2btGltDZu8NMe0NbKzHjq8gLjCiw1nA/dubESnOrx/oHeNl6q1yjEJZ9U2LVLUU2P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dDYG0b7qc8wC2+rdWAnJ0Xe8Dk9heaY+MdS188L3u7sqECQQDVIpDdyLeKoI58NFjPiDZeCzJaEl8Vd5K93qTA+zpCoOlqqDFrPgwMqLczCVJhmtAriHRXaC2vw1TCsrxPSOSNAkEAz2tBieV+FVU0JoaAYcy88/xPeBaBCnVohdjjrKjhsXpXO6cbQsmr/bNMqPykemiTuXpixXBaL9FmRshrK86tKQJAGuRSnPkvV1lswPUl44GPQoxtHPpGbwH4TOajqQnJzxBYgzGXkq1wfcRn4ROjBlevPl7oNwMZCJ0/u5Urt2E+HQJBAJ8cFrVSPyrcJlobOSZMqPG8rbVgBfLg56ItI1FSZ3b+cyZGZOoRzAacYQUMcJuZ1yAj2tq7+eLOjddkbJm5PCkCQC9rqJpYYt+ZUoPb4MfQPMRlhsNVIsCflNjYYJMbtP8aISjxkBXzI1f+9EbC/AzXcbc7Xhhad3vq2VA4Gnvmy8w=";
return privatekey;
}

private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); // 用于封装随机产生的公钥与私钥

public static void main(String[] args) throws Exception {
// 生成公钥和私钥
genKeyPair();
// 加密字符串
String message = "aaabbbb";
System.out.println("随机生成的公钥为:" + keyMap.get(0));
System.out.println("随机生成的私钥为:" + keyMap.get(1));
String messageEn = encrypt(message, keyMap.get(0));
System.out.println(message + "\t加密后的字符串为:" + messageEn);
String messageDe = decrypt(messageEn, keyMap.get(1));
System.out.println("还原后的字符串为:" + messageDe);
}

/**
* 随机生成密钥对
*
* @throws NoSuchAlgorithmException
*/
public static void genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(1024, new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// 得到私钥字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// 将公钥和私钥保存到Map
keyMap.put(0, publicKeyString); // 0表示公钥
keyMap.put(1, privateKeyString); // 1表示私钥
}

/**
* RSA公钥加密
*
* @param str 加密字符串
* @param publicKey 公钥
* @return 密文
* @throws Exception 加密过程中的异常信息
*/
public static String encrypt(String str, String publicKey) throws Exception {
// base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(decoded));
// RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}

/**
* RSA私钥解密
* @param str 加密字符串
* @param privateKey 私钥
* @return 铭文
* @throws Exception 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception {
// 64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
// base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
.generatePrivate(new PKCS8EncodedKeySpec(decoded));
// RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
}

}

C# 实现

using System;

using System.Collections.Generic;

using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace BS.Data
{
/// <summary>
/// 类名:RSACrypt
/// 功能:RSA加密、解密、签名、验签
/// </summary>
public class RSACrypt
{

/***
* 秘钥对可以在在线生成网站获取(http://web.chacuo.net/netrsakeypair)
* 在线生成非对称加密公钥私钥对、在线生成公私钥对、RSA Key pair create、生成RSA密钥对
* 选择秘钥位数:1024
* 秘钥格式:PKCS#8
*/

/// <summary>
/// 获取公钥
/// </summary>
/// <returns></returns>
public static string getPubliceKey()
{
//rsa_public_key.pem内容
string publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLK6Hw+RE///HKM1zukQTao/ybdm7RpbQ2bvDTHtDWysx46vIC4wosNZwP3bmxEpzq8f6B3jZeqtcoxCWfVNi1S1FNjyKpC55xmjzrCTNUe9mSgKwyoGU/kHpR4FyXTgP02XkuDXXJrODlDQQg0UNrgbkA9BboLxdxkZLsp1tshQIDAQAB";

publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCssD8md1gI0kA6TVOQtggtvBrSH+N/q5/+grs7LSXT2P7UzVeuN1SdETZdt+386D/3K/k8aJmQILc0HoEjHUIopbdEP318odCnmytveenZCdCtq8/9n1HUcmAUDEVS03F6z51DUvjMfKKSqdc66vhagVciamOmFQNdZJu3jZXjlQIDAQAB";
return publickey;
}

/// <summary>
/// 获取私钥
/// </summary>
/// <returns></returns>
public static string getPrivateKey()
{
string privatekey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMsrofD5ET//8cozXO6RBNqj/Jt2btGltDZu8NMe0NbKzHjq8gLjCiw1nA/dubESnOrx/oHeNl6q1yjEJZ9U2LVLUU2PIqkLnnGaPOsJM1R72ZKArDKgZT+QelHgXJdOA/TZeS4Ndcms4OUNBCDRQ2uBuQD0FugvF3GRkuynW2yFAgMBAAECgYEAwlEMBOaiqfyIbCTt+Dp5UwhOvP3sBdWfZAR9jt7FTPoP0IKdT0eI3jmz9rTROlub+1XSXrGCfM6XFKVtelNzI1PqEB+QomBhZtwhzSmxrFWCg4q2oeZsqROKlDBDhV8pFhGX9Euo4HxsNJWLcA4Ngt6ZIwV/Drj7uOEA06UxFyECQQD76Fl4rKPOdzC0RBtRZEqxmC32nikwAWz2FqinNzee+tiMeF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8cFrVSPyrcJlobOSZMqPG8rbVgBfLg56ItI1FSZ3b+cyZGZOoRzAacYQUMcJuZ1yAj2tq7+eLOjddkbJm5PCkCQC9rqJpYYt+ZUoPb4MfQPMRlhsNVIsCflNjYYJMbtP8aISjxkBXzI1f+9EbC/AzXcbc7Xhhad3vq2VA4Gnvmy8w=";
return privatekey;
}

/// <summary>
/// 签名
/// </summary>
/// <param name="content">待签名字符串</param>
/// <param name="privateKey">私钥</param>
/// <param name="input_charset">编码格式</param>
/// <returns>签名后字符串</returns>
public static string sign(string content, string privateKey, string input_charset)
{
byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content);
RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
SHA1 sh = new SHA1CryptoServiceProvider();
byte[] signData = rsa.SignData(Data, sh);
return Convert.ToBase64String(signData);
}

/// <summary>
/// 验签
/// </summary>
/// <param name="content">待验签字符串</param>
/// <param name="signedString">签名</param>
/// <param name="publicKey">公钥</param>
/// <param name="input_charset">编码格式</param>
/// <returns>true(通过),false(不通过)</returns>
public static bool verify(string content, string signedString, string publicKey, string input_charset)
{
bool result = false;
byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content);
byte[] data = Convert.FromBase64String(signedString);
RSAParameters paraPub = ConvertFromPublicKey(publicKey);
RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
rsaPub.ImportParameters(paraPub);
SHA1 sh = new SHA1CryptoServiceProvider();
result = rsaPub.VerifyData(Data, sh, data);
return result;
}

/// <summary>
/// 加密 (注意:同一个数据每次加密生成的结果数据不一样,私钥都可以完成解密)
/// </summary>
/// <param name="resData">需要加密的字符串</param>
/// <param name="publicKey">公钥</param>
/// <param name="input_charset">编码格式</param>
/// <returns>明文</returns>
public static string encryptData(string resData, string publicKey, string input_charset)
{
byte[] DataToEncrypt = Encoding.ASCII.GetBytes(resData);
string result = encrypt(DataToEncrypt, publicKey, input_charset);
return result;
}

/// <summary>
/// 解密
/// </summary>
/// <param name="resData">加密字符串</param>
/// <param name="privateKey">私钥</param>
/// <param name="input_charset">编码格式</param>
/// <returns>明文</returns>
public static string decryptData(string resData, string privateKey, string input_charset)
{
byte[] DataToDecrypt = Convert.FromBase64String(resData);
string result = "";
for (int j = 0; j < DataToDecrypt.Length / 128; j++)
{
byte[] buf = new byte[128];
for (int i = 0; i < 128; i++)
{

buf[i] = DataToDecrypt[i + 128 * j];
}
result += decrypt(buf, privateKey, input_charset);
}
return result;
}

private static string encrypt(byte[] data, string publicKey, string input_charset)
{
RSACryptoServiceProvider rsa = DecodePemPublicKey(publicKey);
SHA1 sh = new SHA1CryptoServiceProvider();
byte[] result = rsa.Encrypt(data, false);

return Convert.ToBase64String(result);
}

private static string decrypt(byte[] data, string privateKey, string input_charset)
{
string result = "";
RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
SHA1 sh = new SHA1CryptoServiceProvider();
byte[] source = rsa.Decrypt(data, false);
char[] asciiChars = new char[Encoding.GetEncoding(input_charset).GetCharCount(source, 0, source.Length)];
Encoding.GetEncoding(input_charset).GetChars(source, 0, source.Length, asciiChars, 0);
result = new string(asciiChars);
return result;
}

private static RSACryptoServiceProvider DecodePemPublicKey(String pemstr)
{
byte[] pkcs8publickkey;
pkcs8publickkey = Convert.FromBase64String(pemstr);
if (pkcs8publickkey != null)
{
RSACryptoServiceProvider rsa = DecodeRSAPublicKey(pkcs8publickkey);
return rsa;
}
else
return null;
}

private static RSACryptoServiceProvider DecodePemPrivateKey(String pemstr)
{
byte[] pkcs8privatekey;
pkcs8privatekey = Convert.FromBase64String(pemstr);
if (pkcs8privatekey != null)
{
RSACryptoServiceProvider rsa = DecodePrivateKeyInfo(pkcs8privatekey);
return rsa;
}
else
return null;
}

private static RSACryptoServiceProvider DecodePrivateKeyInfo(byte[] pkcs8)
{
byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
byte[] seq = new byte[15];

MemoryStream mem = new MemoryStream(pkcs8);
int lenstream = (int)mem.Length;
BinaryReader binr = new BinaryReader(mem);
byte bt = 0;
ushort twobytes = 0;

try
{
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130)
binr.ReadByte();
else if (twobytes == 0x8230)
binr.ReadInt16();
else
return null;

bt = binr.ReadByte();
if (bt != 0x02)
return null;

twobytes = binr.ReadUInt16();

if (twobytes != 0x0001)
return null;

seq = binr.ReadBytes(15);
if (!CompareBytearrays(seq, SeqOID))
return null;

bt = binr.ReadByte();
if (bt != 0x04)
return null;

bt = binr.ReadByte();
if (bt == 0x81)
binr.ReadByte();
else
if (bt == 0x82)
binr.ReadUInt16();

byte[] rsaprivkey = binr.ReadBytes((int)(lenstream - mem.Position));
RSACryptoServiceProvider rsacsp = DecodeRSAPrivateKey(rsaprivkey);
return rsacsp;
}

catch (Exception)
{
return null;
}

finally { binr.Close(); }
}

private static bool CompareBytearrays(byte[] a, byte[] b)
{
if (a.Length != b.Length)
return false;
int i = 0;
foreach (byte c in a)
{
if (c != b[i])
return false;
i++;
}
return true;
}

private static RSACryptoServiceProvider DecodeRSAPublicKey(byte[] publickey)
{
byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
byte[] seq = new byte[15];
MemoryStream mem = new MemoryStream(publickey);
BinaryReader binr = new BinaryReader(mem);
byte bt = 0;
ushort twobytes = 0;

try
{

twobytes = binr.ReadUInt16();
if (twobytes == 0x8130)
binr.ReadByte();
else if (twobytes == 0x8230)
binr.ReadInt16();
else
return null;

seq = binr.ReadBytes(15);
if (!CompareBytearrays(seq, SeqOID))
return null;

twobytes = binr.ReadUInt16();
if (twobytes == 0x8103)
binr.ReadByte();
else if (twobytes == 0x8203)
binr.ReadInt16();
else
return null;

bt = binr.ReadByte();
if (bt != 0x00)
return null;

twobytes = binr.ReadUInt16();
if (twobytes == 0x8130)
binr.ReadByte();
else if (twobytes == 0x8230)
binr.ReadInt16();
else
return null;

twobytes = binr.ReadUInt16();
byte lowbyte = 0x00;
byte highbyte = 0x00;

if (twobytes == 0x8102)
lowbyte = binr.ReadByte();
else if (twobytes == 0x8202)
{
highbyte = binr.ReadByte();
lowbyte = binr.ReadByte();
}
else
return null;
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
int modsize = BitConverter.ToInt32(modint, 0);

byte firstbyte = binr.ReadByte();
binr.BaseStream.Seek(-1, SeekOrigin.Current);

if (firstbyte == 0x00)
{
binr.ReadByte();
modsize -= 1;
}

byte[] modulus = binr.ReadBytes(modsize);

if (binr.ReadByte() != 0x02)
return null;
int expbytes = (int)binr.ReadByte();
byte[] exponent = binr.ReadBytes(expbytes);

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters();
RSAKeyInfo.Modulus = modulus;
RSAKeyInfo.Exponent = exponent;
RSA.ImportParameters(RSAKeyInfo);
return RSA;
}
catch (Exception)
{
return null;
}

finally { binr.Close(); }
}

private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

MemoryStream mem = new MemoryStream(privkey);
BinaryReader binr = new BinaryReader(mem);
byte bt = 0;
ushort twobytes = 0;
int elems = 0;
try
{
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130)
binr.ReadByte();
else if (twobytes == 0x8230)
binr.ReadInt16();
else
return null;

twobytes = binr.ReadUInt16();
if (twobytes != 0x0102)
return null;
bt = binr.ReadByte();
if (bt != 0x00)
return null;

elems = GetIntegerSize(binr);
MODULUS = binr.ReadBytes(elems);

elems = GetIntegerSize(binr);
E = binr.ReadBytes(elems);

elems = GetIntegerSize(binr);
D = binr.ReadBytes(elems);

elems = GetIntegerSize(binr);
P = binr.ReadBytes(elems);

elems = GetIntegerSize(binr);
Q = binr.ReadBytes(elems);

elems = GetIntegerSize(binr);
DP = binr.ReadBytes(elems);

elems = GetIntegerSize(binr);
DQ = binr.ReadBytes(elems);

elems = GetIntegerSize(binr);
IQ = binr.ReadBytes(elems);

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAparams = new RSAParameters();
RSAparams.Modulus = MODULUS;
RSAparams.Exponent = E;
RSAparams.D = D;
RSAparams.P = P;
RSAparams.Q = Q;
RSAparams.DP = DP;
RSAparams.DQ = DQ;
RSAparams.InverseQ = IQ;
RSA.ImportParameters(RSAparams);
return RSA;
}
catch (Exception)
{
return null;
}
finally { binr.Close(); }
}

private static int GetIntegerSize(BinaryReader binr)
{
byte bt = 0;
byte lowbyte = 0x00;
byte highbyte = 0x00;
int count = 0;
bt = binr.ReadByte();
if (bt != 0x02)
return 0;
bt = binr.ReadByte();

if (bt == 0x81)
count = binr.ReadByte();
else
if (bt == 0x82)
{
highbyte = binr.ReadByte();
lowbyte = binr.ReadByte();
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
count = BitConverter.ToInt32(modint, 0);
}
else
{
count = bt;
}

while (binr.ReadByte() == 0x00)
{
count -= 1;
}
binr.BaseStream.Seek(-1, SeekOrigin.Current);
return count;
}

private static RSAParameters ConvertFromPublicKey(string pemFileConent)
{

byte[] keyData = Convert.FromBase64String(pemFileConent);
if (keyData.Length < 162)
{
throw new ArgumentException("pem file content is incorrect.");
}
byte[] pemModulus = new byte[128];
byte[] pemPublicExponent = new byte[3];
Array.Copy(keyData, 29, pemModulus, 0, 128);
Array.Copy(keyData, 159, pemPublicExponent, 0, 3);
RSAParameters para = new RSAParameters();
para.Modulus = pemModulus;
para.Exponent = pemPublicExponent;
return para;
}

private static RSAParameters ConvertFromPrivateKey(string pemFileConent)
{
byte[] keyData = Convert.FromBase64String(pemFileConent);
if (keyData.Length < 609)
{
throw new ArgumentException("pem file content is incorrect.");
}

int index = 11;
byte[] pemModulus = new byte[128];
Array.Copy(keyData, index, pemModulus, 0, 128);

index += 128;
index += 2;
byte[] pemPublicExponent = new byte[3];
Array.Copy(keyData, index, pemPublicExponent, 0, 3);

index += 3;
index += 4;
byte[] pemPrivateExponent = new byte[128];
Array.Copy(keyData, index, pemPrivateExponent, 0, 128);

index += 128;
index += ((int)keyData[index + 1] == 64 ? 2 : 3);
byte[] pemPrime1 = new byte[64];
Array.Copy(keyData, index, pemPrime1, 0, 64);

index += 64;
index += ((int)keyData[index + 1] == 64 ? 2 : 3);//346
byte[] pemPrime2 = new byte[64];
Array.Copy(keyData, index, pemPrime2, 0, 64);

index += 64;
index += ((int)keyData[index + 1] == 64 ? 2 : 3);
byte[] pemExponent1 = new byte[64];
Array.Copy(keyData, index, pemExponent1, 0, 64);

index += 64;
index += ((int)keyData[index + 1] == 64 ? 2 : 3);
byte[] pemExponent2 = new byte[64];
Array.Copy(keyData, index, pemExponent2, 0, 64);

index += 64;
index += ((int)keyData[index + 1] == 64 ? 2 : 3);
byte[] pemCoefficient = new byte[64];
Array.Copy(keyData, index, pemCoefficient, 0, 64);

RSAParameters para = new RSAParameters();
para.Modulus = pemModulus;
para.Exponent = pemPublicExponent;
para.D = pemPrivateExponent;
para.P = pemPrime1;
para.Q = pemPrime2;
para.DP = pemExponent1;
para.DQ = pemExponent2;
para.InverseQ = pemCoefficient;
return para;
}

}

}

原文地址:https://www.cnblogs.com/zt2710/p/12112471.html

时间: 2024-10-11 09:33:14

RSA加解密工具类的相关文章

C#的DES文件加解密工具类

using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; namespace www.xinduofen.com { class FileDES { /// /// 加密文件随机数生成 /// private static RandomNumberGenerator rand = new RNGCryptoServi

C# 中使用 RSA加解密算法

一.什么是RSA RSA公开密钥密码体制.所谓的公开密钥密码体制就是使用不同的加密密钥与解密密钥,是一种“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制. 在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息,而解密密钥(即秘密密钥)SK是需要保密的.加密算法E和解密算法D也都是公开的.虽然密钥SK是由公开密钥PK决定的,但却不能根据PK计算出SK.正是基于这种理论,1978年出现了著名的RSA算法,它通常是先生成一对RSA 密钥,其中之一是保密密钥,由用户保存:另一个为公开密钥

全面解决.Net与Java互通时的RSA加解密问题,使用PEM格式的密钥文件

一.缘由 RSA是一种常用的非对称加密算法.所以有时需要在不用编程语言中分别使用RSA的加密.解密.例如用Java做后台服务端,用C#开发桌面的客户端软件时.由于 .Net.Java 的RSA类库存在很多细节区别,尤其是它们支持的密钥格式不同.导致容易出现“我加密的数据对方不能解密,对方加密的数据我不能解密,但是自身是可以正常加密解密”等情况.虽然网上已经有很多文章讨论 .Net与Java互通的RSA加解密,但是存在不够全面.需要第三方dll.方案复杂 等问题.于是我仔细研究了这一课题,得到了一

java rsa加解密算法的实现

RSAUtils:RSA加解密的实现 package com.rsa.test; import java.io.ByteArrayOutputStream; import java.nio.charset.Charset; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import jav

openssl - rsa加解密例程

原文链接: http://www.cnblogs.com/cswuyg/p/3187462.html openssl是可以很方便加密解密的库,可以使用它来对需要在网络中传输的数据加密.可以使用非对称加密:公钥加密,私钥解密.openssl提供了对RSA的支持,但RSA存在计算效率低的问题,所以一般的做法是使用对称密钥加密数据,然后再把这个只在当前有效的临时生成的对称密钥用非对称密钥的公钥加密之后传递给目标方,目标方使用约定好的非对称密钥中的私钥解开,得到数据加密的密钥,再进行数据解密,得到数据,

RSA 加解密 秘钥对说明

rsa非对称加密, 加解密需要不同的秘钥,称作一对. rsa加解密分两种,第一:公钥加密私钥解密.第二:私钥加密公钥解密. 需要注意的是,公加私解得到的密文是变化的,而私加公解的得到的密文是固定的. 生成密匙对需要设置一个长度,常用的设置为1024,或者2048.注意,不同长度的密匙,能够加密的明文最长度是有限制的.说明如下: 1024的情况: 加密时,明文最大长度: 1024/8 - 11 = 117   ,因此需要对明文做117字节长度的分片加密,再拼接. 解密时,密文最大长度:1024/8

【转】 Java 进行 RSA 加解密时不得不考虑到的那些事儿

[转] Java 进行 RSA 加解密时不得不考虑到的那些事儿 1. 加密的系统不要具备解密的功能,否则 RSA 可能不太合适 公钥加密,私钥解密.加密的系统和解密的系统分开部署,加密的系统不应该同时具备解密的功能,这样即使黑客攻破了加密系统,他拿到的也只是一堆无法破解的密文数据.否则的话,你就要考虑你的场景是否有必要用 RSA 了. 2. 可以通过修改生成密钥的长度来调整密文长度 生成密文的长度等于密钥长度.密钥长度越大,生成密文的长度也就越大,加密的速度也就越慢,而密文也就越难被破解掉.著名

PHP RSA加解密示例(转)

1.生成密钥和公钥 开始前需要准备openssl环境 linux 需要安装openssl工具包,传送门http://www.openssl.org/source/ window 下需要安装openssl的程序,传送门http://slproweb.com/products/Win32OpenSSL.html 如果不想安装,可以用本例提供的密钥和公钥进行测试. 密钥生成 openssl genrsa 用于生成rsa私钥文件,生成是可以指定私钥长度和密码保护,具体参数请参考文档. openssl g

java RSA加解密以及用途

在公司当前版本的中间件通信框架中,为了防止非授权第三方和到期客户端的连接,我们通过AES和RSA两种方式的加解密策略进行认证.对于非对称RSA加解密,因为其性能耗费较大,一般仅用于认证连接,不会用于每次报文本身的加解密(这一般使用AES/DES加密),对于较为安全的支付通道,则一般是约定定期交换加解密密钥,交换过程本身的报文则是通过RSA进行加解密的.这样就在单纯的对称加密的基础上提供了更好的保障,只要签名复杂,定期的更新足以使得破坏的成本高昂到超过破解的成本. 一般来说,公钥会发布给客户端,客