Path: blob/master/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyKAT.java
41152 views
/*1* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 825541026* @library /test/lib ..27* @modules jdk.crypto.cryptoki28* @build jdk.test.lib.Convert29* @run main/othervm TestChaChaPolyKAT30* @summary ChaCha20-Poly1305 Cipher Implementation (KAT)31*/3233import java.util.*;34import java.security.GeneralSecurityException;35import java.security.Provider;36import java.security.NoSuchAlgorithmException;37import javax.crypto.Cipher;38import javax.crypto.spec.ChaCha20ParameterSpec;39import javax.crypto.spec.IvParameterSpec;40import javax.crypto.spec.SecretKeySpec;41import javax.crypto.AEADBadTagException;42import java.nio.ByteBuffer;43import jdk.test.lib.Convert;4445public class TestChaChaPolyKAT extends PKCS11Test {46public static class TestData {47public TestData(String name, String keyStr, String nonceStr, int ctr,48int dir, String inputStr, String aadStr, String outStr) {49testName = Objects.requireNonNull(name);50HexFormat hex = HexFormat.of();51key = hex.parseHex(Objects.requireNonNull(keyStr));52nonce = hex.parseHex(Objects.requireNonNull(nonceStr));53if ((counter = ctr) < 0) {54throw new IllegalArgumentException(55"counter must be 0 or greater");56}57direction = dir;58if ((direction != Cipher.ENCRYPT_MODE) &&59(direction != Cipher.DECRYPT_MODE)) {60throw new IllegalArgumentException(61"Direction must be ENCRYPT_MODE or DECRYPT_MODE");62}63input = hex.parseHex(Objects.requireNonNull(inputStr));64aad = (aadStr != null) ? hex.parseHex(aadStr) : null;65expOutput = hex.parseHex(Objects.requireNonNull(outStr));66}6768public final String testName;69public final byte[] key;70public final byte[] nonce;71public final int counter;72public final int direction;73public final byte[] input;74public final byte[] aad;75public final byte[] expOutput;76}7778private static final String ALGO = "ChaCha20-Poly1305";7980public static final List<TestData> aeadTestList =81new LinkedList<TestData>() {{82add(new TestData("RFC 7539 Sample AEAD Test Vector",83"808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",84"070000004041424344454647",851, Cipher.ENCRYPT_MODE,86"4c616469657320616e642047656e746c656d656e206f662074686520636c6173" +87"73206f66202739393a204966204920636f756c64206f6666657220796f75206f" +88"6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73" +89"637265656e20776f756c642062652069742e",90"50515253c0c1c2c3c4c5c6c7",91"d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6" +92"3dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b36" +93"92ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc" +94"3ff4def08e4b7a9de576d26586cec64b61161ae10b594f09e26a7e902ecbd060" +95"0691"));96add(new TestData("RFC 7539 A.5 Sample Decryption",97"1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0",98"000000000102030405060708",991, Cipher.DECRYPT_MODE,100"64a0861575861af460f062c79be643bd5e805cfd345cf389f108670ac76c8cb2" +101"4c6cfc18755d43eea09ee94e382d26b0bdb7b73c321b0100d4f03b7f355894cf" +102"332f830e710b97ce98c8a84abd0b948114ad176e008d33bd60f982b1ff37c855" +103"9797a06ef4f0ef61c186324e2b3506383606907b6a7c02b0f9f6157b53c867e4" +104"b9166c767b804d46a59b5216cde7a4e99040c5a40433225ee282a1b0a06c523e" +105"af4534d7f83fa1155b0047718cbc546a0d072b04b3564eea1b422273f548271a" +106"0bb2316053fa76991955ebd63159434ecebb4e466dae5a1073a6727627097a10" +107"49e617d91d361094fa68f0ff77987130305beaba2eda04df997b714d6c6f2c29" +108"a6ad5cb4022b02709beead9d67890cbb22392336fea1851f38",109"f33388860000000000004e91",110"496e7465726e65742d4472616674732061726520647261667420646f63756d65" +111"6e74732076616c696420666f722061206d6178696d756d206f6620736978206d" +112"6f6e74687320616e64206d617920626520757064617465642c207265706c6163" +113"65642c206f72206f62736f6c65746564206279206f7468657220646f63756d65" +114"6e747320617420616e792074696d652e20497420697320696e617070726f7072" +115"6961746520746f2075736520496e7465726e65742d4472616674732061732072" +116"65666572656e6365206d6174657269616c206f7220746f206369746520746865" +117"6d206f74686572207468616e206173202fe2809c776f726b20696e2070726f67" +118"726573732e2fe2809d"));119}};120121@Override122public void main(Provider p) throws Exception {123System.out.println("Testing " + p.getName());124125try {126Cipher.getInstance(ALGO, p);127} catch (NoSuchAlgorithmException nsae) {128System.out.println("Skip; no support for " + ALGO);129return;130}131132int testsPassed = 0;133int testNumber = 0;134135System.out.println("----- AEAD Tests -----");136for (TestData test : aeadTestList) {137System.out.println("*** Test " + ++testNumber + ": " +138test.testName);139if (runAEADTest(p, test)) {140testsPassed++;141}142}143System.out.println();144145System.out.println("Total tests: " + testNumber +146", Passed: " + testsPassed + ", Failed: " +147(testNumber - testsPassed));148if (testsPassed != testNumber) {149throw new RuntimeException("One or more tests failed. " +150"Check output for details");151}152}153154private static boolean runAEADTest(Provider p, TestData testData)155throws GeneralSecurityException {156boolean result = false;157158Cipher mambo = Cipher.getInstance(ALGO, p);159SecretKeySpec mamboKey = new SecretKeySpec(testData.key, "ChaCha20");160IvParameterSpec mamboSpec = new IvParameterSpec(testData.nonce);161162mambo.init(testData.direction, mamboKey, mamboSpec);163164byte[] out = new byte[mambo.getOutputSize(testData.input.length)];165int outOff = 0;166try {167mambo.updateAAD(testData.aad);168outOff += mambo.update(testData.input, 0, testData.input.length,169out, outOff);170outOff += mambo.doFinal(out, outOff);171} catch (AEADBadTagException abte) {172// If we get a bad tag or derive a tag mismatch, log it173// and register it as a failure174System.out.println("FAIL: " + abte);175return false;176}177178if (!Arrays.equals(out, 0, outOff, testData.expOutput, 0, outOff)) {179System.out.println("ERROR - Output Mismatch!");180System.out.println("Expected:\n" +181dumpHexBytes(testData.expOutput, 16, "\n", " "));182System.out.println("Actual:\n" +183dumpHexBytes(out, 16, "\n", " "));184System.out.println();185} else {186result = true;187}188189return result;190}191192/**193* Dump the hex bytes of a buffer into string form.194*195* @param data The array of bytes to dump to stdout.196* @param itemsPerLine The number of bytes to display per line197* if the {@code lineDelim} character is blank then all bytes198* will be printed on a single line.199* @param lineDelim The delimiter between lines200* @param itemDelim The delimiter between bytes201*202* @return The hexdump of the byte array203*/204private static String dumpHexBytes(byte[] data, int itemsPerLine,205String lineDelim, String itemDelim) {206return dumpHexBytes(ByteBuffer.wrap(data), itemsPerLine, lineDelim,207itemDelim);208}209210private static String dumpHexBytes(ByteBuffer data, int itemsPerLine,211String lineDelim, String itemDelim) {212StringBuilder sb = new StringBuilder();213if (data != null) {214data.mark();215int i = 0;216while (data.remaining() > 0) {217if (i % itemsPerLine == 0 && i != 0) {218sb.append(lineDelim);219}220sb.append(String.format("%02X", data.get())).append(itemDelim);221i++;222}223data.reset();224}225226return sb.toString();227}228229public static void main(String[] args) throws Exception {230main(new TestChaChaPolyKAT(), args);231}232}233234235