「javarsa生成公钥」简述rsa的公钥生成算法

博主:adminadmin 2022-12-01 14:25:06 109

本篇文章给大家谈谈javarsa生成公钥,以及简述rsa的公钥生成算法对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

给一个java简单随机生成rsa公钥私钥的算法代码

#!/usr/bin/perl -w

#RSA 计算过程学习程序编写的测试程序

#watercloud 2003-8-12

#

use strict;

use Math::BigInt;

my %RSA_CORE = (n=2773,e=63,d=847); #p=47,q=59

my $N=new Math::BigInt($RSA_CORE{n});

my $E=new Math::BigInt($RSA_CORE{e});

my $D=new Math::BigInt($RSA_CORE{d});

print "N=$N D=$D E=$E\n";

sub RSA_ENCRYPT

{

my $r_mess = shift @_;

my ($c,$i,$M,$C,$cmess);

for($i=0;$i length($$r_mess);$i++)

{

$c=ord(substr($$r_mess,$i,1));

$M=Math::BigInt-new($c);

$C=$M-copy(); $C-bmodpow($D,$N);

$c=sprintf "%03X",$C;

$cmess.=$c;

}

return \$cmess;

}

sub RSA_DECRYPT

{

my $r_mess = shift @_;

my ($c,$i,$M,$C,$dmess);

for($i=0;$i length($$r_mess);$i+=3)

{

$c=substr($$r_mess,$i,3);

$c=hex($c);

$M=Math::BigInt-new($c);

$C=$M-copy(); $C-bmodpow($E,$N);

$c=chr($C);

$dmess.=$c;

}

return \$dmess;

}

my $mess="RSA 娃哈哈哈~~~";

$mess=$ARGV[0] if @ARGV = 1;

print "原始串:",$mess,"\n";

my $r_cmess = RSA_ENCRYPT(\$mess);

print "加密串:",$$r_cmess,"\n";

my $r_dmess = RSA_DECRYPT($r_cmess);

print "解密串:",$$r_dmess,"\n";

#EOF

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 MapString,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();

//将生成的密钥对返回

MapString,String map = new HashMapString,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;

}

}

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 (InvalidAlgorithmParameterException 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 (InvalidAlgorithmParameterException 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;

}

//通过modulus和exponent生成公钥

//参数含义就是RSA算法里的意思

public static RSAPublicKey getPublicKey(String modulus, String exponent) {

try {

BigInteger b1 = new BigInteger(modulus);

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;

}

} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169

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

1234567891011121314151617181920212223

总结

主要是对RSA算法不是很熟悉,其中很多术语不懂,导致跟java里的加密模块的函数和类对应不上。

RSA算法的细节到现在也是一知半解,但真的没时间去深入学习了。

关于javarsa生成公钥和简述rsa的公钥生成算法的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

The End

发布于:2022-12-01,除非注明,否则均为首码项目网原创文章,转载请注明出处。