是否可以单独从一个编码的字节数组创建一个PrivateKey
,而无需事先知道该算法?
所以从某种意义上说,that question上有一个扭曲,答案中没有提到。
说我有这样生成的一对密钥:
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); // Could be "EC" instead of "RSA"
String privateKeyB64 = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
writePrivateKeyToSafeLocation(privateKeyB64);
要从base64编码的字节中获取PrivateKey
,我可以这样做,但是我必须事先了解算法家族:
String privateKeyB64 = readPrivateKeyFromSafeLocation();
EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyB64));
byte[] encodedKeyBytes = encodedKeySpec.getEncoded();
String algorithmFamily = "RSA"; // Can this be deduced from encodedKeyBytes?
PrivateKey key = KeyFactory.getInstance(algorithmFamily).generatePrivate(encodedKeySpec);
很遗憾,encodedKeySpec.getAlgorithm()
返回了null
。
我很确定算法ID实际上是在PKCS#8格式的那些字节中指定的,但是我不确定如何读取ASN.1编码。
我可以通过可靠的方式从那些字节中“嗅探”算法ID吗?
仅支持RSA和EC(JRE支持的算法,无需其他提供程序)是可以的。
要了解我所追求的目标,以下尝试似乎可以凭经验进行:
private static final byte[] EC_ASN1_ID = {42, -122, 72, -50, 61, 2, 1};
private static final byte[] RSA_ASN1_ID = {42, -122, 72, -122, -9, 13, 1, 1, 1};
private static final int EC_ID_OFFSET = 9;
private static final int RSA_ID_OFFSET = 11;
private static String sniffAlgorithmFamily(byte[] keyBytes) {
if (Arrays.equals(Arrays.copyOfRange(keyBytes, EC_ID_OFFSET, EC_ID_OFFSET + EC_ASN1_ID.length), EC_ASN1_ID)) {
return "EC";
}
if (Arrays.equals(Arrays.copyOfRange(keyBytes, RSA_ID_OFFSET, RSA_ID_OFFSET + RSA_ASN1_ID.length), RSA_ASN1_ID)) {
return "RSA";
}
throw new RuntimeException("Illegal key, this thingy requires either RSA or EC private key");
}
但是我不知道这是否可以安全使用。也许ID并不总是在那些偏移处。也许可以用其他方式对它们进行编码...
答案 0 :(得分:1)
正如James在评论中所建议的那样,尝试每种受支持的算法都可以以更加安全的方式进行。
可以动态获取此类算法的列表:
Set<String> supportedKeyPairAlgorithms() {
Set<String> algos = new HashSet<>();
for (Provider provider : Security.getProviders()) {
for (Provider.Service service : provider.getServices()) {
if ("KeyPairGenerator".equals(service.getType())) {
algos.add(service.getAlgorithm());
}
}
}
return algos;
}
然后,只需尝试全部操作即可生成KeyPair
:
PrivateKey generatePrivateKey(String b64) {
byte[] bytes = Base64.getDecoder().decode(b64);
for (String algorithm : supportedKeyPairAlgorithms()) {
try {
LOGGER.debug("Attempting to decode key as " + algorithm);
return KeyFactory.getInstance(algorithm).generatePrivate(new PKCS8EncodedKeySpec(bytes));
} catch (NoSuchAlgorithmException e) {
LOGGER.warn("Standard algorithm " + algorithm + " not known by this Java runtime from outer space", e);
} catch (InvalidKeySpecException e) {
LOGGER.debug("So that key is not " + algorithm + ", nevermind", e);
}
}
throw new RuntimeException("No standard KeyFactory algorithm could decode your key");
}