8252055: Use java.util.HexFormat in java.security

Reviewed-by: xuelei
This commit is contained in:
Roger Riggs 2020-12-18 16:35:11 +00:00
parent 1dae45d745
commit 68f2acbf4c
15 changed files with 71 additions and 241 deletions

@ -730,19 +730,6 @@ public abstract class AbstractDrbg {
// Misc
/** A handy method returning hexdump string with no colon or new line.
*
* @param in input byte array
* @return the hexdump string
*/
protected static String hex(byte[] in) {
StringBuilder sb = new StringBuilder();
for (byte b : in) {
sb.append(String.format("%02x", b&0xff));
}
return sb.toString();
}
/**
* Returns the smallest standard strength (112, 128, 192, 256) that is
* greater or equal to the input.

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2020, 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

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2020, 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
@ -30,6 +30,7 @@ import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.Locale;
public class CtrDrbg extends AbstractDrbg {
@ -181,8 +182,8 @@ public class CtrDrbg extends AbstractDrbg {
private void status() {
if (debug != null) {
debug.println(this, "Key = " + hex(k));
debug.println(this, "V = " + hex(v));
debug.println(this, "Key = " + HexFormat.of().formatHex(k));
debug.println(this, "V = " + HexFormat.of().formatHex(v));
debug.println(this, "reseed counter = " + reseedCounter);
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2020, 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
@ -33,6 +33,7 @@ import java.security.NoSuchProviderException;
import java.security.SecureRandomParameters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
public class HashDrbg extends AbstractHashDrbg {
@ -161,8 +162,8 @@ public class HashDrbg extends AbstractHashDrbg {
private void status() {
if (debug != null) {
debug.println(this, "V = " + hex(v));
debug.println(this, "C = " + hex(c));
debug.println(this, "V = " + HexFormat.of().formatHex(v));
debug.println(this, "C = " + HexFormat.of().formatHex(c));
debug.println(this, "reseed counter = " + reseedCounter);
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2020, 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
@ -33,6 +33,7 @@ import java.security.NoSuchProviderException;
import java.security.SecureRandomParameters;
import java.util.Arrays;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
public class HmacDrbg extends AbstractHashDrbg {
@ -51,8 +52,8 @@ public class HmacDrbg extends AbstractHashDrbg {
private void status() {
if (debug != null) {
debug.println(this, "V = " + hex(v));
debug.println(this, "Key = " + hex(k));
debug.println(this, "V = " + HexFormat.of().formatHex(v));
debug.println(this, "Key = " + HexFormat.of().formatHex(k));
debug.println(this, "reseed counter = " + reseedCounter);
}
}

@ -774,12 +774,12 @@ class RevocationChecker extends PKIXRevocationChecker {
/*
* Removes any non-hexadecimal characters from a string.
*/
private static final String HEX_DIGITS = "0123456789ABCDEFabcdef";
private static String stripOutSeparators(String value) {
HexFormat hex = HexFormat.of();
char[] chars = value.toCharArray();
StringBuilder hexNumber = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
if (HEX_DIGITS.indexOf(chars[i]) != -1) {
if (hex.isHexDigit(chars[i])) {
hexNumber.append(chars[i]);
}
}

@ -39,6 +39,7 @@ import java.text.MessageFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HexFormat;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
@ -580,7 +581,7 @@ public final class SSLLogger {
Utilities.toHexString((byte[])value) + "\"";
} else if (value instanceof Byte) {
formatted = "\"" + key + "\": \"" +
Utilities.toHexString((byte)value) + "\"";
HexFormat.of().toHexDigits((byte)value) + "\"";
} else {
formatted = "\"" + key + "\": " +
"\"" + value.toString() + "\"";

@ -33,6 +33,7 @@ import java.security.GeneralSecurityException;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HexFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
@ -237,9 +238,8 @@ final class ServerHello {
serverVersion.name,
Utilities.toHexString(serverRandom.randomBytes),
sessionId.toString(),
cipherSuite.name + "(" +
Utilities.byte16HexString(cipherSuite.id) + ")",
Utilities.toHexString(compressionMethod),
cipherSuite.name + "(" + Utilities.byte16HexString(cipherSuite.id) + ")",
HexFormat.of().toHexDigits(compressionMethod),
Utilities.indent(extensions.toString(), " ")
};

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2020, 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
@ -36,10 +36,11 @@ import sun.security.action.GetPropertyAction;
* A utility class to share the static methods.
*/
final class Utilities {
static final char[] hexDigits = "0123456789ABCDEF".toCharArray();
private static final String indent = " ";
private static final Pattern lineBreakPatern =
Pattern.compile("\\r\\n|\\n|\\r");
private static final HexFormat HEX_FORMATTER =
HexFormat.of().withUpperCase();
/**
* Puts {@code hostname} into the {@code serverNames} list.
@ -164,15 +165,8 @@ final class Utilities {
return builder.toString();
}
static String toHexString(byte b) {
return String.valueOf(hexDigits[(b >> 4) & 0x0F]) +
String.valueOf(hexDigits[b & 0x0F]);
}
static String byte16HexString(int id) {
return "0x" +
hexDigits[(id >> 12) & 0x0F] + hexDigits[(id >> 8) & 0x0F] +
hexDigits[(id >> 4) & 0x0F] + hexDigits[id & 0x0F];
return "0x" + HEX_FORMATTER.toHexDigits((short)id);
}
static String toHexString(byte[] bytes) {
@ -180,19 +174,7 @@ final class Utilities {
return "";
}
StringBuilder builder = new StringBuilder(bytes.length * 3);
boolean isFirst = true;
for (byte b : bytes) {
if (isFirst) {
isFirst = false;
} else {
builder.append(' ');
}
builder.append(hexDigits[(b >> 4) & 0x0F]);
builder.append(hexDigits[b & 0x0F]);
}
return builder.toString();
return HEX_FORMATTER.formatHex(bytes);
}
static String toHexString(long lv) {
@ -206,10 +188,8 @@ final class Utilities {
builder.append(' ');
}
builder.append(hexDigits[(int)(lv & 0x0F)]);
lv >>>= 4;
builder.append(hexDigits[(int)(lv & 0x0F)]);
lv >>>= 4;
HEX_FORMATTER.toHexDigits(builder, (byte)lv);
lv >>>= 8;
} while (lv != 0);
builder.reverse();

@ -1445,7 +1445,7 @@ public final class Main {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
boolean canRead = false;
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
while (true) {
String s = reader.readLine();
if (s == null) break;
@ -2597,7 +2597,7 @@ public final class Main {
throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
boolean started = false;
while (true) {
String s = reader.readLine();
@ -3507,33 +3507,6 @@ public final class Main {
}
}
/**
* Converts a byte to hex digit and writes to the supplied buffer
*/
private void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F' };
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
/**
* Converts a byte array to hex string
*/
private String toHexString(byte[] block) {
StringBuffer buf = new StringBuffer();
int len = block.length;
for (int i = 0; i < len; i++) {
byte2hex(block[i], buf);
if (i < len-1) {
buf.append(":");
}
}
return buf.toString();
}
/**
* Recovers (private) key associated with given alias.
*
@ -3663,7 +3636,7 @@ public final class Main {
byte[] encCertInfo = cert.getEncoded();
MessageDigest md = MessageDigest.getInstance(mdAlg);
byte[] digest = md.digest(encCertInfo);
return toHexString(digest);
return HexFormat.ofDelimiter(":").withUpperCase().formatHex(digest);
}
/**
@ -4571,21 +4544,16 @@ public final class Main {
break;
case -1:
ObjectIdentifier oid = ObjectIdentifier.of(name);
HexFormat hexFmt = HexFormat.of();
byte[] data = null;
if (value != null) {
data = new byte[value.length() / 2 + 1];
int pos = 0;
for (char c: value.toCharArray()) {
int hex;
if (c >= '0' && c <= '9') {
hex = c - '0' ;
} else if (c >= 'A' && c <= 'F') {
hex = c - 'A' + 10;
} else if (c >= 'a' && c <= 'f') {
hex = c - 'a' + 10;
} else {
if (!hexFmt.isHexDigit(c)) {
continue;
}
int hex = hexFmt.fromHexDigit(c);
if (pos % 2 == 0) {
data[pos/2] = (byte)(hex << 4);
} else {

@ -1,5 +1,5 @@
/*
* Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2020, 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
@ -27,6 +27,7 @@ package sun.security.util;
import java.io.PrintStream;
import java.math.BigInteger;
import java.util.HexFormat;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Locale;
@ -318,22 +319,11 @@ public class Debug {
return null;
}
private static final char[] hexDigits = "0123456789abcdef".toCharArray();
public static String toString(byte[] b) {
if (b == null) {
return "(null)";
}
StringBuilder sb = new StringBuilder(b.length * 3);
for (int i = 0; i < b.length; i++) {
int k = b[i] & 0xff;
if (i != 0) {
sb.append(':');
}
sb.append(hexDigits[k >>> 4]);
sb.append(hexDigits[k & 0xf]);
}
return sb.toString();
return HexFormat.ofDelimiter(":").formatHex(b);
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2020, 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
@ -214,8 +214,8 @@ public class ManifestEntryVerifier {
if (debug != null) {
debug.println("Manifest Entry: " +
name + " digest=" + digest.getAlgorithm());
debug.println(" manifest " + toHex(manHash));
debug.println(" computed " + toHex(theHash));
debug.println(" manifest " + HexFormat.of().formatHex(manHash));
debug.println(" computed " + HexFormat.of().formatHex(theHash));
debug.println();
}
@ -231,25 +231,4 @@ public class ManifestEntryVerifier {
}
return signers;
}
// for the toHex function
private static final char[] hexc =
{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
/**
* convert a byte array to a hex string for debugging purposes
* @param data the binary data to be converted to a hex string
* @return an ASCII hex string
*/
static String toHex(byte[] data) {
StringBuilder sb = new StringBuilder(data.length*2);
for (int i=0; i<data.length; i++) {
sb.append(hexc[(data[i] >>4) & 0x0f]);
sb.append(hexc[data[i] & 0x0f]);
}
return sb.toString();
}
}

@ -42,6 +42,7 @@ import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.HexFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
@ -497,8 +498,8 @@ public class SignatureFileVerifier {
if (debug != null) {
debug.println("Signature File: Manifest digest " +
algorithm);
debug.println( " sigfile " + toHex(expectedHash));
debug.println( " computed " + toHex(computedHash));
debug.println( " sigfile " + HexFormat.of().formatHex(expectedHash));
debug.println( " computed " + HexFormat.of().formatHex(computedHash));
debug.println();
}
@ -568,8 +569,8 @@ public class SignatureFileVerifier {
debug.println("Signature File: " +
"Manifest Main Attributes digest " +
digest.getAlgorithm());
debug.println( " sigfile " + toHex(expectedHash));
debug.println( " computed " + toHex(computedHash));
debug.println( " sigfile " + HexFormat.of().formatHex(expectedHash));
debug.println( " computed " + HexFormat.of().formatHex(computedHash));
debug.println();
}
@ -676,8 +677,8 @@ public class SignatureFileVerifier {
if (debug != null) {
debug.println("Signature Block File: " +
name + " digest=" + digest.getAlgorithm());
debug.println(" expected " + toHex(expected));
debug.println(" computed " + toHex(computed));
debug.println(" expected " + HexFormat.of().formatHex(expected));
debug.println(" computed " + HexFormat.of().formatHex(computed));
debug.println();
}
@ -690,7 +691,7 @@ public class SignatureFileVerifier {
computed = mde.digestWorkaround(digest);
if (MessageDigest.isEqual(computed, expected)) {
if (debug != null) {
debug.println(" re-computed " + toHex(computed));
debug.println(" re-computed " + HexFormat.of().formatHex(computed));
debug.println();
}
workaround = true;
@ -763,26 +764,6 @@ public class SignatureFileVerifier {
}
}
// for the toHex function
private static final char[] hexc =
{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
/**
* convert a byte array to a hex string for debugging purposes
* @param data the binary data to be converted to a hex string
* @return an ASCII hex string
*/
static String toHex(byte[] data) {
StringBuilder sb = new StringBuilder(data.length*2);
for (int i=0; i<data.length; i++) {
sb.append(hexc[(data[i] >>4) & 0x0f]);
sb.append(hexc[data[i] & 0x0f]);
}
return sb.toString();
}
// returns true if set contains signer
static boolean contains(CodeSigner[] set, CodeSigner signer)
{

@ -108,12 +108,6 @@ public class AVA implements DerEncoder {
private static final String specialCharsDefault = ",=\n+<>#;\\\" ";
private static final String escapedDefault = ",+<>;\"";
/*
* Values that aren't printable strings are emitted as BER-encoded
* hex data.
*/
private static final String hexDigits = "0123456789ABCDEF";
public AVA(ObjectIdentifier type, DerValue val) {
if ((type == null) || (val == null)) {
throw new NullPointerException();
@ -257,7 +251,7 @@ public class AVA implements DerEncoder {
private static DerValue parseHexString
(Reader in, int format) throws IOException {
HexFormat hex = HexFormat.of();
int c;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte b = 0;
@ -268,21 +262,18 @@ public class AVA implements DerEncoder {
if (isTerminator(c, format)) {
break;
}
int cVal = hexDigits.indexOf(Character.toUpperCase((char)c));
if (cVal == -1) {
throw new IOException("AVA parse, invalid hex " +
"digit: "+ (char)c);
try {
int cVal = hex.fromHexDigit(c); // throws on invalid character
if ((cNdx % 2) == 1) {
b = (byte)((b * 16) + (byte)(cVal));
baos.write(b);
} else {
b = (byte)(cVal);
}
cNdx++;
} catch (NumberFormatException nfe) {
throw new IOException("AVA parse, invalid hex digit: "+ (char)c);
}
if ((cNdx % 2) == 1) {
b = (byte)((b * 16) + (byte)(cVal));
baos.write(b);
} else {
b = (byte)(cVal);
}
cNdx++;
}
// throw exception if no hex digits
@ -511,13 +502,14 @@ public class AVA implements DerEncoder {
private static Byte getEmbeddedHexPair(int c1, Reader in)
throws IOException {
if (hexDigits.indexOf(Character.toUpperCase((char)c1)) >= 0) {
HexFormat hex = HexFormat.of();
if (hex.isHexDigit(c1)) {
int c2 = readChar(in, "unexpected EOF - " +
"escaped hex value must include two valid digits");
if (hexDigits.indexOf(Character.toUpperCase((char)c2)) >= 0) {
int hi = Character.digit((char)c1, 16);
int lo = Character.digit((char)c2, 16);
if (hex.isHexDigit(c2)) {
int hi = hex.fromHexDigit(c1);
int lo = hex.fromHexDigit(c2);
return (byte)((hi<<4) + lo);
} else {
throw new IOException
@ -737,11 +729,7 @@ public class AVA implements DerEncoder {
throw new IllegalArgumentException("DER Value conversion");
}
typeAndValue.append('#');
for (int j = 0; j < data.length; j++) {
byte b = data[j];
typeAndValue.append(Character.forDigit(0xF & (b >>> 4), 16));
typeAndValue.append(Character.forDigit(0xF & b, 16));
}
HexFormat.of().formatHex(typeAndValue, data);
} else {
/*
* 2.4 (cont): Otherwise, if the AttributeValue is of a type which
@ -806,15 +794,7 @@ public class AVA implements DerEncoder {
// embed non-printable/non-escaped char
// as escaped hex pairs for debugging
byte[] valueBytes = Character.toString(c).getBytes(UTF_8);
for (int j = 0; j < valueBytes.length; j++) {
sbuffer.append('\\');
char hexChar = Character.forDigit
(0xF & (valueBytes[j] >>> 4), 16);
sbuffer.append(Character.toUpperCase(hexChar));
hexChar = Character.forDigit
(0xF & (valueBytes[j]), 16);
sbuffer.append(Character.toUpperCase(hexChar));
}
HexFormat.of().withPrefix("\\").withUpperCase().formatHex(sbuffer, valueBytes);
} else {
// append non-printable/non-escaped char
@ -884,11 +864,7 @@ public class AVA implements DerEncoder {
throw new IllegalArgumentException("DER Value conversion");
}
typeAndValue.append('#');
for (int j = 0; j < data.length; j++) {
byte b = data[j];
typeAndValue.append(Character.forDigit(0xF & (b >>> 4), 16));
typeAndValue.append(Character.forDigit(0xF & b, 16));
}
HexFormat.of().formatHex(typeAndValue, data);
} else {
/*
* 2.4 (cont): Otherwise, if the AttributeValue is of a type which
@ -960,15 +936,8 @@ public class AVA implements DerEncoder {
// as escaped hex pairs for debugging
previousWhite = false;
byte[] valueBytes = Character.toString(c).getBytes(UTF_8);
for (int j = 0; j < valueBytes.length; j++) {
sbuffer.append('\\');
sbuffer.append(Character.forDigit
(0xF & (valueBytes[j] >>> 4), 16));
sbuffer.append(Character.forDigit
(0xF & (valueBytes[j]), 16));
}
HexFormat.of().withPrefix("\\").withUpperCase().formatHex(sbuffer, valueBytes);
} else {
// append non-printable/non-escaped char
@ -1042,11 +1011,7 @@ public class AVA implements DerEncoder {
byte[] data = value.toByteArray();
retval.append('#');
for (int i = 0; i < data.length; i++) {
retval.append(hexDigits.charAt((data [i] >> 4) & 0x0f));
retval.append(hexDigits.charAt(data [i] & 0x0f));
}
HexFormat.of().formatHex(retval, data);
} else {
boolean quoteNeeded = false;
@ -1106,15 +1071,7 @@ public class AVA implements DerEncoder {
// embed escaped hex pairs
byte[] valueBytes =
Character.toString(c).getBytes(UTF_8);
for (int j = 0; j < valueBytes.length; j++) {
sbuffer.append('\\');
char hexChar = Character.forDigit
(0xF & (valueBytes[j] >>> 4), 16);
sbuffer.append(Character.toUpperCase(hexChar));
hexChar = Character.forDigit
(0xF & (valueBytes[j]), 16);
sbuffer.append(Character.toUpperCase(hexChar));
}
HexFormat.of().withPrefix("\\").withUpperCase().formatHex(sbuffer, valueBytes);
} else {
// append non-printable/non-escaped char

@ -1932,26 +1932,10 @@ public class X509CertImpl extends X509Certificate implements DerEncoder {
byte[] encCertInfo = cert.getEncoded();
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] digest = md.digest(encCertInfo);
StringBuilder sb = new StringBuilder(digest.length * 2);
for (int i = 0; i < digest.length; i++) {
byte2hex(digest[i], sb);
}
return sb.toString();
return HexFormat.of().withUpperCase().formatHex(digest);
} catch (NoSuchAlgorithmException | CertificateEncodingException e) {
// ignored
}
return "";
}
/**
* Converts a byte to hex digit and writes to the supplied builder
*/
private static void byte2hex(byte b, StringBuilder buf) {
char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F' };
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high])
.append(hexChars[low]);
}
}