8258796: [test] Apply HexFormat to tests for java.security

Reviewed-by: xuelei
This commit is contained in:
Roger Riggs 2021-01-08 21:32:54 +00:00
parent 876c7fb5f7
commit 628c546bea
43 changed files with 292 additions and 677 deletions

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 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
@ -25,6 +25,7 @@ import java.nio.ByteBuffer;
import java.security.AlgorithmParameters;
import java.security.Provider;
import java.security.Security;
import java.util.HexFormat;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
@ -102,7 +103,7 @@ public class SameBuffer {
String padding, int keyLength, int textLength, int AADLength,
int offset) throws Exception {
System.out.println("Testing " + keyLength + " key length; "
+ textLength + " text lenght; " + AADLength + " AAD length; "
+ textLength + " text length; " + AADLength + " AAD length; "
+ offset + " offset");
if (keyLength > Cipher.getMaxAllowedKeyLength(algo)) {
// skip this if this key length is larger than what's
@ -239,12 +240,12 @@ public class SameBuffer {
* Check if two results are equal
*/
private void runGCMWithSeparateArray(int mode, byte[] AAD, byte[] text,
int txtOffset, int lenght, int offset, AlgorithmParameters params)
int txtOffset, int length, int offset, AlgorithmParameters params)
throws Exception {
// first, generate the cipher text at an allocated buffer
Cipher cipher = createCipher(mode, params);
cipher.updateAAD(AAD);
byte[] outputText = cipher.doFinal(text, txtOffset, lenght);
byte[] outputText = cipher.doFinal(text, txtOffset, length);
// new cipher for encrypt operation
Cipher anotherCipher = createCipher(mode, params);
@ -252,17 +253,17 @@ public class SameBuffer {
// next, generate cipher text again at the same buffer of plain text
int myoff = offset;
int off = anotherCipher.update(text, txtOffset, lenght, text, myoff);
int off = anotherCipher.update(text, txtOffset, length, text, myoff);
anotherCipher.doFinal(text, myoff + off);
// check if two resutls are equal
if (!isEqual(text, myoff, outputText, 0, outputText.length)) {
System.err.println(
"\noutputText: len = " + outputText.length + " txtOffset = " + txtOffset + "\n" +
jdk.test.lib.Convert.byteArrayToHexString(outputText) + "\n" +
HexFormat.of().withUpperCase().formatHex(outputText) + "\n" +
"text: len = " + text.length + " myoff = " + myoff + "\n" +
jdk.test.lib.Convert.byteArrayToHexString(text) + "\n" +
"lenght " + lenght);
HexFormat.of().withUpperCase().formatHex(text) + "\n" +
"length " + length);
System.err.println("tlen = " + params.getParameterSpec(GCMParameterSpec.class).getTLen() / 8);
throw new RuntimeException("Two results not equal, mode:" + mode);
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 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
@ -112,33 +112,4 @@ public class BlowfishTestVector {
}
System.out.println("Test passed");
}
/*
* Converts a byte to hex digit and writes to the supplied buffer
*/
static 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
*/
static 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();
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -45,9 +45,9 @@ public class ChaCha20KAT {
public TestData(String name, String keyStr, String nonceStr, int ctr,
int dir, String inputStr, String aadStr, String outStr) {
testName = Objects.requireNonNull(name);
key = Convert.hexStringToByteArray(Objects.requireNonNull(keyStr));
nonce = Convert.hexStringToByteArray(
Objects.requireNonNull(nonceStr));
HexFormat hex = HexFormat.of();
key = hex.parseHex(Objects.requireNonNull(keyStr));
nonce = hex.parseHex(Objects.requireNonNull(nonceStr));
if ((counter = ctr) < 0) {
throw new IllegalArgumentException(
"counter must be 0 or greater");
@ -58,12 +58,9 @@ public class ChaCha20KAT {
throw new IllegalArgumentException(
"Direction must be ENCRYPT_MODE or DECRYPT_MODE");
}
input = Convert.hexStringToByteArray(
Objects.requireNonNull(inputStr));
aad = (aadStr != null) ?
Convert.hexStringToByteArray(aadStr) : null;
expOutput = Convert.hexStringToByteArray(
Objects.requireNonNull(outStr));
input = hex.parseHex(Objects.requireNonNull(inputStr));
aad = (aadStr != null) ? hex.parseHex(aadStr) : null;
expOutput = hex.parseHex(Objects.requireNonNull(outStr));
}
public final String testName;

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -30,13 +30,12 @@
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidParameterException;
import java.util.HexFormat;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.ChaCha20ParameterSpec;
import jdk.test.lib.Utils;
public class ChaCha20KeyGeneratorTest {
public static void main(String[] args) throws Exception {
@ -44,7 +43,7 @@ public class ChaCha20KeyGeneratorTest {
try {
generator.init(new ChaCha20ParameterSpec(
Utils.toByteArray("100000000000000000000000"), 0));
HexFormat.of().parseHex("100000000000000000000000"), 0));
throw new RuntimeException(
"ChaCha20 key generation should not consume AlgorithmParameterSpec");
} catch (InvalidAlgorithmParameterException e) {
@ -65,7 +64,7 @@ public class ChaCha20KeyGeneratorTest {
generator.init(256);
SecretKey key = generator.generateKey();
byte[] keyValue = key.getEncoded();
System.out.println("Key: " + Utils.toHexString(keyValue));
System.out.println("Key: " + HexFormat.of().formatHex(keyValue));
if (keyValue.length != 32) {
throw new RuntimeException("The size of generated key must be 256");
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -25,7 +25,6 @@
* @test
* @bug 8153029
* @library /test/lib
* @build jdk.test.lib.Convert
* @run main ChaCha20NoReuse
* @summary ChaCha20 Cipher Implementation (key/nonce reuse protection)
*/
@ -39,7 +38,6 @@ import javax.crypto.spec.SecretKeySpec;
import javax.crypto.AEADBadTagException;
import javax.crypto.SecretKey;
import java.security.InvalidKeyException;
import jdk.test.lib.Convert;
public class ChaCha20NoReuse {
@ -76,9 +74,9 @@ public class ChaCha20NoReuse {
public TestData(String name, String keyStr, String nonceStr, int ctr,
int dir, String inputStr, String aadStr, String outStr) {
testName = Objects.requireNonNull(name);
key = Convert.hexStringToByteArray(Objects.requireNonNull(keyStr));
nonce = Convert.hexStringToByteArray(
Objects.requireNonNull(nonceStr));
HexFormat hex = HexFormat.of();
key = hex.parseHex(keyStr);
nonce = hex.parseHex(nonceStr);
if ((counter = ctr) < 0) {
throw new IllegalArgumentException(
"counter must be 0 or greater");
@ -89,12 +87,9 @@ public class ChaCha20NoReuse {
throw new IllegalArgumentException(
"Direction must be ENCRYPT_MODE or DECRYPT_MODE");
}
input = Convert.hexStringToByteArray(
Objects.requireNonNull(inputStr));
aad = (aadStr != null) ?
Convert.hexStringToByteArray(aadStr) : null;
expOutput = Convert.hexStringToByteArray(
Objects.requireNonNull(outStr));
input = hex.parseHex(inputStr);
aad = (aadStr != null) ? hex.parseHex(aadStr) : null;
expOutput = hex.parseHex(outStr);
}
public final String testName;

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -25,7 +25,6 @@
* @test
* @bug 8153029 8257769
* @library /test/lib
* @build jdk.test.lib.Convert
* @run main ChaCha20Poly1305ParamTest
* @summary ChaCha20 Cipher Implementation (parameters)
*/
@ -53,9 +52,9 @@ public class ChaCha20Poly1305ParamTest {
public TestData(String name, String keyStr, String nonceStr, int ctr,
int dir, String inputStr, String aadStr, String outStr) {
testName = Objects.requireNonNull(name);
key = Convert.hexStringToByteArray(Objects.requireNonNull(keyStr));
nonce = Convert.hexStringToByteArray(
Objects.requireNonNull(nonceStr));
HexFormat hex = HexFormat.of();
key = hex.parseHex(keyStr);
nonce = hex.parseHex(nonceStr);
if ((counter = ctr) < 0) {
throw new IllegalArgumentException(
"counter must be 0 or greater");
@ -66,12 +65,9 @@ public class ChaCha20Poly1305ParamTest {
throw new IllegalArgumentException(
"Direction must be ENCRYPT_MODE or DECRYPT_MODE");
}
input = Convert.hexStringToByteArray(
Objects.requireNonNull(inputStr));
aad = (aadStr != null) ?
Convert.hexStringToByteArray(aadStr) : null;
expOutput = Convert.hexStringToByteArray(
Objects.requireNonNull(outStr));
input = hex.parseHex(inputStr);
aad = (aadStr != null) ? hex.parseHex(aadStr) : null;
expOutput = hex.parseHex(outStr);
}
public final String testName;

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -35,6 +35,7 @@ import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HexFormat;
import javax.crypto.Cipher;
import javax.crypto.spec.ChaCha20ParameterSpec;
@ -46,10 +47,9 @@ import jdk.test.lib.Utils;
public class ChaCha20CipherUnitTest {
private static final byte[] NONCE
= Utils.toByteArray("012345670123456701234567");
= HexFormat.of().parseHex("012345670123456701234567");
private static final SecretKeySpec KEY = new SecretKeySpec(
Utils.toByteArray(
"0123456701234567012345670123456701234567012345670123456701234567"),
HexFormat.of().parseHex("0123456701234567012345670123456701234567012345670123456701234567"),
"ChaCha20");
private static final ChaCha20ParameterSpec CHACHA20_PARAM_SPEC
= new ChaCha20ParameterSpec(NONCE, 0);
@ -165,7 +165,7 @@ public class ChaCha20CipherUnitTest {
}
private static void testAEAD() throws Exception {
byte[] expectedPlainttext = Utils.toByteArray("01234567");
byte[] expectedPlainttext = HexFormat.of().parseHex("01234567");
byte[] ciphertext = testUpdateAAD(Cipher.ENCRYPT_MODE, expectedPlainttext);
byte[] plaintext = testUpdateAAD(Cipher.DECRYPT_MODE, ciphertext);
if (!Arrays.equals(plaintext, expectedPlainttext)) {
@ -180,7 +180,7 @@ public class ChaCha20CipherUnitTest {
String opModeName = getOpModeName(opMode);
System.out.println("== updateAAD (" + opModeName + ") ==");
byte[] aad = Utils.toByteArray("0000");
byte[] aad = HexFormat.of().parseHex("0000");
ByteBuffer aadBuf = ByteBuffer.wrap(aad);
Cipher cipher = Cipher.getInstance("ChaCha20");

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 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
@ -34,6 +34,7 @@ import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
import java.util.HexFormat;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
@ -51,6 +52,10 @@ import javax.crypto.interfaces.*;
public class DHKeyAgreement2 {
private static final String SUNJCE = "SunJCE";
// Hex formatter to upper case with ":" delimiter
private static final HexFormat HEX_FORMATTER = HexFormat.ofDelimiter(":").withUpperCase();
private DHKeyAgreement2() {}
public static void main(String argv[]) throws Exception {
@ -209,8 +214,8 @@ public class DHKeyAgreement2 {
System.out.println("EXPECTED: " + e.getMessage());
}
System.out.println("Alice secret: " + toHexString(aliceSharedSecret));
System.out.println("Bob secret: " + toHexString(bobSharedSecret));
System.out.println("Alice secret: " + HEX_FORMATTER.formatHex(aliceSharedSecret));
System.out.println("Bob secret: " + HEX_FORMATTER.formatHex(bobSharedSecret));
if (aliceLen != bobLen) {
throw new Exception("Shared secrets have different lengths");
@ -262,23 +267,6 @@ public class DHKeyAgreement2 {
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();
}
/*
* Prints the usage of this test.
*/

@ -1,5 +1,5 @@
/*
* Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 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
@ -33,6 +33,7 @@ import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
import java.util.HexFormat;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
@ -47,6 +48,9 @@ import javax.crypto.interfaces.*;
public class DHKeyAgreement3 {
// Hex formatter to upper case with ":" delimiter
private static final HexFormat HEX_FORMATTER = HexFormat.ofDelimiter(":").withUpperCase();
private DHKeyAgreement3() {}
public static void main(String argv[]) throws Exception {
@ -120,15 +124,15 @@ public class DHKeyAgreement3 {
// Alice, Bob and Carol compute their secrets
byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
int aliceLen = aliceSharedSecret.length;
System.out.println("Alice secret: " + toHexString(aliceSharedSecret));
System.out.println("Alice secret: " + HEX_FORMATTER.formatHex(aliceSharedSecret));
byte[] bobSharedSecret = bobKeyAgree.generateSecret();
int bobLen = bobSharedSecret.length;
System.out.println("Bob secret: " + toHexString(bobSharedSecret));
System.out.println("Bob secret: " + HEX_FORMATTER.formatHex(bobSharedSecret));
byte[] carolSharedSecret = carolKeyAgree.generateSecret();
int carolLen = carolSharedSecret.length;
System.out.println("Carol secret: " + toHexString(carolSharedSecret));
System.out.println("Carol secret: " + HEX_FORMATTER.formatHex(carolSharedSecret));
// Compare Alice and Bob
@ -167,23 +171,6 @@ public class DHKeyAgreement3 {
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();
}
/*
* Prints the usage of this test.
*/

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
@ -37,6 +37,8 @@ import java.util.*;
public class PBKDF2HmacSHA1FactoryTest {
// Hex formatter to upper case with "" delimiter
private static final HexFormat HEX_FORMATTER = HexFormat.of();
private static final String ALGO = "PBKDF2WithHmacSHA1";
static final int[] KEY_SIZES = { 128, 256 }; // in bits
@ -51,7 +53,7 @@ public class PBKDF2HmacSHA1FactoryTest {
"01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86"),
new TestVector(1200, "password", "ATHENA.MIT.EDUraeburn",
"5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13"),
new TestVector(5, "password", fromHexString("1234567878563412"),
new TestVector(5, "password", HEX_FORMATTER.parseHex("1234567878563412"),
"d1daa78615f287e6a1c8b120d7062a493f98d203e6be49a6adf4fa574b6e64ee"),
new TestVector(1200,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
@ -61,7 +63,7 @@ public class PBKDF2HmacSHA1FactoryTest {
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"pass phrase exceeds block size",
"9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a"),
new TestVector(50, fromHexString("f09d849e"),
new TestVector(50, HEX_FORMATTER.parseHex("f09d849e"),
"EXAMPLE.COMpianist",
"6b9cf26d45455a43a5b8bb276a403b39e7fe37a0c41e02c281ff3069e1e94f52"),
};
@ -83,8 +85,8 @@ public class PBKDF2HmacSHA1FactoryTest {
throw new Exception("Wrong length for derived key");
}
// Test generateSecret(...) using test vectors
if (!tv.expectedVals[j].equals(toHexString(derivedKey))) {
System.out.println("got: " + toHexString(derivedKey));
if (!tv.expectedVals[j].equals(HEX_FORMATTER.formatHex(derivedKey))) {
System.out.println("got: " + HEX_FORMATTER.formatHex(derivedKey));
System.out.println("expected: " + tv.expectedVals[j]);
throw new Exception("Wrong value for derived key");
}
@ -109,31 +111,6 @@ public class PBKDF2HmacSHA1FactoryTest {
return false;
}
private static String toHexString(byte[] bytes) {
String mapping = "0123456789abcdef";
StringBuilder sb = new StringBuilder(bytes.length*2);
for (int i = 0; i < bytes.length; i++) {
int low = bytes[i] & 0x0f;
int high = ((bytes[i] >> 4) & 0x0f);
char[] res = new char[2];
res[0] = mapping.charAt(high);
res[1] = mapping.charAt(low);
sb.append(res);
}
return sb.toString();
}
private static byte[] fromHexString(String value) {
byte[] bytes = new byte[value.length()/2];
String mapping = "0123456789abcdef";
StringBuilder sb = new StringBuilder(bytes.length*2);
for (int i = 0; i < bytes.length; i++) {
String high = value.substring(2*i, 2*i+1);
String low = value.substring(2*i+1, 2*i+2);
bytes[i] = (byte) ((mapping.indexOf(high) << 4) +
mapping.indexOf(low));
}
return bytes;
}
public static void main (String[] args) throws Exception {
test();
System.out.println("Test Passed!");

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 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
@ -32,6 +32,7 @@ import java.io.*;
import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
import java.util.HexFormat;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
@ -47,6 +48,8 @@ import javax.crypto.interfaces.*;
public class TestLeadingZeroes {
private static final String SUNJCE = "SunJCE";
// Hex formatter to upper case with ":" delimiter
private static final HexFormat HEX_FORMATTER = HexFormat.ofDelimiter(":").withUpperCase();
private TestLeadingZeroes() {}
@ -74,7 +77,7 @@ public class TestLeadingZeroes {
aliceKeyAgree.init(alicePrivKey);
aliceKeyAgree.doPhase(bobPubKey, true);
byte[] sharedSecret = aliceKeyAgree.generateSecret();
System.out.println("shared secret:\n" + toHexString(sharedSecret));
System.out.println("shared secret:\n" + HEX_FORMATTER.formatHex(sharedSecret));
// verify that leading zero is present
if (sharedSecret.length != 128) {
@ -90,7 +93,7 @@ public class TestLeadingZeroes {
byte[] tlsPremasterSecret =
aliceKeyAgree.generateSecret("TlsPremasterSecret").getEncoded();
System.out.println(
"tls premaster secret:\n" + toHexString(tlsPremasterSecret));
"tls premaster secret:\n" + HEX_FORMATTER.formatHex(tlsPremasterSecret));
// check that leading zero has been stripped
if (tlsPremasterSecret.length != 127) {
@ -107,35 +110,6 @@ public class TestLeadingZeroes {
}
/*
* 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();
}
private static final byte alicePubKeyEnc[] = {
(byte)0x30, (byte)0x82, (byte)0x01, (byte)0x24,
(byte)0x30, (byte)0x81, (byte)0x99, (byte)0x06,

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -27,7 +27,6 @@
* @summary KeyLength support test for DiffieHellman, EC, XDH.
* Arguments order <KeyExchangeAlgorithm> <Provider> <KeyGenAlgorithm> <keyLen>
* @library /test/lib
* @build jdk.test.lib.Convert
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 512
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 768
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 832
@ -55,10 +54,10 @@ import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.security.spec.NamedParameterSpec;
import java.util.Arrays;
import java.util.HexFormat;
import javax.crypto.KeyAgreement;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import jdk.test.lib.Convert;
public class KeySizeTest {
@ -229,9 +228,9 @@ public class KeySizeTest {
private static boolean equals(byte[] actual, byte[] expected) {
boolean equals = Arrays.equals(actual, expected);
if (!equals) {
throw new RuntimeException(String.format("Actual array: %s, "
+ "Expected array:%s", Convert.byteArrayToHexString(actual),
Convert.byteArrayToHexString(expected)));
throw new RuntimeException(String.format("Actual array: %s, Expected array:%s",
HexFormat.of().withUpperCase().formatHex(actual),
HexFormat.of().withUpperCase().formatHex(expected)));
}
return equals;
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -35,7 +35,6 @@
* Arguments order <KeyExchangeAlgorithm> <Provider> <KeyGenAlgorithm>
* <keySize> <Curve*>
* @library /test/lib
* @build jdk.test.lib.Convert
* @run main NegativeTest DiffieHellman SunJCE DiffieHellman 1024
* @run main NegativeTest ECDH SunEC EC 256
* @run main NegativeTest XDH SunEC XDH 255 X25519
@ -58,8 +57,8 @@ import java.security.spec.X509EncodedKeySpec;
import java.security.spec.XECPrivateKeySpec;
import java.security.spec.XECPublicKeySpec;
import java.util.Arrays;
import java.util.HexFormat;
import javax.crypto.KeyAgreement;
import jdk.test.lib.Convert;
public class NegativeTest {
@ -128,8 +127,8 @@ public class NegativeTest {
} catch (InvalidKeySpecException e) {
System.out.printf("Expected InvalidKeySpecException for invalid "
+ "PrivateKey %s%n and modified encoding: %s, %s%n",
Convert.byteArrayToHexString(encoded),
Convert.byteArrayToHexString(modified), e.getMessage());
HexFormat.of().withUpperCase().formatHex(encoded),
HexFormat.of().withUpperCase().formatHex(modified), e.getMessage());
}
// Test modified PublicKey encoding
encoded = kp.getPublic().getEncoded();
@ -143,8 +142,8 @@ public class NegativeTest {
} catch (InvalidKeySpecException e) {
System.out.printf("Expected InvalidKeySpecException for invalid "
+ "PublicKey %s%n and modified encoding: %s, %s%n",
Convert.byteArrayToHexString(encoded),
Convert.byteArrayToHexString(modified), e.getMessage());
HexFormat.of().withUpperCase().formatHex(encoded),
HexFormat.of().withUpperCase().formatHex(modified), e.getMessage());
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019, 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
@ -27,18 +27,17 @@
* @summary Use SunJCE Mac in SecretKeyFactory PBKDF2 implementation
* @library evilprov.jar
* @library /test/lib
* @build jdk.test.lib.Convert
* @run main/othervm SecKeyFacSunJCEPrf
*/
import java.util.Arrays;
import java.util.HexFormat;
import javax.crypto.SecretKeyFactory;
import javax.crypto.SecretKey;
import javax.crypto.spec.PBEKeySpec;
import java.security.Provider;
import java.security.Security;
import com.evilprovider.*;
import jdk.test.lib.Convert;
public class SecKeyFacSunJCEPrf {
@ -46,8 +45,8 @@ public class SecKeyFacSunJCEPrf {
private static final byte[] SALT = "salt".getBytes();
private static final char[] PASS = "password".toCharArray();
private static final int ITER = 4096;
private static final byte[] EXP_OUT = Convert.hexStringToByteArray(
"4B007901B765489ABEAD49D926F721D065A429C1");
private static final byte[] EXP_OUT =
HexFormat.of().parseHex("4B007901B765489ABEAD49D926F721D065A429C1");
public static void main(String[] args) throws Exception {
// Instantiate the Evil Provider and insert it in the
@ -62,13 +61,13 @@ public class SecKeyFacSunJCEPrf {
SecretKey secKey1 = pbkdf2.generateSecret(pbks);
System.out.println("PBKDF2WithHmacSHA1:\n" +
Convert.byteArrayToHexString(secKey1.getEncoded()));
HexFormat.of().withUpperCase().formatHex(secKey1.getEncoded()));
if (Arrays.equals(secKey1.getEncoded(), EXP_OUT)) {
System.out.println("Test Vector Passed");
} else {
System.out.println("Test Vector Failed");
System.out.println("Expected Output:\n" +
Convert.byteArrayToHexString(EXP_OUT));
HexFormat.of().withUpperCase().formatHex(EXP_OUT));
throw new RuntimeException();
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019, 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
@ -21,8 +21,6 @@
* questions.
*/
import jdk.test.lib.Convert;
import java.security.*;
import java.security.spec.*;
import java.math.*;
@ -79,10 +77,8 @@ public class SignatureDigestTruncate {
private static void assertEquals(byte[] expected, byte[] actual,
String name) {
if (!Arrays.equals(actual, expected)) {
System.out.println("expect: "
+ Convert.byteArrayToHexString(expected));
System.out.println("actual: "
+ Convert.byteArrayToHexString(actual));
System.out.println("expect: " + HexFormat.of().withUpperCase().formatHex(expected));
System.out.println("actual: " + HexFormat.of().withUpperCase().formatHex(actual));
throw new RuntimeException("Incorrect " + name + " value");
}
}
@ -93,10 +89,11 @@ public class SignatureDigestTruncate {
System.out.println("Testing " + alg + " with " + curveName);
byte[] privateKey = Convert.hexStringToByteArray(privateKeyStr);
byte[] msg = Convert.hexStringToByteArray(msgStr);
byte[] k = Convert.hexStringToByteArray(kStr);
byte[] expectedSig = Convert.hexStringToByteArray(sigStr);
HexFormat hex = HexFormat.of();
byte[] privateKey = hex.parseHex(privateKeyStr);
byte[] msg = hex.parseHex(msgStr);
byte[] k = hex.parseHex(kStr);
byte[] expectedSig = hex.parseHex(sigStr);
AlgorithmParameters params =
AlgorithmParameters.getInstance("EC", "SunEC");

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 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
@ -54,7 +54,7 @@ public class SignatureKAT {
private BigInteger pubY;
private static BigInteger toBigInteger(String hex) {
byte[] bytes = Convert.hexStringToByteArray(checkHex(hex));
byte[] bytes = HexFormat.of().parseHex(checkHex(hex));
return new BigInteger(1, bytes);
}
CurveData(String name, String msg, String priv, String pubX,
@ -79,7 +79,7 @@ public class SignatureKAT {
s != checkHex(s)) {
throw new RuntimeException("Error: invalid r, s");
}
this.expSig = Convert.hexStringToByteArray(r + s);
this.expSig = HexFormat.of().parseHex(r + s);
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 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
@ -39,6 +39,8 @@ import java.security.spec.EdECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.NamedParameterSpec;
import java.util.Arrays;
import java.util.HexFormat;
import jdk.test.lib.Convert;
/*
@ -214,8 +216,8 @@ public class EdDSAKeySize {
private static void equals(byte[] actual, byte[] expected) {
if (!Arrays.equals(actual, expected)) {
throw new RuntimeException(String.format("Actual array: %s, "
+ "Expected array:%s", Convert.byteArrayToHexString(actual),
Convert.byteArrayToHexString(expected)));
+ "Expected array:%s", HexFormat.of().withUpperCase().formatHex(actual),
HexFormat.of().withUpperCase().formatHex(expected)));
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 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
@ -34,14 +34,13 @@ import java.security.interfaces.EdECPrivateKey;
import java.security.interfaces.EdECPublicKey;
import java.security.spec.EdDSAParameterSpec;
import java.util.Arrays;
import jdk.test.lib.Convert;
import java.util.HexFormat;
/*
* @test
* @bug 8209632
* @summary Negative cases for EDDSA.
* @library /test/lib
* @build jdk.test.lib.Convert
* @run main EdDSANegativeTest
*/
public class EdDSANegativeTest {
@ -138,7 +137,7 @@ public class EdDSANegativeTest {
new byte[255], new byte[500]}) {
System.out.printf("Testing signature for name: %s, algorithm "
+ "spec: (prehash:%s, context:%s)%n", name, preHash,
Convert.byteArrayToHexString(context));
HexFormat.of().withUpperCase().formatHex(context));
try {
verify(sig, kp.getPublic(), MSG,
new EdDSAParameterSpec(preHash, context),
@ -219,8 +218,8 @@ public class EdDSANegativeTest {
throw new RuntimeException(String.format("Signature verification"
+ " success with different param context(actual:%s, "
+ "expected:%s), Prehash(actual:%s, expected:%s)",
Convert.byteArrayToHexString(context),
Convert.byteArrayToHexString(initContext),
HexFormat.of().withUpperCase().formatHex(context),
HexFormat.of().withUpperCase().formatHex(initContext),
preHash, initPreHash));
} else {
System.out.println("Atleast a case matched");
@ -253,8 +252,8 @@ public class EdDSANegativeTest {
boolean equals = Arrays.equals(actual, expected);
if (!equals) {
throw new RuntimeException(String.format("Actual array: %s, "
+ "Expected array:%s", Convert.byteArrayToHexString(actual),
Convert.byteArrayToHexString(expected)));
+ "Expected array:%s", HexFormat.of().withUpperCase().formatHex(actual),
HexFormat.of().withUpperCase().formatHex(expected)));
}
return equals;
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 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
@ -28,7 +28,7 @@ import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.EdDSAParameterSpec;
import java.util.Arrays;
import jdk.test.lib.Convert;
import java.util.HexFormat;
/*
* @test
@ -78,7 +78,7 @@ public class EdDSAParamSpec {
for (byte[] context : new byte[][]{"others".getBytes(), maxCtx}) {
System.out.printf("Testing signature for name: %s,"
+ " algorithm spec: (prehash:%s, context:%s)%n",
name, preHash, Convert.byteArrayToHexString(context));
name, preHash, HexFormat.of().withUpperCase().formatHex(context));
EdDSAParameterSpec params
= new EdDSAParameterSpec(preHash, context);
verifyPublic(sig, kp.getPublic(), MSG, params, initParam,
@ -129,8 +129,8 @@ public class EdDSAParamSpec {
throw new RuntimeException(String.format("Signature verification"
+ " success with different param context(actual:%s, "
+ "expected:%s), Prehash(actual:%s, expected:%s)",
Convert.byteArrayToHexString(context),
Convert.byteArrayToHexString(initContext),
HexFormat.of().withUpperCase().formatHex(context),
HexFormat.of().withUpperCase().formatHex(initContext),
preHash, initPreHash));
} else {
System.out.println("Atleast a case matched");
@ -165,8 +165,8 @@ public class EdDSAParamSpec {
boolean equals = Arrays.equals(actual, expected);
if (!equals) {
throw new RuntimeException(String.format("Actual array: %s, "
+ "Expected array:%s", Convert.byteArrayToHexString(actual),
Convert.byteArrayToHexString(expected)));
+ "Expected array:%s", HexFormat.of().withUpperCase().formatHex(actual),
HexFormat.of().withUpperCase().formatHex(expected)));
}
return equals;
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 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
@ -49,7 +49,7 @@ import java.security.spec.InvalidKeySpecException;
import java.security.spec.NamedParameterSpec;
import java.security.spec.EdDSAParameterSpec;
import java.util.Arrays;
import jdk.test.lib.Convert;
import java.util.HexFormat;
/*
* @test
@ -349,8 +349,8 @@ public class EdDSATest {
private static void equals(byte[] actual, byte[] expected) {
if (!Arrays.equals(actual, expected)) {
throw new RuntimeException(String.format("Actual array: %s, "
+ "Expected array:%s", Convert.byteArrayToHexString(actual),
Convert.byteArrayToHexString(expected)));
+ "Expected array:%s", HexFormat.of().withUpperCase().formatHex(actual),
HexFormat.of().withUpperCase().formatHex(expected)));
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 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
@ -39,8 +39,6 @@ import java.nio.file.*;
import java.math.*;
import java.util.*;
import jdk.test.lib.Convert;
import sun.security.util.*;
public class EdECKeyFormat {
@ -98,7 +96,7 @@ public class EdECKeyFormat {
private static void pubKeyTest(Provider p, String key) throws Exception {
// ensure that a properly-formatted key can be read
byte[] encodedKey = Convert.hexStringToByteArray(key);
byte[] encodedKey = HexFormat.of().parseHex(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
KeyFactory kf = KeyFactory.getInstance("EdDSA", p);
kf.generatePublic(keySpec);
@ -125,7 +123,7 @@ public class EdECKeyFormat {
checkPrivKeyFormat(keySpec.getEncoded());
// ensure that a properly-formatted key can be read
byte[] encodedKey = Convert.hexStringToByteArray(privKeys.get(algName));
byte[] encodedKey = HexFormat.of().parseHex(privKeys.get(algName));
keySpec = new PKCS8EncodedKeySpec(encodedKey);
kf.generatePrivate(keySpec);
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 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
@ -116,7 +116,7 @@ public class TestEdDSA {
"09351fc9ac90b3ecfdfbc7c66431e0303dca179c138ac17ad9bef1177331a704");
// Ed25519ctx
byte[] context = Convert.hexStringToByteArray("666f6f");
byte[] context = HexFormat.of().parseHex("666f6f");
runSignTest("Ed25519", new EdDSAParameterSpec(false, context),
"0305334e381af78f141cb666f6199f57bc3495335a256a95bd2a55bf546663f6",
"dfc9425e4f968f7f0c29f0259cf5f9aed6851c2bb4ad8bfb860cfee0ab248292",
@ -124,7 +124,7 @@ public class TestEdDSA {
"55a4cc2f70a54e04288c5f4cd1e45a7bb520b36292911876cada7323198dd87a" +
"8b36950b95130022907a7fb7c4e9b2d5f6cca685a587b4b21f4b888e4e7edb0d");
context = Convert.hexStringToByteArray("626172");
context = HexFormat.of().parseHex("626172");
runSignTest("Ed25519", new EdDSAParameterSpec(false, context),
"0305334e381af78f141cb666f6199f57bc3495335a256a95bd2a55bf546663f6",
"dfc9425e4f968f7f0c29f0259cf5f9aed6851c2bb4ad8bfb860cfee0ab248292",
@ -132,7 +132,7 @@ public class TestEdDSA {
"fc60d5872fc46b3aa69f8b5b4351d5808f92bcc044606db097abab6dbcb1aee3" +
"216c48e8b3b66431b5b186d1d28f8ee15a5ca2df6668346291c2043d4eb3e90d");
context = Convert.hexStringToByteArray("666f6f");
context = HexFormat.of().parseHex("666f6f");
runSignTest("Ed25519", new EdDSAParameterSpec(false, context),
"0305334e381af78f141cb666f6199f57bc3495335a256a95bd2a55bf546663f6",
"dfc9425e4f968f7f0c29f0259cf5f9aed6851c2bb4ad8bfb860cfee0ab248292",
@ -140,7 +140,7 @@ public class TestEdDSA {
"8b70c1cc8310e1de20ac53ce28ae6e7207f33c3295e03bb5c0732a1d20dc6490" +
"8922a8b052cf99b7c4fe107a5abb5b2c4085ae75890d02df26269d8945f84b0b");
context = Convert.hexStringToByteArray("666f6f");
context = HexFormat.of().parseHex("666f6f");
runSignTest("Ed25519", new EdDSAParameterSpec(false, context),
"ab9c2853ce297ddab85c993b3ae14bcad39b2c682beabc27d6d4eb20711d6560",
"0f1d1274943b91415889152e893d80e93275a1fc0b65fd71b4b0dda10ad7d772",
@ -179,7 +179,7 @@ public class TestEdDSA {
"cee1afb2e027df36bc04dcecbf154336c19f0af7e0a6472905e799f1953d2a0f" +
"f3348ab21aa4adafd1d234441cf807c03a00");
context = Convert.hexStringToByteArray("666f6f");
context = HexFormat.of().parseHex("666f6f");
runSignTest("Ed448", new EdDSAParameterSpec(false, context),
"c4eab05d357007c632f3dbb48489924d552b08fe0c353a0d4a1f00acda2c463a" +
"fbea67c5e8d2877c5e3bc397a659949ef8021e954e0a12274e",
@ -325,9 +325,9 @@ public class TestEdDSA {
AlgorithmParameterSpec params, String privateKey, String publicKey,
String message, String signature) throws Exception {
byte[] privKeyBytes = Convert.hexStringToByteArray(privateKey);
byte[] privKeyBytes = HexFormat.of().parseHex(privateKey);
EdECPoint pubKeyPoint = Convert.hexStringToEdPoint(publicKey);
byte[] msgBytes = Convert.hexStringToByteArray(message);
byte[] msgBytes = HexFormat.of().parseHex(message);
byte[] computedSig;
NamedParameterSpec namedSpec = new NamedParameterSpec(algorithm);
@ -342,8 +342,7 @@ public class TestEdDSA {
sig.initSign(privKey);
sig.update(msgBytes);
computedSig = sig.sign();
if (!Arrays.equals(computedSig,
Convert.hexStringToByteArray(signature))) {
if (!Arrays.equals(computedSig, HexFormat.of().parseHex(signature))) {
throw new RuntimeException("Incorrect signature");
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 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
@ -26,7 +26,6 @@
* @bug 8166597
* @summary Test EdDSA basic operations
* @library /test/lib
* @build jdk.test.lib.Convert
* @modules java.base/sun.security.provider
* java.base/sun.security.util
* java.base/sun.security.util.math
@ -39,8 +38,9 @@ import sun.security.ec.ed.*;
import java.security.*;
import java.security.spec.*;
import java.util.Arrays;
import java.util.HexFormat;
import sun.security.provider.SHAKE256;
import jdk.test.lib.Convert;
public class TestEdOps {
@ -71,8 +71,8 @@ public class TestEdOps {
}
private static void runShakeTest(int outputLen, String msg, String digest) {
byte[] msgBytes = Convert.hexStringToByteArray(msg);
byte[] digestBytes = Convert.hexStringToByteArray(digest);
byte[] msgBytes = HexFormat.of().parseHex(msg);
byte[] digestBytes = HexFormat.of().parseHex(digest);
SHAKE256 md = new SHAKE256(outputLen);
md.update(msgBytes, 0, msgBytes.length);
byte[] computed = md.digest();
@ -178,14 +178,14 @@ public class TestEdOps {
EdDSAParameterSpec sigParams = new EdDSAParameterSpec(false);
byte[] privKeyBytes = Convert.hexStringToByteArray(privateKey);
byte[] pubKeyBytes = Convert.hexStringToByteArray(publicKey);
byte[] msgBytes = Convert.hexStringToByteArray(message);
HexFormat hex = HexFormat.of();
byte[] privKeyBytes = hex.parseHex(privateKey);
byte[] pubKeyBytes = hex.parseHex(publicKey);
byte[] msgBytes = hex.parseHex(message);
byte[] computedSig = ops.sign(sigParams, privKeyBytes, msgBytes);
if (!Arrays.equals(computedSig,
Convert.hexStringToByteArray(signature))) {
if (!Arrays.equals(computedSig, hex.parseHex(signature))) {
throw new RuntimeException("Incorrect signature: " +
Convert.byteArrayToHexString(computedSig) + " != " + signature);
HexFormat.of().withUpperCase().formatHex(computedSig) + " != " + signature);
}
// Test public key computation
EdECPoint pubPoint = ops.computePublic(privKeyBytes);
@ -262,7 +262,7 @@ public class TestEdOps {
// y value too large
testInvalidPoint(NamedParameterSpec.ED448,
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" +
"fffffffffffffffffffffffffffffffffffffffffffffffffff00");
"ffffffffffffffffffffffffffffffffffffffffffffffffffff00");
// not square
testInvalidPoint(NamedParameterSpec.ED448,
"43ba28f430cdfe456ae531545f7ecd0ac834a55c9358c0372bfa0c6c6798c086" +
@ -277,7 +277,7 @@ public class TestEdOps {
private static void testInvalidPoint(NamedParameterSpec curve,
String pointStr) throws Exception {
byte[] encodedPoint = Convert.hexStringToByteArray(pointStr);
byte[] encodedPoint = HexFormat.of().parseHex(pointStr);
EdDSAParameters params =
EdDSAParameters.get(RuntimeException::new, curve);
EdDSAOperations ops = new EdDSAOperations(params);

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -34,8 +34,11 @@ import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import java.util.Arrays;
import java.math.BigInteger;
import java.util.HexFormat;
import jdk.test.lib.Convert;
import jdk.test.lib.hexdump.ASN1Formatter;
import jdk.test.lib.hexdump.HexPrinter;
public class TestXDH {
@ -334,10 +337,10 @@ public class TestXDH {
String b_pub, String result) throws Exception {
KeyFactory kf = KeyFactory.getInstance("XDH");
byte[] a_pri_ba = Convert.hexStringToByteArray(a_pri);
byte[] a_pri_ba = HexFormat.of().parseHex(a_pri);
KeySpec privateSpec = new PKCS8EncodedKeySpec(a_pri_ba);
PrivateKey privateKey = kf.generatePrivate(privateSpec);
byte[] b_pub_ba = Convert.hexStringToByteArray(b_pub);
byte[] b_pub_ba = HexFormat.of().parseHex(b_pub);
KeySpec publicSpec = new X509EncodedKeySpec(b_pub_ba);
PublicKey publicKey = kf.generatePublic(publicSpec);
@ -346,10 +349,10 @@ public class TestXDH {
ka.doPhase(publicKey, true);
byte[] sharedSecret = ka.generateSecret();
byte[] expectedResult = Convert.hexStringToByteArray(result);
byte[] expectedResult = HexFormat.of().parseHex(result);
if (!Arrays.equals(sharedSecret, expectedResult)) {
throw new RuntimeException("fail: expected=" + result + ", actual="
+ Convert.byteArrayToHexString(sharedSecret));
+ HexFormat.of().withUpperCase().formatHex(sharedSecret));
}
}
@ -360,7 +363,7 @@ public class TestXDH {
NamedParameterSpec paramSpec = new NamedParameterSpec(curveName);
KeyFactory kf = KeyFactory.getInstance("XDH");
KeySpec privateSpec = new XECPrivateKeySpec(paramSpec,
Convert.hexStringToByteArray(a_pri));
HexFormat.of().parseHex(a_pri));
PrivateKey privateKey = kf.generatePrivate(privateSpec);
boolean clearHighBit = curveName.equals("X25519");
KeySpec publicSpec = new XECPublicKeySpec(paramSpec,
@ -369,20 +372,25 @@ public class TestXDH {
byte[] encodedPrivateKey = privateKey.getEncoded();
System.out.println("Encoded private: " +
Convert.byteArrayToHexString(encodedPrivateKey));
HexFormat.of().withUpperCase().formatHex(encodedPrivateKey));
System.out.println(HexPrinter.simple()
.formatter(ASN1Formatter.formatter())
.toString(encodedPrivateKey));
byte[] encodedPublicKey = publicKey.getEncoded();
System.out.println("Encoded public: " +
Convert.byteArrayToHexString(encodedPublicKey));
HexFormat.of().withUpperCase().formatHex(encodedPublicKey));
System.out.println(HexPrinter.simple()
.formatter(ASN1Formatter.formatter())
.toString(encodedPublicKey));
KeyAgreement ka = KeyAgreement.getInstance("XDH");
ka.init(privateKey);
ka.doPhase(publicKey, true);
byte[] sharedSecret = ka.generateSecret();
byte[] expectedResult = Convert.hexStringToByteArray(result);
byte[] expectedResult = HexFormat.of().parseHex(result);
if (!Arrays.equals(sharedSecret, expectedResult)) {
throw new RuntimeException("fail: expected=" + result + ", actual="
+ Convert.byteArrayToHexString(sharedSecret));
+ HexFormat.of().withUpperCase().formatHex(sharedSecret));
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -95,9 +95,9 @@ public class TestXECOps {
byte[] basePoint = Convert.byteToByteArray(settings.getBasePoint(),
settings.getBytes());
byte[] a = Convert.hexStringToByteArray(a_str);
byte[] b = Convert.hexStringToByteArray(b_str);
byte[] expectedResult = Convert.hexStringToByteArray(result_str);
byte[] a = HexFormat.of().parseHex(a_str);
byte[] b = HexFormat.of().parseHex(b_str);
byte[] expectedResult = HexFormat.of().parseHex(result_str);
byte[] a_copy = Arrays.copyOf(a, a.length);
byte[] b_copy = Arrays.copyOf(b, b.length);
@ -118,9 +118,9 @@ public class TestXECOps {
private void runTest(String opName, String k_in_str,
String u_in_str, String u_out_str) {
byte[] k_in = Convert.hexStringToByteArray(k_in_str);
byte[] u_in = Convert.hexStringToByteArray(u_in_str);
byte[] u_out_expected = Convert.hexStringToByteArray(u_out_str);
byte[] k_in = HexFormat.of().parseHex(k_in_str);
byte[] u_in = HexFormat.of().parseHex(u_in_str);
byte[] u_out_expected = HexFormat.of().parseHex(u_out_str);
NamedParameterSpec paramSpec = new NamedParameterSpec(opName);
XECParameters settings =

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -45,7 +45,6 @@ import sun.security.ec.*;
import java.io.*;
import java.security.spec.NamedParameterSpec;
import java.util.*;
import jdk.test.lib.Convert;
/*
* This test is derived from the iterative test in RFC 7748. To produce the
@ -95,7 +94,7 @@ public class XECIterative {
StringTokenizer tok = new StringTokenizer(line, ",");
long iter = Long.parseLong(tok.nextToken());
String kOrU = tok.nextToken();
byte[] value = Convert.hexStringToByteArray(tok.nextToken());
byte[] value = HexFormat.of().parseHex(tok.nextToken());
KU entry = testIters.get(iter);
if (entry == null) {
entry = new KU();
@ -117,13 +116,13 @@ public class XECIterative {
if (i % 1000 == 0 && (curEntry = testIters.get(i)) != null) {
if (!Arrays.equals(k, curEntry.k)) {
throw new RuntimeException("At iter " + i + ": expected k: "
+ Convert.byteArrayToHexString(curEntry.k)
+ ", computed k: " + Convert.byteArrayToHexString(k));
+ HexFormat.of().withUpperCase().formatHex(curEntry.k)
+ ", computed k: " + HexFormat.of().withUpperCase().formatHex(k));
}
if (!Arrays.equals(u, curEntry.u)) {
throw new RuntimeException("At iter " + i + ": expected u: "
+ Convert.byteArrayToHexString(curEntry.u)
+ ", computed u: " + Convert.byteArrayToHexString(u));
+ HexFormat.of().withUpperCase().formatHex(curEntry.u)
+ ", computed u: " + HexFormat.of().withUpperCase().formatHex(u));
}
System.out.println(opName + " checkpoint passed at " + i);
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -26,7 +26,6 @@
* @bug 8213363
* @summary Check for correct formatting of X25519/X448 private keys
* @library /test/lib
* @build jdk.test.lib.Convert
* @modules java.base/sun.security.util
* @run main XECKeyFormat
*/
@ -39,7 +38,7 @@ import java.nio.file.*;
import java.math.*;
import java.util.*;
import jdk.test.lib.Convert;
import java.util.HexFormat;
import sun.security.util.*;
@ -98,7 +97,7 @@ public class XECKeyFormat {
private static void pubKeyTest(Provider p, String key) throws Exception {
// ensure that a properly-formatted key can be read
byte[] encodedKey = Convert.hexStringToByteArray(key);
byte[] encodedKey = HexFormat.of().parseHex(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
KeyFactory kf = KeyFactory.getInstance("XDH", p);
kf.generatePublic(keySpec);
@ -125,7 +124,7 @@ public class XECKeyFormat {
checkPrivKeyFormat(keySpec.getEncoded());
// ensure that a properly-formatted key can be read
byte[] encodedKey = Convert.hexStringToByteArray(privKeys.get(algName));
byte[] encodedKey = HexFormat.of().parseHex(privKeys.get(algName));
keySpec = new PKCS8EncodedKeySpec(encodedKey);
kf.generatePrivate(keySpec);
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2009, 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
@ -40,6 +40,7 @@ import sun.security.krb5.internal.crypto.dk.AesDkCrypto;
import sun.security.krb5.internal.crypto.dk.Des3DkCrypto;
import sun.security.krb5.internal.crypto.dk.DkCrypto;
import java.nio.*;
import java.util.HexFormat;
import javax.crypto.*;
import javax.crypto.spec.*;
@ -216,29 +217,12 @@ public class RFC396xTest {
}
static String hex(byte[] bs) {
StringBuffer sb = new StringBuffer(bs.length * 2);
for(byte b: bs) {
char c = (char)((b+256)%256);
if (c / 16 < 10)
sb.append((char)(c/16+'0'));
else
sb.append((char)(c/16-10+'a'));
if (c % 16 < 10)
sb.append((char)(c%16+'0'));
else
sb.append((char)(c%16-10+'a'));
}
return new String(sb);
return HexFormat.of().formatHex(bs);
}
static byte[] xeh(String in) {
in = in.replaceAll(" ", "");
int len = in.length()/2;
byte[] out = new byte[len];
for (int i=0; i<len; i++) {
out[i] = (byte)Integer.parseInt(in.substring(i*2, i*2+2), 16);
}
return out;
return HexFormat.of().parseHex(in);
}
static void assertStringEquals(String a, String b) {

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 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
@ -408,22 +408,11 @@ public class ReplayCacheTestProc {
ps.printf("%s:\nmsg: %s\nMD5: %s\nSHA-256: %s\n\n",
label,
req.msg,
hex(md5.digest(data)),
hex(sha256.digest(data)));
HexFormat.of().withUpperCase().formatHex(md5.digest(data)),
HexFormat.of().withUpperCase().formatHex(sha256.digest(data)));
}
}
// Returns a compact hexdump for a byte array
private static String hex(byte[] hash) {
char[] h = new char[hash.length * 2];
char[] hexConst = "0123456789ABCDEF".toCharArray();
for (int i=0; i<hash.length; i++) {
h[2*i] = hexConst[(hash[i]&0xff)>>4];
h[2*i+1] = hexConst[hash[i]&0xf];
}
return new String(h);
}
// return size of dfl file, excluding the null hash ones
private static int csize(int p) throws Exception {
try (SeekableByteChannel chan = Files.newByteChannel(

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 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
@ -32,6 +32,7 @@
import javax.crypto.Cipher;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HexFormat;
import sun.security.krb5.internal.crypto.dk.AesSha2DkCrypto;
import jdk.test.lib.hexdump.HexPrinter;
@ -190,11 +191,7 @@ public class KerberosAesSha2 {
private static byte[] hex(String var) {
var = var.replaceAll("\\s", "");
byte[] data = new byte[var.length()/2];
for (int i=0; i<data.length; i++) {
data[i] = Integer.valueOf(var.substring(2*i,2*i+2), 16).byteValue();
}
return data;
return HexFormat.of().parseHex(var);
}
private static void check(byte[] b1, byte[] b2) throws Exception {

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 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
@ -44,6 +44,7 @@ import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.Map;
public class VerifyCACerts {
@ -60,6 +61,9 @@ public class VerifyCACerts {
private static final String CHECKSUM
= "50:97:53:06:1B:40:32:71:D6:CD:3B:29:89:7C:BF:BF:41:6F:56:B1:0D:E9:B8:2A:8C:7C:C2:CD:CD:9F:10:EF";
// Hex formatter to upper case with ":" delimiter
private static final HexFormat HEX = HexFormat.ofDelimiter(":").withUpperCase();
// map of cert alias to SHA-256 fingerprint
@SuppressWarnings("serial")
private static final Map<String, String> FINGERPRINT_MAP = new HashMap<>() {
@ -279,7 +283,7 @@ public class VerifyCACerts {
md = MessageDigest.getInstance("SHA-256");
byte[] data = Files.readAllBytes(Path.of(CACERTS));
String checksum = toHexString(md.digest(data));
String checksum = HEX.formatHex(md.digest(data));
if (!checksum.equals(CHECKSUM)) {
atLeastOneFailed = true;
System.err.println("ERROR: wrong checksum\n" + checksum);
@ -368,18 +372,7 @@ public class VerifyCACerts {
}
System.out.println("Checking fingerprint of " + alias);
byte[] digest = md.digest(cert.getEncoded());
return fingerprint.equals(toHexString(digest));
return fingerprint.equals(HEX.formatHex(digest));
}
private static String toHexString(byte[] block) {
StringBuilder buf = new StringBuilder();
int len = block.length;
for (int i = 0; i < len; i++) {
buf.append(String.format("%02X", block[i]));
if (i < len - 1) {
buf.append(":");
}
}
return buf.toString();
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 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
@ -37,8 +37,10 @@
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HexFormat;
import jdk.test.lib.Utils;
import jdk.test.lib.hexdump.ASN1Formatter;
import jdk.test.lib.hexdump.HexPrinter;
import org.testng.Assert;
import org.testng.annotations.Test;
import sun.security.pkcs.PKCS8Key;
@ -52,7 +54,7 @@ public class PKCS8Test {
"\tp: 02\n\tq: 03\n\tg: 04\n";
static final String ALGORITHM = "DSA";
static final byte[] EXPECTED = Utils.toByteArray(
static final byte[] EXPECTED = HexFormat.of().parseHex(
"301e" + // SEQUENCE
"020100" + // Version int 0
"3014" + // PrivateKeyAlgorithmIdentifier
@ -70,7 +72,9 @@ public class PKCS8Test {
BigInteger.valueOf(4)).getEncoded();
Assert.assertTrue(Arrays.equals(encodedKey, EXPECTED),
Utils.toHexString(encodedKey));
HexPrinter.simple()
.formatter(ASN1Formatter.formatter())
.toString(encodedKey));
PKCS8Key decodedKey = (PKCS8Key)PKCS8Key.parseKey(
new DerValue(encodedKey));
@ -82,7 +86,9 @@ public class PKCS8Test {
byte[] encodedOutput = decodedKey.getEncoded();
Assert.assertTrue(Arrays.equals(encodedOutput, EXPECTED),
Utils.toHexString(encodedOutput));
HexPrinter.simple()
.formatter(ASN1Formatter.formatter())
.toString(encodedOutput));
// Test additional fields
enlarge(0, "8000"); // attributes
@ -106,7 +112,7 @@ public class PKCS8Test {
byte[] original = EXPECTED.clone();
int length = original.length;
for (String field : fields) { // append fields
byte[] add = Utils.toByteArray(field);
byte[] add = HexFormat.of().parseHex(field);
original = Arrays.copyOf(original, length + add.length);
System.arraycopy(add, 0, original, length, add.length);
length += add.length;

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 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
@ -39,6 +39,7 @@ import java.security.Provider;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HexFormat;
import javax.crypto.KeyAgreement;
/**
@ -51,6 +52,9 @@ import javax.crypto.KeyAgreement;
public class TestLeadingZeroesP11 extends PKCS11Test {
// Hex formatter to upper case with ":" delimiter
private static final HexFormat HEX = HexFormat.ofDelimiter(":").withUpperCase();
public static void main(String[] args) throws Exception {
main(new TestLeadingZeroesP11(), args);
}
@ -74,7 +78,7 @@ public class TestLeadingZeroesP11 extends PKCS11Test {
aliceKeyAgree.init(alicePrivKey);
aliceKeyAgree.doPhase(bobPubKey, true);
byte[] sharedSecret = aliceKeyAgree.generateSecret();
System.out.println("shared secret:\n" + toHexString(sharedSecret));
System.out.println("shared secret:\n" + HEX.formatHex(sharedSecret));
// verify that leading zero is present
if (sharedSecret.length != 128) {
@ -90,7 +94,7 @@ public class TestLeadingZeroesP11 extends PKCS11Test {
byte[] tlsPremasterSecret =
aliceKeyAgree.generateSecret("TlsPremasterSecret").getEncoded();
System.out.println(
"tls premaster secret:\n" + toHexString(tlsPremasterSecret));
"tls premaster secret:\n" + HEX.formatHex(tlsPremasterSecret));
// check that leading zero has been stripped
if (tlsPremasterSecret.length != 127) {
@ -107,35 +111,6 @@ public class TestLeadingZeroesP11 extends PKCS11Test {
}
/*
* 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();
}
private static final byte alicePubKeyEnc[] = {
(byte)0x30, (byte)0x82, (byte)0x01, (byte)0x24,
(byte)0x30, (byte)0x81, (byte)0x99, (byte)0x06,

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
@ -71,17 +71,22 @@ public class TestDSA {
private final static BigInteger y = new BigInteger(ys, 16);
// data for test 1, original and SHA-1 hashed
private final static byte[] data1Raw = b("0102030405060708090a0b0c0d0e0f10111213");
private final static byte[] data1SHA = b("00:e2:5f:c9:1c:8f:d6:8c:6a:dc:c6:bd:f0:46:60:5e:a2:cd:8d:ad");
private final static byte[] data1Raw = HexFormat.of()
.parseHex("0102030405060708090a0b0c0d0e0f10111213");
private final static byte[] data1SHA = HexFormat.ofDelimiter(":")
.parseHex("00:e2:5f:c9:1c:8f:d6:8c:6a:dc:c6:bd:f0:46:60:5e:a2:cd:8d:ad");
// valid signatures of data1. sig1b uses incorrect ASN.1 encoding,
// which we want to accept anyway for compatibility
private final static byte[] sig1a = b("30:2d:02:14:53:06:3f:7d:ec:48:3c:99:17:9a:2c:a9:4d:e8:00:da:70:fb:35:d7:02:15:00:92:6a:39:6b:15:63:2f:e7:32:90:35:bf:af:47:55:e7:ff:33:a5:13");
private final static byte[] sig1b = b("30:2c:02:14:53:06:3f:7d:ec:48:3c:99:17:9a:2c:a9:4d:e8:00:da:70:fb:35:d7:02:14:92:6a:39:6b:15:63:2f:e7:32:90:35:bf:af:47:55:e7:ff:33:a5:13");
private final static byte[] sig1a = HexFormat.ofDelimiter(":")
.parseHex("30:2d:02:14:53:06:3f:7d:ec:48:3c:99:17:9a:2c:a9:4d:e8:00:da:70:fb:35:d7:02:15:00:92:6a:39:6b:15:63:2f:e7:32:90:35:bf:af:47:55:e7:ff:33:a5:13");
private final static byte[] sig1b = HexFormat.ofDelimiter(":")
.parseHex("30:2c:02:14:53:06:3f:7d:ec:48:3c:99:17:9a:2c:a9:4d:e8:00:da:70:fb:35:d7:02:14:92:6a:39:6b:15:63:2f:e7:32:90:35:bf:af:47:55:e7:ff:33:a5:13");
// data for test 2 (invalid signatures)
private final static byte[] data2Raw = {};
private final static byte[] data2SHA = b("da:39:a3:ee:5e:6b:4b:0d:32:55:bf:ef:95:60:18:90:af:d8:07:09");
private final static byte[] data2SHA = HexFormat.ofDelimiter(":")
.parseHex("da:39:a3:ee:5e:6b:4b:0d:32:55:bf:ef:95:60:18:90:af:d8:07:09");
private static void verify(Provider provider, String alg, PublicKey key, byte[] data, byte[] sig, boolean result) throws Exception {
Signature s = Signature.getInstance(alg, provider);
@ -182,62 +187,4 @@ public class TestDSA {
long stop = System.currentTimeMillis();
System.out.println("All tests passed (" + (stop - start) + " ms).");
}
private final static char[] hexDigits = "0123456789abcdef".toCharArray();
public static String toString(byte[] b) {
StringBuffer sb = new StringBuffer(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();
}
public static byte[] parse(String s) {
try {
int n = s.length();
ByteArrayOutputStream out = new ByteArrayOutputStream(n / 3);
StringReader r = new StringReader(s);
while (true) {
int b1 = nextNibble(r);
if (b1 < 0) {
break;
}
int b2 = nextNibble(r);
if (b2 < 0) {
throw new RuntimeException("Invalid string " + s);
}
int b = (b1 << 4) | b2;
out.write(b);
}
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static byte[] b(String s) {
return parse(s);
}
private static int nextNibble(StringReader r) throws IOException {
while (true) {
int ch = r.read();
if (ch == -1) {
return -1;
} else if ((ch >= '0') && (ch <= '9')) {
return ch - '0';
} else if ((ch >= 'a') && (ch <= 'f')) {
return ch - 'a' + 10;
} else if ((ch >= 'A') && (ch <= 'F')) {
return ch - 'A' + 10;
}
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
@ -36,62 +36,7 @@ import java.security.*;
public class DigestKAT {
private final static char[] hexDigits = "0123456789abcdef".toCharArray();
public static String toString(byte[] b) {
StringBuffer sb = new StringBuffer(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();
}
public static byte[] parse(String s) {
try {
int n = s.length();
ByteArrayOutputStream out = new ByteArrayOutputStream(n / 3);
StringReader r = new StringReader(s);
while (true) {
int b1 = nextNibble(r);
if (b1 < 0) {
break;
}
int b2 = nextNibble(r);
if (b2 < 0) {
throw new RuntimeException("Invalid string " + s);
}
int b = (b1 << 4) | b2;
out.write(b);
}
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static byte[] b(String s) {
return parse(s);
}
private static int nextNibble(StringReader r) throws IOException {
while (true) {
int ch = r.read();
if (ch == -1) {
return -1;
} else if ((ch >= '0') && (ch <= '9')) {
return ch - '0';
} else if ((ch >= 'a') && (ch <= 'f')) {
return ch - 'a' + 10;
} else if ((ch >= 'A') && (ch <= 'F')) {
return ch - 'A' + 10;
}
}
}
private static final HexFormat HEX = HexFormat.ofDelimiter(":");
static abstract class Test {
abstract void run(Provider p) throws Exception;
@ -118,10 +63,10 @@ public class DigestKAT {
if (Arrays.equals(digest, myDigest) == false) {
System.out.println("Digest test for " + alg + " failed:");
if (data.length < 256) {
System.out.println("data: " + DigestKAT.toString(data));
System.out.println("data: " + HEX.formatHex(data));
}
System.out.println("dig: " + DigestKAT.toString(digest));
System.out.println("out: " + DigestKAT.toString(myDigest));
System.out.println("dig: " + HEX.formatHex(digest));
System.out.println("out: " + HEX.formatHex(myDigest));
throw new Exception("Digest test for " + alg + " failed");
}
// System.out.println("Passed " + alg);
@ -137,7 +82,8 @@ public class DigestKAT {
}
private static Test t(String alg, byte[] data, String digest) {
return new DigestTest(alg, data, parse(digest));
HexFormat hex = (digest.indexOf(':') < 0) ? HexFormat.of() : HexFormat.ofDelimiter(":");
return new DigestTest(alg, data, hex.parseHex(digest));
}
private final static byte[] ALONG, BLONG;

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -30,36 +30,13 @@ import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
public final class SigRecord {
static final String TEST_SRC = System.getProperty("test.src", ".");
// utility method for converting byte array to hex string
static String toHexString(byte[] array) {
StringBuilder sb = new StringBuilder(array.length * 2);
for (byte b : array) {
// The single digits 0123456789abcdef get a leading 0
if ((b >= 0x00) && (b < 0x10)) {
sb.append('0');
}
sb.append(Integer.toHexString(b & 0xff));
}
return sb.toString();
}
// utility method for converting hex string to byte array
static byte[] toByteArray(String s) {
byte[] bytes = new byte[s.length() / 2];
for (int i = 0; i < bytes.length; i++) {
int index = i * 2;
int v = Integer.parseInt(s.substring(index, index + 2), 16);
bytes[i] = (byte) v;
}
return bytes;
}
public static final class SigVector {
// digest algorithm to use
final String mdAlg;
@ -115,9 +92,9 @@ public final class SigRecord {
throw new IllegalArgumentException("One or more test vectors must be specified");
}
BigInteger n = new BigInteger(1, toByteArray(mod));
BigInteger e = new BigInteger(1, toByteArray(pubExp));
BigInteger d = new BigInteger(1, toByteArray(privExp));
BigInteger n = new BigInteger(1, HexFormat.of().parseHex(mod));
BigInteger e = new BigInteger(1, HexFormat.of().parseHex(pubExp));
BigInteger d = new BigInteger(1, HexFormat.of().parseHex(privExp));
this.id = ("n=" + mod + ", e=" + pubExp);
this.pubKeySpec = new RSAPublicKeySpec(n, e);
this.privKeySpec = new RSAPrivateKeySpec(n, d);

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -30,6 +30,7 @@ import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
/*
@ -100,8 +101,8 @@ public class TestSigGen15 {
" due to no support");
continue;
}
byte[] msgBytes = SigRecord.toByteArray(v.msg);
byte[] expSigBytes = SigRecord.toByteArray(v.sig);
byte[] msgBytes = HexFormat.of().parseHex(v.msg);
byte[] expSigBytes = HexFormat.of().parseHex(v.sig);
sig.initSign(privKey);
sig.update(msgBytes);
@ -114,7 +115,7 @@ public class TestSigGen15 {
System.out.println("\tSHAALG = " + v.mdAlg);
System.out.println("\tMsg = " + v.msg);
System.out.println("\tExpected Sig = " + v.sig);
System.out.println("\tActual Sig = " + SigRecord.toHexString(actualSigBytes));
System.out.println("\tActual Sig = " + HexFormat.of().formatHex(actualSigBytes));
} else {
System.out.println("\t" + v.mdAlg + " Test Vector Passed");
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -30,36 +30,13 @@ import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
public final class SigRecord {
static final String TEST_SRC = System.getProperty("test.src", ".");
// utility method for converting byte array to hex string
static String toHexString(byte[] array) {
StringBuilder sb = new StringBuilder(array.length * 2);
for (byte b : array) {
// The single digits 0123456789abcdef get a leading 0
if ((b >= 0x00) && (b < 0x10)) {
sb.append('0');
}
sb.append(Integer.toHexString(b & 0xff));
}
return sb.toString();
}
// utility method for converting hex string to byte array
static byte[] toByteArray(String s) {
byte[] bytes = new byte[s.length() / 2];
for (int i = 0; i < bytes.length; i++) {
int index = i * 2;
int v = Integer.parseInt(s.substring(index, index + 2), 16);
bytes[i] = (byte) v;
}
return bytes;
}
public static final class SigVector {
// digest algorithm to use
final String mdAlg;
@ -120,9 +97,9 @@ public final class SigRecord {
throw new IllegalArgumentException("One or more test vectors must be specified");
}
BigInteger n = new BigInteger(1, toByteArray(mod));
BigInteger e = new BigInteger(1, toByteArray(pubExp));
BigInteger d = new BigInteger(1, toByteArray(privExp));
BigInteger n = new BigInteger(1, HexFormat.of().parseHex(mod));
BigInteger e = new BigInteger(1, HexFormat.of().parseHex(pubExp));
BigInteger d = new BigInteger(1, HexFormat.of().parseHex(privExp));
this.id = ("n=" + mod + ", e=" + pubExp);
this.pubKeySpec = new RSAPublicKeySpec(n, e);
this.privKeySpec = new RSAPrivateKeySpec(n, d);

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -21,15 +21,10 @@
* questions.
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
/*
@ -50,7 +45,7 @@ public class TestSigGenPSS {
int numBytes;
MyKnownRandomSrc(String srcString) {
this.srcBytes = SigRecord.toByteArray(srcString);
this.srcBytes = HexFormat.of().parseHex(srcString);
this.numBytes = this.srcBytes.length;
}
@Override
@ -120,8 +115,8 @@ public class TestSigGenPSS {
boolean success = true;
for (SigRecord.SigVector v : vectors) {
System.out.println("\tAgainst " + v.mdAlg);
byte[] msgBytes = SigRecord.toByteArray(v.msg);
byte[] expSigBytes = SigRecord.toByteArray(v.sig);
byte[] msgBytes = HexFormat.of().parseHex(v.msg);
byte[] expSigBytes = HexFormat.of().parseHex(v.sig);
MyKnownRandomSrc saltSrc = new MyKnownRandomSrc(v.salt);
sig.initSign(privKey, saltSrc);
@ -145,7 +140,7 @@ public class TestSigGenPSS {
System.out.println("\tMsg = " + v.msg);
System.out.println("\tSalt = " + v.salt);
System.out.println("\tExpected Sig = " + v.sig);
System.out.println("\tActual Sig = " + SigRecord.toHexString(actualSigBytes));
System.out.println("\tActual Sig = " + HexFormat.of().formatHex(actualSigBytes));
} else {
System.out.println("\t" + v.mdAlg + " Test Vector Passed");
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -195,23 +195,13 @@ public class TestIntegerModuloP {
byte[] baselineResult = func.apply(baseline, right.baseline);
if (!Arrays.equals(testResult, baselineResult)) {
throw new RuntimeException("Array values do not match: "
+ byteArrayToHexString(testResult) + " != "
+ byteArrayToHexString(baselineResult));
+ HexFormat.of().withUpperCase().formatHex(testResult) + " != "
+ HexFormat.of().withUpperCase().formatHex(baselineResult));
}
}
}
static String byteArrayToHexString(byte[] arr) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < arr.length; ++i) {
byte curVal = arr[i];
result.append(Character.forDigit(curVal >> 4 & 0xF, 16));
result.append(Character.forDigit(curVal & 0xF, 16));
}
return result.toString();
}
static TestPair<IntegerModuloP>
applyAndCheck(ElemFunction func, TestPair<MutableIntegerModuloP> left,
TestPair<IntegerModuloP> right) {

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 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
@ -23,15 +23,23 @@
/* @test
* @bug 4228833
* @library /test/lib
* @summary Make sure constructor that takes DerValue argument works
* @modules java.base/sun.security.util
* java.base/sun.security.x509
*/
import jdk.test.lib.hexdump.ASN1Formatter;
import jdk.test.lib.hexdump.HexPrinter;
import sun.security.util.*;
import sun.security.x509.*;
import java.util.HexFormat;
public class DerValueConstructor {
// Hex formatter to upper case with ":" delimiter
private static final HexFormat HEX = HexFormat.ofDelimiter(":").withUpperCase();
public static void main(String[] args) throws Exception {
String name = "CN=anne test";
@ -50,7 +58,10 @@ public class DerValueConstructor {
dn.encode(debugDER);
ba = debugDER.toByteArray();
System.err.print("DEBUG: encoded X500Name bytes: ");
System.out.println(toHexString(ba));
System.out.println(HEX.formatHex(ba));
System.out.println(HexPrinter.simple()
.formatter(ASN1Formatter.formatter())
.toString(ba));
System.err.println();
// decode
@ -76,7 +87,10 @@ public class DerValueConstructor {
gn.encode(debugDER);
ba = debugDER.toByteArray();
System.err.print("DEBUG: encoded GeneralName bytes: ");
System.out.println(toHexString(ba));
System.out.println(HEX.formatHex(ba));
System.out.println(HexPrinter.simple()
.formatter(ASN1Formatter.formatter())
.toString(ba));
System.err.println();
// decode
@ -96,39 +110,13 @@ public class DerValueConstructor {
subTree.encode(debugDER);
ba = debugDER.toByteArray();
System.err.print("DEBUG: encoded GeneralSubtree bytes: ");
System.out.println(toHexString(ba));
System.out.println(HEX.formatHex(ba));
System.out.println(HexPrinter.simple()
.formatter(ASN1Formatter.formatter())
.toString(ba));
System.err.println();
// decode
GeneralSubtree debugSubtree = new GeneralSubtree(new DerValue(ba));
}
/*
* Converts a byte to hex digit and writes to the supplied buffer
*/
private static 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 static 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();
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 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
@ -24,6 +24,7 @@
package jdk.test.lib;
import java.math.BigInteger;
import java.util.HexFormat;
import java.security.spec.EdECPoint;
/**
@ -33,17 +34,6 @@ import java.security.spec.EdECPoint;
public class Convert {
// Convert from a byte array to a hexadecimal representation as a string.
public static String byteArrayToHexString(byte[] arr) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < arr.length; ++i) {
byte curVal = arr[i];
result.append(Character.forDigit(curVal >> 4 & 0xF, 16));
result.append(Character.forDigit(curVal & 0xF, 16));
}
return result.toString();
}
// Expand a single byte to a byte array
public static byte[] byteToByteArray(byte v, int length) {
byte[] result = new byte[length];
@ -51,17 +41,6 @@ public class Convert {
return result;
}
// Convert a hexadecimal string to a byte array
public static byte[] hexStringToByteArray(String str) {
byte[] result = new byte[str.length() / 2];
for (int i = 0; i < result.length; i++) {
result[i] = (byte) Character.digit(str.charAt(2 * i), 16);
result[i] <<= 4;
result[i] += Character.digit(str.charAt(2 * i + 1), 16);
}
return result;
}
/*
* Convert a hexadecimal string to the corresponding little-ending number
* as a BigInteger. The clearHighBit argument determines whether the most
@ -92,7 +71,7 @@ public class Convert {
}
public static EdECPoint hexStringToEdPoint(String str) {
return byteArrayToEdPoint(hexStringToByteArray(str));
return byteArrayToEdPoint(HexFormat.of().parseHex(str));
}
private static void swap(byte[] arr, int i, int j) {

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 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
@ -46,6 +46,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HexFormat;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
@ -462,24 +463,17 @@ public final class Utils {
return new String(Files.readAllBytes(filePath));
}
private static final char[] hexArray = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* Returns hex view of byte array
*
* @param bytes byte array to process
* @return space separated hexadecimal string representation of bytes
* @deprecated replaced by {@link java.util.HexFormat#ofDelimiter(String)
* HexFormat.ofDelimiter(" ").format (byte[], char)}.
*/
@Deprecated
public static String toHexString(byte[] bytes) {
char[] hexView = new char[bytes.length * 3 - 1];
for (int i = 0; i < bytes.length - 1; i++) {
hexView[i * 3] = hexArray[(bytes[i] >> 4) & 0x0F];
hexView[i * 3 + 1] = hexArray[bytes[i] & 0x0F];
hexView[i * 3 + 2] = ' ';
}
hexView[hexView.length - 2] = hexArray[(bytes[bytes.length - 1] >> 4) & 0x0F];
hexView[hexView.length - 1] = hexArray[bytes[bytes.length - 1] & 0x0F];
return new String(hexView);
return HexFormat.ofDelimiter(" ").withUpperCase().formatHex(bytes);
}
/**
@ -489,13 +483,7 @@ public final class Utils {
* @return byte array
*/
public static byte[] toByteArray(String hex) {
int length = hex.length();
byte[] bytes = new byte[length / 2];
for (int i = 0; i < length; i += 2) {
bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
return bytes;
return HexFormat.of().parseHex(hex);
}
/**