[英]Can we do whatever we do using keytool with java.security apis like KeyPairGenerator etc
我们可以使用keytool和KeyPairGenerator等java.security api来做任何事情吗?
我有兴趣扩展具有特定有效性的证书。
例如,可以使用Java安全API运行以下命令吗?
keytool -genkeypair {-alias别名} {-keyalg keyalg} {-keysize keysize} {-sigalg sigalg} [-dname dname] [-keypass keypass] {-validity valDays} {-storetype storetype}
我只想使用Java核心安全性API,而对第三方API不感兴趣
可以使用带有一些附加实用工具类的java.security.*
类来重新创建keytool
大多数操作(至少我所知道的那些操作),例如,创建一对新的密钥,您可以使用:
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);
}
}
这是一个(更详细的) 示例 ,它不仅创建KeyPair
,还将其存储在文件中
您还可以将KeyPair
与到期时间戳一起序列化为SealedObject,以模拟validity
参数和keytool
提供的存储
编辑: SealedObject本身不会给您提供validity
参数模拟,而是与密钥对(在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
提供的某些功能的原因
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.