8260693: Provide the support for specifying a signer in keytool -genkeypair

Reviewed-by: weijun
This commit is contained in:
Hai-May Chao 2021-04-09 01:59:59 +00:00
parent 77b16739ab
commit 719f95e504
6 changed files with 484 additions and 42 deletions

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -74,28 +74,41 @@ public final class CertAndKeyGen {
* @exception NoSuchAlgorithmException on unrecognized algorithms.
*/
public CertAndKeyGen (String keyType, String sigAlg)
throws NoSuchAlgorithmException
throws NoSuchAlgorithmException
{
keyGen = KeyPairGenerator.getInstance(keyType);
this.sigAlg = sigAlg;
this.keyType = keyType;
}
/**
* @see #CertAndKeyGen(String, String, String, PrivateKey, X500Name)
*/
public CertAndKeyGen (String keyType, String sigAlg, String providerName)
throws NoSuchAlgorithmException, NoSuchProviderException
{
this(keyType, sigAlg, providerName, null, null);
}
/**
* Creates a CertAndKeyGen object for a particular key type,
* signature algorithm, and provider.
* signature algorithm, and provider. The newly generated cert will
* be signed by the signer's private key when it is provided.
*
* @param keyType type of key, e.g. "RSA", "DSA"
* @param sigAlg name of the signature algorithm, e.g. "MD5WithRSA",
* "MD2WithRSA", "SHAwithDSA". If set to null, a default
* algorithm matching the private key will be chosen after
* the first keypair is generated.
* @param keyType type of key, e.g. "RSA", "DSA", "X25519", "DH", etc.
* @param sigAlg name of the signature algorithm, e.g. "SHA384WithRSA",
* "SHA256withDSA", etc. If set to null, a default
* algorithm matching the private key or signer's private
* key will be chosen after the first keypair is generated.
* @param providerName name of the provider
* @param signerPrivateKey (optional) signer's private key
* @param signerSubjectName (optional) signer's subject name
* @exception NoSuchAlgorithmException on unrecognized algorithms.
* @exception NoSuchProviderException on unrecognized providers.
*/
public CertAndKeyGen (String keyType, String sigAlg, String providerName)
throws NoSuchAlgorithmException, NoSuchProviderException
public CertAndKeyGen(String keyType, String sigAlg, String providerName,
PrivateKey signerPrivateKey, X500Name signerSubjectName)
throws NoSuchAlgorithmException, NoSuchProviderException
{
if (providerName == null) {
keyGen = KeyPairGenerator.getInstance(keyType);
@ -109,6 +122,9 @@ public final class CertAndKeyGen {
}
this.sigAlg = sigAlg;
this.keyType = keyType;
this.signerPrivateKey = signerPrivateKey;
this.signerSubjectName = signerSubjectName;
this.signerFlag = signerPrivateKey != null;
}
/**
@ -187,11 +203,20 @@ public final class CertAndKeyGen {
}
if (sigAlg == null) {
sigAlg = SignatureUtil.getDefaultSigAlgForKey(privateKey);
if (sigAlg == null) {
throw new IllegalArgumentException(
"Cannot derive signature algorithm from "
+ privateKey.getAlgorithm());
if (signerFlag) {
sigAlg = SignatureUtil.getDefaultSigAlgForKey(signerPrivateKey);
if (sigAlg == null) {
throw new IllegalArgumentException(
"Cannot derive signature algorithm from "
+ signerPrivateKey.getAlgorithm());
}
} else {
sigAlg = SignatureUtil.getDefaultSigAlgForKey(privateKey);
if (sigAlg == null) {
throw new IllegalArgumentException(
"Cannot derive signature algorithm from "
+ privateKey.getAlgorithm());
}
}
}
}
@ -266,6 +291,8 @@ public final class CertAndKeyGen {
}
// Like above, plus a CertificateExtensions argument, which can be null.
// Create a self-signed certificate, or a certificate that is signed by
// a signer when the signer's private key is provided.
public X509Certificate getSelfCertificate (X500Name myname, Date firstDate,
long validity, CertificateExtensions ext)
throws CertificateException, InvalidKeyException, SignatureException,
@ -293,11 +320,21 @@ public final class CertAndKeyGen {
info.set(X509CertInfo.SUBJECT, myname);
info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.ISSUER, myname);
if (signerFlag) {
// use signer's subject name to set the issuer name
info.set(X509CertInfo.ISSUER, signerSubjectName);
} else {
info.set(X509CertInfo.ISSUER, myname);
}
if (ext != null) info.set(X509CertInfo.EXTENSIONS, ext);
cert = new X509CertImpl(info);
cert.sign(privateKey, sigAlg);
if (signerFlag) {
// use signer's private key to sign
cert.sign(signerPrivateKey, sigAlg);
} else {
cert.sign(privateKey, sigAlg);
}
return cert;
@ -321,4 +358,7 @@ public final class CertAndKeyGen {
private KeyPairGenerator keyGen;
private PublicKey publicKey;
private PrivateKey privateKey;
private boolean signerFlag;
private PrivateKey signerPrivateKey;
private X500Name signerSubjectName;
}

View file

@ -162,6 +162,8 @@ public final class Main {
private String srcstoretype = null;
private Set<char[]> passwords = new HashSet<>();
private String startDate = null;
private String signerAlias = null;
private char[] signerKeyPass = null;
private boolean tlsInfo = false;
@ -208,6 +210,7 @@ public final class Main {
GENKEYPAIR("Generates.a.key.pair",
ALIAS, KEYALG, KEYSIZE, CURVENAME, SIGALG, DNAME,
STARTDATE, EXT, VALIDITY, KEYPASS, KEYSTORE,
SIGNER, SIGNERKEYPASS,
STOREPASS, STORETYPE, PROVIDERNAME, ADDPROVIDER,
PROVIDERCLASS, PROVIDERPATH, V, PROTECTED),
GENSECKEY("Generates.a.secret.key",
@ -352,6 +355,8 @@ public final class Main {
PROVIDERPATH("providerpath", "<list>", "provider.classpath"),
RFC("rfc", null, "output.in.RFC.style"),
SIGALG("sigalg", "<alg>", "signature.algorithm.name"),
SIGNER("signer", "<alias>", "signer.alias"),
SIGNERKEYPASS("signerkeypass", "<arg>", "signer.key.password"),
SRCALIAS("srcalias", "<alias>", "source.alias"),
SRCKEYPASS("srckeypass", "<arg>", "source.key.password"),
SRCKEYSTORE("srckeystore", "<keystore>", "source.keystore.name"),
@ -603,6 +608,11 @@ public final class Main {
keyAlgName = args[++i];
} else if (collator.compare(flags, "-sigalg") == 0) {
sigAlgName = args[++i];
} else if (collator.compare(flags, "-signer") == 0) {
signerAlias = args[++i];
} else if (collator.compare(flags, "-signerkeypass") == 0) {
signerKeyPass = getPass(modifier, args[++i]);
passwords.add(signerKeyPass);
} else if (collator.compare(flags, "-startdate") == 0) {
startDate = args[++i];
} else if (collator.compare(flags, "-validity") == 0) {
@ -1148,7 +1158,8 @@ public final class Main {
throw new Exception(rb.getString(
"keyalg.option.missing.error"));
}
doGenKeyPair(alias, dname, keyAlgName, keysize, groupName, sigAlgName);
doGenKeyPair(alias, dname, keyAlgName, keysize, groupName, sigAlgName,
signerAlias);
kssave = true;
} else if (command == GENSECKEY) {
if (keyAlgName == null) {
@ -1858,7 +1869,8 @@ public final class Main {
* Creates a new key pair and self-signed certificate.
*/
private void doGenKeyPair(String alias, String dname, String keyAlgName,
int keysize, String groupName, String sigAlgName)
int keysize, String groupName, String sigAlgName,
String signerAlias)
throws Exception
{
if (groupName != null) {
@ -1879,6 +1891,14 @@ public final class Main {
keysize = 255;
} else if ("Ed448".equalsIgnoreCase(keyAlgName)) {
keysize = 448;
} else if ("XDH".equalsIgnoreCase(keyAlgName)) {
keysize = SecurityProviderConstants.DEF_XEC_KEY_SIZE;
} else if ("X25519".equalsIgnoreCase(keyAlgName)) {
keysize = 255;
} else if ("X448".equalsIgnoreCase(keyAlgName)) {
keysize = 448;
} else if ("DH".equalsIgnoreCase(keyAlgName)) {
keysize = SecurityProviderConstants.DEF_DH_KEY_SIZE;
}
} else {
if ("EC".equalsIgnoreCase(keyAlgName)) {
@ -1900,9 +1920,35 @@ public final class Main {
throw new Exception(form.format(source));
}
CertAndKeyGen keypair =
new CertAndKeyGen(keyAlgName, sigAlgName, providerName);
CertAndKeyGen keypair;
KeyIdentifier signerSubjectKeyId = null;
if (signerAlias != null) {
PrivateKey signerPrivateKey =
(PrivateKey)recoverKey(signerAlias, storePass, signerKeyPass).fst;
Certificate signerCert = keyStore.getCertificate(signerAlias);
X509CertImpl signerCertImpl;
if (signerCert instanceof X509CertImpl) {
signerCertImpl = (X509CertImpl) signerCert;
} else {
signerCertImpl = new X509CertImpl(signerCert.getEncoded());
}
X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get(
X509CertImpl.NAME + "." + X509CertImpl.INFO);
X500Name signerSubjectName = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "." +
X509CertInfo.DN_NAME);
keypair = new CertAndKeyGen(keyAlgName, sigAlgName, providerName,
signerPrivateKey, signerSubjectName);
signerSubjectKeyId = signerCertImpl.getSubjectKeyId();
if (signerSubjectKeyId == null) {
signerSubjectKeyId = new KeyIdentifier(signerCert.getPublicKey());
}
} else {
keypair = new CertAndKeyGen(keyAlgName, sigAlgName, providerName);
}
// If DN is provided, parse it. Otherwise, prompt the user for it.
X500Name x500Name;
@ -1920,34 +1966,55 @@ public final class Main {
keypair.generate(keysize);
}
PrivateKey privKey = keypair.getPrivateKey();
CertificateExtensions ext = createV3Extensions(
null,
null,
v3ext,
keypair.getPublicKeyAnyway(),
null);
signerSubjectKeyId);
X509Certificate[] chain = new X509Certificate[1];
chain[0] = keypair.getSelfCertificate(
PrivateKey privKey = keypair.getPrivateKey();
X509Certificate newCert = keypair.getSelfCertificate(
x500Name, getStartDate(startDate), validity*24L*60L*60L, ext);
MessageFormat form = new MessageFormat(rb.getString
("Generating.keysize.bit.keyAlgName.key.pair.and.self.signed.certificate.sigAlgName.with.a.validity.of.validality.days.for"));
Object[] source = {
groupName == null ? keysize : KeyUtil.getKeySize(privKey),
fullDisplayAlgName(privKey),
chain[0].getSigAlgName(),
validity,
x500Name};
System.err.println(form.format(source));
if (signerAlias != null) {
MessageFormat form = new MessageFormat(rb.getString
("Generating.keysize.bit.keyAlgName.key.pair.and.a.certificate.sigAlgName.issued.by.signerAlias.with.a.validity.of.validality.days.for"));
Object[] source = {
groupName == null ? keysize : KeyUtil.getKeySize(privKey),
fullDisplayAlgName(privKey),
newCert.getSigAlgName(),
signerAlias,
validity,
x500Name};
System.err.println(form.format(source));
} else {
MessageFormat form = new MessageFormat(rb.getString
("Generating.keysize.bit.keyAlgName.key.pair.and.self.signed.certificate.sigAlgName.with.a.validity.of.validality.days.for"));
Object[] source = {
groupName == null ? keysize : KeyUtil.getKeySize(privKey),
fullDisplayAlgName(privKey),
newCert.getSigAlgName(),
validity,
x500Name};
System.err.println(form.format(source));
}
if (keyPass == null) {
keyPass = promptForKeyPass(alias, null, storePass);
}
checkWeak(rb.getString("the.generated.certificate"), chain[0]);
keyStore.setKeyEntry(alias, privKey, keyPass, chain);
Certificate[] finalChain;
if (signerAlias != null) {
Certificate[] signerChain = keyStore.getCertificateChain(signerAlias);
finalChain = new X509Certificate[signerChain.length + 1];
finalChain[0] = newCert;
System.arraycopy(signerChain, 0, finalChain, 1, signerChain.length);
} else {
finalChain = new Certificate[] { newCert };
}
checkWeak(rb.getString("the.generated.certificate"), finalChain);
keyStore.setKeyEntry(alias, privKey, keyPass, finalChain);
}
private String ecGroupNameForSize(int size) throws Exception {
@ -4243,7 +4310,6 @@ public final class Main {
* @param existingEx the original extensions, can be null, used for -selfcert
* @param extstrs -ext values, Read keytool doc
* @param pkey the public key for the certificate
* @param akey the public key for the authority (issuer)
* @param aSubjectKeyId the subject key identifier for the authority (issuer)
* @return the created CertificateExtensions
*/

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -162,6 +162,10 @@ public class Resources extends java.util.ListResourceBundle {
"output in RFC style"}, //-rfc
{"signature.algorithm.name",
"signature algorithm name"}, //-sigalg
{"signer.alias",
"signer alias"}, //-signer
{"signer.key.password",
"signer key password"}, //-signerkeypass
{"source.alias",
"source alias"}, //-srcalias
{"source.key.password",
@ -302,6 +306,8 @@ public class Resources extends java.util.ListResourceBundle {
"Key pair not generated, alias <{0}> already exists"},
{"Generating.keysize.bit.keyAlgName.key.pair.and.self.signed.certificate.sigAlgName.with.a.validity.of.validality.days.for",
"Generating {0} bit {1} key pair and self-signed certificate ({2}) with a validity of {3} days\n\tfor: {4}"},
{"Generating.keysize.bit.keyAlgName.key.pair.and.a.certificate.sigAlgName.issued.by.signerAlias.with.a.validity.of.validality.days.for",
"Generating {0} bit {1} key pair and a certificate ({2}) issued by <{3}> with a validity of {4} days\n\tfor: {5}"},
{"Enter.key.password.for.alias.", "Enter key password for <{0}>"},
{".RETURN.if.same.as.keystore.password.",
"\t(RETURN if same as keystore password): "},
@ -481,7 +487,6 @@ public class Resources extends java.util.ListResourceBundle {
{"backup.keystore.warning", "The original keystore \"%1$s\" is backed up as \"%3$s\"..."},
{"importing.keystore.status", "Importing keystore %1$s to %2$s..."},
{"keyalg.option.missing.error", "The -keyalg option must be specified."},
{"showinfo.no.option", "Missing option for -showinfo. Try \"keytool -showinfo -tls\"."},
};