8221257: Improve serial number generation mechanism for keytool -gencert

Reviewed-by: xuelei, mullan
This commit is contained in:
Weijun Wang 2019-03-30 16:32:23 +08:00
parent d1926144eb
commit 61485b75a9
4 changed files with 119 additions and 7 deletions

View file

@ -287,8 +287,11 @@ public final class CertAndKeyGen {
// Add all mandatory attributes
info.set(X509CertInfo.VERSION,
new CertificateVersion(CertificateVersion.V3));
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
new java.util.Random().nextInt() & 0x7fffffff));
if (prng == null) {
prng = new SecureRandom();
}
info.set(X509CertInfo.SERIAL_NUMBER,
CertificateSerialNumber.newRandom64bit(prng));
AlgorithmId algID = AlgorithmId.getWithParameterSpec(sigAlg, params);
info.set(X509CertInfo.ALGORITHM_ID,
new CertificateAlgorithmId(algID));

View file

@ -37,6 +37,7 @@ import java.security.MessageDigest;
import java.security.Key;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.Timestamp;
import java.security.UnrecoverableEntryException;
@ -1436,8 +1437,8 @@ public final class Main {
.getDefaultAlgorithmParameterSpec(sigAlgName, privateKey);
AlgorithmId algID = AlgorithmId.getWithParameterSpec(sigAlgName, params);
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
new java.util.Random().nextInt() & 0x7fffffff));
info.set(X509CertInfo.SERIAL_NUMBER,
CertificateSerialNumber.newRandom64bit(new SecureRandom()));
info.set(X509CertInfo.VERSION,
new CertificateVersion(CertificateVersion.V3));
info.set(X509CertInfo.ALGORITHM_ID,
@ -2947,8 +2948,8 @@ public final class Main {
certInfo.set(X509CertInfo.VALIDITY, interval);
// Make new serial number
certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
new java.util.Random().nextInt() & 0x7fffffff));
certInfo.set(X509CertInfo.SERIAL_NUMBER,
CertificateSerialNumber.newRandom64bit(new SecureRandom()));
// Set owner and issuer fields
X500Name owner;

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2019, 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
@ -29,6 +29,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.Enumeration;
import java.util.Random;
import sun.security.util.*;
@ -179,4 +180,16 @@ public class CertificateSerialNumber implements CertAttrSet<String> {
public String getName() {
return (NAME);
}
/**
* Generates a new random serial number.
*/
public static CertificateSerialNumber newRandom64bit(Random rand) {
while (true) {
BigInteger b = new BigInteger(64, rand);
if (b.signum() != 0) {
return new CertificateSerialNumber(b);
}
}
}
}