我有一个普通公开rsa密钥的十六进制表示。现在我要检索密钥的长度。
public void testIt(String[] args) {
logger.entry();
Security.addProvider(new BouncyCastleProvider());
String
pubAsHex="30820122300d06092a864886f70d01010105000382010f003082010a0282010100e816e9de7ed0c26c1157e56d7751ba59ebf5a75e65b91ce338794ed9ca24aefa1a26a5d927ccc7f3c6d21b05f3acc6fa73be2db0ed124a38dcb130aaa191214304f4c8c06d0b0dfd3ebc3ea0f5753555d5830ff09bd0f041013c0abc25d482ec6ec03b633b6c314fdd6fe71ddc5f6566f58edc65a6da86e8fb5f1205b48c53aecd2d5daec0232cca5071cc81609332568fa1a982bab49ebe9f6fd28cba52c50281a84597764b44e8775622cac36c7e1d4f3dd5417ecc8b8e1b5bdbc4ac36a2ef8e3dfc757a114d3ed82eb8ffbbd08392f242342db90c02ec9d210eec2bb4e2f8a6fc94a27647e9ec14789a1c3e962e59a75bc59d9658689e28699e136fce75470203";
byte[] myKeyBytes=hex2Binary(pubAsHex);
try{
//Takes your byte array of the key as constructor parameter
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(myKeyBytes);
//Takes algorithm used to generate keys (DSA, RSA, DiffieHellman, etc.) as 1st parameter
//Takes security provider (SUN, BouncyCastle, etc.) as second parameter
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//Creates a new PublicKey object
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
RSAPublicKey myRsaKey = (RSAPublicKey) pubKey;
logger.info("Length: "+myRsaKey.getModulus().bitLength());
} catch(Exception e) {
e.printStackTrace();
}
logger.exit();
}
public static byte [] hex2Binary (String hex) throws IllegalArgumentException, NullPointerException, NumberFormatException
{
int j = hex.length ();
if (j % 2 != 0)
throw new IllegalArgumentException ("Incorrect hex string length " + j);
byte [] result = new byte [j >> 1];
for (int i = result.length - 1; i >= 0; i--, j -= 2)
result [i] = (byte) Integer.parseInt (hex.substring (j - 2, j), 16);
return result;
}
我找不到一个密钥不被视为x509证书的示例。示例代码引发invalidkeyspecexception
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: Detect premature EOF
at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:205)
at java.security.KeyFactory.generatePublic(KeyFactory.java:334)
at de.martinm.tools.Test.KKSTester.testIt(KKSTester.java:156)
at de.martinm.tools.Test.KKSTester.process(KKSTester.java:343)
at de.martinm.tools.Test.KKSTester.main(KKSTester.java:351)
Caused by: java.security.InvalidKeyException: IOException: Detect premature EOF
at sun.security.x509.X509Key.decode(X509Key.java:398)
at sun.security.x509.X509Key.decode(X509Key.java:403)
at sun.security.rsa.RSAPublicKeyImpl.<init>(RSAPublicKeyImpl.java:86)
at sun.security.rsa.RSAKeyFactory.generatePublic(RSAKeyFactory.java:298)
at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:201)
... 4 more
1条答案
按热度按时间ecr0jaav1#
很抱歉使用了一个不是真实答案的答案,但是这些数据在评论中是不可读的。
您的密钥似乎已加密且无效。见结构:
oid编号“1 2 840 113549 1 1 1 1”给出了“rsaes-pkcs1-v1ţ5加密方案”和“此oid在公钥加密标准(pkcs)1中定义。另见ietf rfc 8017。
也许你是幸运的,在bouncy castle的pem阅读器的帮助下,当你知道密码短语时,你就能够读懂钥匙了。