编程语言
首页 > 编程语言> > Android-Java RSA解密

Android-Java RSA解密

作者:互联网

我需要从二进制字符串为RSA算法创建一个公共密钥.

我的代码是:

String pubKey = "tihq/Gk3OUs5NzP+XTRKXBwSxHtB0TWn0RREcpXEtp316tyD9DzKaIbdKexb/mRr";

byte[] keyBytes = Base64.decode(pubKey,Base64.DEFAULT);
//test if is correct: ok
Log.d("response keyBytes",new String(Base64.encode(keyBytes,Base64.DEFAULT)));

KeyFactory keyFactory = KeyFactory.getInstance("RSA");      
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);

RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(spec);
//PublicKey publicKey = (PublicKey) keyFactory.generatePublic(spec);

但是我有这个错误:

java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag

解决方法:

解决了.
问题是我有模数和指数,所以我必须这样做:

String pubKey = "tihq/Gk3OUs5NzP+XTRKXBwSxHtB0TWn0RREcpXEtp316tyD9DzKaIbdKexb/mRr"; //64 caratteri
String exponent = "AQAB";

byte[] keyBytes = Base64.decode(pubKey,Base64.DEFAULT);
byte[] exponentByte = Base64.decode(exponent,Base64.DEFAULT);

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

RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(keyBytes), new BigInteger(exponentByte));
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);

标签:android,java,rsa,public-key
来源: https://codeday.me/bug/20191010/1883799.html