大多数操作keytool
(至少我知道的操作)可以使用java.security.*
带有一些附加实用程序类的类来重新创建,例如,创建一对可以使用的新密钥:
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);
}
}
这是从 a中检索a的示例KeyPair
KeyStore
这是一个(更详细的)示例,它不仅创建KeyPair
,而且将其存储在文件中
您还可以将KeyPair
过期时间戳旁边序列化为SealedObject以模拟validity
由keytool
编辑: SealedObject单独不会给你validity
参数模拟,是与密钥对一起存储的时间戳(在 a 中SealedObject
),它将“模拟”到期日期(可以看作是密钥的有效性)。例如:
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