Ⅰ java通过RSA算法获取公私钥对 将公钥提供出去 如何获取字符串的公钥
直接将公匙BYTE数组转换为16进制的串啊
private static char hexTable[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static String toHexString(byte bytes[])
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++)
{
char chars[] = new char[2];
int d = (bytes[i] & 240) >> 4;
int m = bytes[i] & 15;
chars[0] = hexTable[d];
chars[1] = hexTable[m];
sb.append(chars);
}
return sb.toString();
}
Ⅱ java生成rsa密钥,c++可以直接使用密钥解密吗
可以的,RSA加密解密有一套规则的,不同的语言都会遵循,只是实现的方式不一样。
用对应的的公钥就可以进行解密
Ⅲ Java生成的RSA密钥对,用C#加密解密,怎么弄
http://davenzeng.blog.51cto.com/3896952/989634看下这个对你有没有帮助
Ⅳ c#怎么调用java生成的RSA 公钥进行加密
.NET无法调用JAVA产生的RSA公钥,必须将RSA算法在.NET里面重写才行,在.NET里面RSA的公钥长度是128位的,但是你给出的JAVA公钥却是159位长度,非常的不标准,公钥长度不满足128的肯定无法给.NET使用。
这里最多帮做个对应解析,数据是肯定无法用的:
将java的RSA公钥最后四个字母AQAB分割开,用.NET的xml格式表示就是
<RSAKeyValue><Molus>
/qp
jLFfDCu3qytxf+/IoCYE
+Hf4hsEDUKV2kkhRJsnwwID</Molus><Exponent>AQAB</Exponent>
</RSAKeyValue>
这里的数据都是用的BASE64编码,你用BASE64解码后可以得到byte[],就可以看到密钥长度了,实际密钥要转换为BigInteger后才能参与RSA核心运算
Ⅳ Java 第三方公钥 RSA加密求助
下面是RSA加密代码。
/**
* RSA算法,实现数据的加密解密。
* @author ShaoJiang
*
*/
public class RSAUtil {
private static Cipher cipher;
static{
try {
cipher = Cipher.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
/**
* 生成密钥对
* @param filePath 生成密钥的路径
* @return
*/
public static Map<String,String> generateKeyPair(String filePath){
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 密钥位数
keyPairGen.initialize(1024);
// 密钥对
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//得到公钥字符串
String publicKeyString = getKeyString(publicKey);
//得到私钥字符串
String privateKeyString = getKeyString(privateKey);
//将密钥对写入到文件 想学习更多加我q u N 前面是二五七 中间是014后面是001
FileWriter pubfw = new FileWriter(filePath+"/publicKey.keystore");
FileWriter prifw = new FileWriter(filePath+"/privateKey.keystore");
BufferedWriter pubbw = new BufferedWriter(pubfw);
BufferedWriter pribw = new BufferedWriter(prifw);
pubbw.write(publicKeyString);
pribw.write(privateKeyString);
pubbw.flush();
pubbw.close();
pubfw.close();
pribw.flush();
pribw.close();
prifw.close();
//将生成的密钥对返回
Map<String,String> map = new HashMap<String,String>();
map.put("publicKey",publicKeyString);
map.put("privateKey",privateKeyString);
return map;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 得到公钥
*
* @param key
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 得到私钥
*
* @param key
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 得到密钥字符串(经过base64编码)
*
* @return
*/
public static String getKeyString(Key key) throws Exception {
byte[] keyBytes = key.getEncoded();
String s = (new BASE64Encoder()).encode(keyBytes);
return s;
}
/**
* 使用公钥对明文进行加密,返回BASE64编码的字符串
* @param publicKey
* @param plainText
* @return
*/
public static String encrypt(PublicKey publicKey,String plainText){
try {
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] enBytes = cipher.doFinal(plainText.getBytes());
return (new BASE64Encoder()).encode(enBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 使用keystore对明文进行加密
* @param publicKeystore 公钥文件路径
* @param plainText 明文
* @return
*/
public static String encrypt(String publicKeystore,String plainText){
try {
FileReader fr = new FileReader(publicKeystore);
BufferedReader br = new BufferedReader(fr);
String publicKeyString="";
String str;
while((str=br.readLine())!=null){
publicKeyString+=str;
}
br.close();
fr.close();
cipher.init(Cipher.ENCRYPT_MODE,getPublicKey(publicKeyString));
byte[] enBytes = cipher.doFinal(plainText.getBytes());
return (new BASE64Encoder()).encode(enBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 使用私钥对明文密文进行解密
* @param privateKey
* @param enStr
* @return
*/
public static String decrypt(PrivateKey privateKey,String enStr){
try {
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));
return new String(deBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 使用keystore对密文进行解密
* @param privateKeystore 私钥路径
* @param enStr 密文
* @return
*/
public static String decrypt(String privateKeystore,String enStr){
try {
FileReader fr = new FileReader(privateKeystore);
BufferedReader br = new BufferedReader(fr);
String privateKeyString="";
String str;
while((str=br.readLine())!=null){
privateKeyString+=str;
}
br.close();
fr.close();
cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyString));
byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));
return new String(deBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Ⅵ c#怎么调用java生成的RSA 公钥进行加密
而net 的公钥是xml格式:
<RSAKeyValue><Molus>vpUk3hmR9kDdo8+AoLfFqpP/JlPkU6VDlMaDq
F5WoNUQcdUsfUT4cQSZaa5O/
/QGFlcVIfSWeDaZnZDn/
S0fDl7F6CfJfJlsM=</Molus><Exponent>AQAB</Exponent>
</RSAKeyValue>
我这里最多帮你做个对应解析,数据是肯定无法用的:
将java的RSA公钥最后四个字母AQAB分割开,用.NET的xml格式表示就是
<RSAKeyValue><Molus>
/qp
jLFfDCu3qytxf+/IoCYE
Ⅶ 怎样用Java实现RSA加密
提供加密,解密,生成密钥对等方法。�梢愿�模��遣灰��螅�裨蛐�驶岬� keyPairGen.initialize(KEY_SIZE, new SecureRandom()); KeyPair keyPair = keyPairGen.genKeyPair(); return keyPair; } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * 生成公钥 * @param molus * @param publicExponent * @return RSAPublicKey * @throws Exception */ public static RSAPublicKey generateRSAPublicKey(byte[] molus, byte[] publicExponent) throws Exception { KeyFactory keyFac = null; try { keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); } catch (NoSuchAlgorithmException ex) { throw new Exception(ex.getMessage()); } RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(molus), new BigInteger(publicExponent)); try { return (RSAPublicKey) keyFac.generatePublic(pubKeySpec); } catch (InvalidKeySpecException ex) { throw new Exception(ex.getMessage()); } } /** * 生成私钥 * @param molus * @param privateExponent * @return RSAPrivateKey * @throws Exception */ public static RSAPrivateKey generateRSAPrivateKey(byte[] molus, byte[] privateExponent) throws Exception { KeyFactory keyFac = null; try { keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); } catch (NoSuchAlgorithmException ex) { throw new Exception(ex.getMessage()); } RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(molus), new BigInteger(privateExponent)); try { return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec); } catch (InvalidKeySpecException ex) { throw new Exception(ex.getMessage()); } } /** * 加密 * @param key 加密的密钥 * @param data 待加密的明文数据 * @return 加密后的数据 * @throws Exception */ public static byte[] encrypt(Key key, byte[] data) throws Exception { try { Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); cipher.init(Cipher.ENCRYPT_MODE, key); int blockSize = cipher.getBlockSize();//获得加密块大小� i++; } return raw; } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * 解密 * @param key 解密的密钥 * @param raw 已经加密的数据 * @return 解密后的明文 * @throws Exception */ public static byte[] decrypt(Key key, byte[] raw) throws Exception { try { Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); cipher.init(cipher.DECRYPT_MODE, key); int blockSize = cipher.getBlockSize(); ByteArrayOutputStream bout = new ByteArrayOutputStream(64); int j = 0; while (raw.length - j * blockSize > 0) { bout.write(cipher.doFinal(raw, j * blockSize, blockSize)); j++; } return bout.toByteArray(); } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { File file = new File("c:/test.html"); FileInputStream in = new FileInputStream(file); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] tmpbuf = new byte[1024]; int count = 0; while ((count = in.read(tmpbuf)) != -1) { bout.write(tmpbuf, 0, count); tmpbuf = new byte[1024]; } in.close(); byte[] orgData = bout.toByteArray(); KeyPair keyPair = RSA.generateKeyPair(); RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate(); byte[] pubModBytes = pubKey.getMolus().toByteArray(); byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray(); byte[] priModBytes = priKey.getMolus().toByteArray(); byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray(); RSAPublicKey recoveryPubKey = RSA.generateRSAPublicKey(pubModBytes,pubPubExpBytes); RSAPrivateKey recoveryPriKey = RSA.generateRSAPrivateKey(priModBytes,priPriExpBytes); byte[] raw = RSA.encrypt(priKey, orgData); file = new File("c:/encrypt_result.dat"); OutputStream out = new FileOutputStream(file); out.write(raw); out.close(); byte[] data = RSA.decrypt(recoveryPubKey, raw); file = new File("c:/decrypt_result.html"); out = new FileOutputStream(file); out.write(data); out.flush(); out.close(); } } (责任编辑:云子)
Ⅷ java生成的rsa公钥 能在python上使用吗
肯定可以,这个跟语言是无关的
Python上RSA加密的库挺多的,最开始使用的是rsa,因为比较简单嘛!测试的时候也是用 python模拟App的访问,顺利通过!
然而App开发者反馈,python测试脚本没法移植到java上,因为java的加密解密模块需要更加精细的算法细节指定,否则java加密过的数据python是解不出来的。
当初就是因为rsa模块简单,不需要注重细节才选的,自己又不是专业搞加密解密的。没办法了,只能硬着头皮,捋了一遍RSA的加密原理。网上还是有比较多的讲述比较好的文章,比如RSA算法原理
原理是懂了,但具体到python和java的区别上,还是一头雾水。最终python的RSA模块换成Crypto,因为支持的参数比较多。搜了很多网站讲的都不是很详细,stackflow上有几篇还可以,借鉴了一下,最后测试通过了。还是直接上代码吧。
Java代码
//下面这行指定了RSA算法的细节,必须更python对应
private static String RSA_CONFIGURATION = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
//这个貌似需要安装指定的provider模块,这里没有使用
private static String RSA_PROVIDER = "BC";
//解密 Key:私钥
public static String decrypt(Key key, String encryptedString){
try {
Cipher c = Cipher.getInstance(RSA_CONFIGURATION);
c.init(Cipher.DECRYPT_MODE, key, new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256,
PSource.PSpecified.DEFAULT));
byte[] decodedBytes;
decodedBytes = c.doFinal(Base64.decode(encryptedString.getBytes("UTF-8")));
return new String(decodedBytes, "UTF-8");
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Base64DecodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch ( e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//加密 Key一般是公钥
public static String encrypt(Key key, String toBeEncryptedString){
try {
Cipher c = Cipher.getInstance(RSA_CONFIGURATION);
c.init(Cipher.ENCRYPT_MODE, key, new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256,
PSource.PSpecified.DEFAULT));
byte[] encodedBytes;
encodedBytes = c.doFinal(toBeEncryptedString.getBytes("UTF-8"));
return Base64.encode(encodedBytes);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch ( e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//通过Pem格式的字符串(PKCS8)生成私钥,base64是去掉头和尾的b64编码的字符串
//Pem格式私钥一般有2种规范:PKCS8和PKCS1.注意java在生成私钥时的不同
static PrivateKey generatePrivateKeyFromPKCS8(String base64)
{
byte[] privateKeyBytes;
try {
privateKeyBytes = Base64.decode(base64.getBytes("UTF-8"));
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = kf.generatePrivate(ks);
return privateKey;
} catch (Base64DecodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//通过Pem格式的字符串(PKCS1)生成私钥,base64是去掉头和尾的b64编码的字符串
static PrivateKey generatePrivateKeyFromPKCS1(String base64)
{
byte[] privateKeyBytes;
try {
privateKeyBytes = Base64.decode(base64.getBytes("UTF-8"));
KeyFactory kf = KeyFactory.getInstance("RSA");
X509EncodedKeySpec ks = new X509EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = kf.generatePrivate(ks);
return privateKey;
} catch (Base64DecodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//通过Pem格式的字符串(PKCS1)生成公钥,base64是去掉头和尾的b64编码的字符串
//Pem格式公钥一般采用PKCS1格式
static PublicKey generatePublicKeyFromPKCS1(String base64)
{
byte[] publicKeyBytes;
try {
publicKeyBytes = Base64.decode(base64.getBytes("UTF-8"));
KeyFactory kf = KeyFactory.getInstance("RSA");
X509EncodedKeySpec ks = new X509EncodedKeySpec(publicKeyBytes);
PublicKey publicKey = kf.generatePublic(ks);
return publicKey;
} catch (Base64DecodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//通过molus和exponent生成公钥
//参数含义就是RSA算法里的意思
public static RSAPublicKey getPublicKey(String molus, String exponent) {
try {
BigInteger b1 = new BigInteger(molus);
BigInteger b2 = new BigInteger(exponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Python 代码
from Config import config
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
key = RSA.generate(1024)
pubkey = key.publickey().key
def Decrypt(prikey,data):
try:
cipher = PKCS1_OAEP.new(prikey, hashAlgo=SHA256)
return cipher.decrypt(data)
except:
traceback.print_exc()
return None
def Encrypt(pubkey,data):
try:
cipher = PKCS1_OAEP.new(pubkey, hashAlgo=SHA256)
return cipher.encrypt(data)
except:
traceback.print_exc()
return None
总结
主要是对RSA算法不是很熟悉,其中很多术语不懂,导致跟java里的加密模块的函数和类对应不上。
RSA算法的细节到现在也是一知半解,但真的没时间去深入学习了。
Ⅸ java中RSA用私钥加密公钥解密问题
公钥和私钥可以互换的用,用公钥加密私钥解密,用私钥加密公钥解密都ok,方法一样