我们可以使用 keytool 和 KeyPairGenerator 等 java.security api 做任何事情吗
我有兴趣延长具有特定有效期的证书。
例如,是否可以使用 Java 安全 API 来运行以下命令
keytool -genkeypair {-alias alias} {-keyalg keyalg} {-keysize keysize} {-sigalg sigalg} [-dname dname] [-keypass keypass] {-validity valDays} {-storetype storetype}
我只想使用 java 核心安全 API,对第三方 API 不感兴趣
最佳答案
keytool
的大多数操作(至少是我所知道的那些)都可以使用 java.security.*
类和一些附加的实用程序类来重新创建,例如,要创建一对新的 key ,您可以使用:
private static final String ALGORITHM = "RSA";
private static final String PROVIDER = "BC";
private PrivateKey privateKey;
private PublicKey publicKey;
...
public void generateNewKeyPair() {
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM, PROVIDER);
keyGen.initialize(2048, new SecureRandom());
KeyPair keypair = keyGen.genKeyPair();
privateKey = keypair.getPrivate();
publicKey = keypair.getPublic();
} catch (Exception e) {
LOG.error("Error creating keyPair", e);
}
}
这是一个 example of retrieving来自 KeyStore
KeyPair
这是一个(更详细的)example这不仅会创建 KeyPair
,还会将其存储在文件中
您还可以将 KeyPair
连同过期时间戳序列化为 SealedObject模拟 validity
参数和 keytool
编辑: SealedObject单独不会给你 validity
参数模拟,时间戳与 key 对一起存储(在 SealedObject
中)将“模拟”到期日期(可以是被视为 key 的有效性)。例如:
class KeyWithExpiration {
private PublicKey publicKey;
private Date expirationDate;
}
public static void serializeEncrypted(File file, Serializable instance) {
// With these lines, I hope to expose some of the craft that is needed to work with the API
PBEKeySpec keySpecObj = new PBEKeySpec(PASSWORD, SALT, ITERATIONS);
Cipher ecipherObj = Cipher.getInstance(keyObj.getAlgorithm());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey keyObj = secretKeyFactory.generateSecret(keySpecObj);
SealedObject sealedObject = new SealedObject(instance, ecipherObj);
ObjectOutputStream objOutputStream = new ObjectOutputStream(new FileOutputStream(file));
objOutputStream.writeObject(sealedObject);
objOutputStream.close();
}
// Generate a new KeyWithExpiration
KeyWithExpiration key = new KeyWithExpiration(keyPair, DateUtil.future().days(365));
serializeEncrypted(new File(".key"), key);
这就是为什么需要 API 和一些实用类来实现 keytool
提供的一些功能
关于java - 我们可以做任何我们使用 keytool 和 java.security api 的事情吗,比如 KeyPairGenerator 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13388087/