2014-09-30 121 views
0

我需要從二進制字符串爲RSA算法創建一個公鑰。Android-Java 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 

回答

1

解決。 問題是,我有模數和指數,所以我必須這樣做:

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);