Path: blob/master/test/jdk/com/sun/crypto/provider/Cipher/ChaCha20/ChaCha20KAT.java
41161 views
/*1* Copyright (c) 2018, 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 815302926* @library /test/lib27* @build jdk.test.lib.Convert28* @run main ChaCha20KAT29* @summary ChaCha20 Cipher Implementation (KAT)30*/3132import java.util.*;33import java.security.GeneralSecurityException;34import javax.crypto.Cipher;35import javax.crypto.spec.ChaCha20ParameterSpec;36import javax.crypto.spec.IvParameterSpec;37import javax.crypto.spec.SecretKeySpec;38import javax.crypto.AEADBadTagException;39import java.nio.ByteBuffer;40import jdk.test.lib.Convert;4142public class ChaCha20KAT {43public static class TestData {44public TestData(String name, String keyStr, String nonceStr, int ctr,45int dir, String inputStr, String aadStr, String outStr) {46testName = Objects.requireNonNull(name);47HexFormat hex = HexFormat.of();48key = hex.parseHex(Objects.requireNonNull(keyStr));49nonce = hex.parseHex(Objects.requireNonNull(nonceStr));50if ((counter = ctr) < 0) {51throw new IllegalArgumentException(52"counter must be 0 or greater");53}54direction = dir;55if ((direction != Cipher.ENCRYPT_MODE) &&56(direction != Cipher.DECRYPT_MODE)) {57throw new IllegalArgumentException(58"Direction must be ENCRYPT_MODE or DECRYPT_MODE");59}60input = hex.parseHex(Objects.requireNonNull(inputStr));61aad = (aadStr != null) ? hex.parseHex(aadStr) : null;62expOutput = hex.parseHex(Objects.requireNonNull(outStr));63}6465public final String testName;66public final byte[] key;67public final byte[] nonce;68public final int counter;69public final int direction;70public final byte[] input;71public final byte[] aad;72public final byte[] expOutput;73}7475public static final List<TestData> testList = new LinkedList<TestData>() {{76add(new TestData("RFC 7539 Sample Test Vector",77"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",78"000000000000004a00000000",791, Cipher.ENCRYPT_MODE,80"4c616469657320616e642047656e746c656d656e206f662074686520636c6173" +81"73206f66202739393a204966204920636f756c64206f6666657220796f75206f" +82"6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73" +83"637265656e20776f756c642062652069742e",84null,85"6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0b" +86"f91b65c5524733ab8f593dabcd62b3571639d624e65152ab8f530c359f0861d8" +87"07ca0dbf500d6a6156a38e088a22b65e52bc514d16ccf806818ce91ab7793736" +88"5af90bbf74a35be6b40b8eedf2785e42874d"));89add(new TestData("RFC 7539 Test Vector 1 (all zeroes)",90"0000000000000000000000000000000000000000000000000000000000000000",91"000000000000000000000000",920, Cipher.ENCRYPT_MODE,93"0000000000000000000000000000000000000000000000000000000000000000" +94"0000000000000000000000000000000000000000000000000000000000000000",95null,96"76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7" +97"da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"));98add(new TestData("RFC 7539 Test Vector 2",99"0000000000000000000000000000000000000000000000000000000000000001",100"000000000000000000000002",1011, Cipher.ENCRYPT_MODE,102"416e79207375626d697373696f6e20746f20746865204945544620696e74656e" +103"6465642062792074686520436f6e7472696275746f7220666f72207075626c69" +104"636174696f6e20617320616c6c206f722070617274206f6620616e2049455446" +105"20496e7465726e65742d4472616674206f722052464320616e6420616e792073" +106"746174656d656e74206d6164652077697468696e2074686520636f6e74657874" +107"206f6620616e204945544620616374697669747920697320636f6e7369646572" +108"656420616e20224945544620436f6e747269627574696f6e222e205375636820" +109"73746174656d656e747320696e636c756465206f72616c2073746174656d656e" +110"747320696e20494554462073657373696f6e732c2061732077656c6c20617320" +111"7772697474656e20616e6420656c656374726f6e696320636f6d6d756e696361" +112"74696f6e73206d61646520617420616e792074696d65206f7220706c6163652c" +113"207768696368206172652061646472657373656420746f",114null,115"a3fbf07df3fa2fde4f376ca23e82737041605d9f4f4f57bd8cff2c1d4b7955ec" +116"2a97948bd3722915c8f3d337f7d370050e9e96d647b7c39f56e031ca5eb6250d" +117"4042e02785ececfa4b4bb5e8ead0440e20b6e8db09d881a7c6132f420e527950" +118"42bdfa7773d8a9051447b3291ce1411c680465552aa6c405b7764d5e87bea85a" +119"d00f8449ed8f72d0d662ab052691ca66424bc86d2df80ea41f43abf937d3259d" +120"c4b2d0dfb48a6c9139ddd7f76966e928e635553ba76c5c879d7b35d49eb2e62b" +121"0871cdac638939e25e8a1e0ef9d5280fa8ca328b351c3c765989cbcf3daa8b6c" +122"cc3aaf9f3979c92b3720fc88dc95ed84a1be059c6499b9fda236e7e818b04b0b" +123"c39c1e876b193bfe5569753f88128cc08aaa9b63d1a16f80ef2554d7189c411f" +124"5869ca52c5b83fa36ff216b9c1d30062bebcfd2dc5bce0911934fda79a86f6e6" +125"98ced759c3ff9b6477338f3da4f9cd8514ea9982ccafb341b2384dd902f3d1ab" +126"7ac61dd29c6f21ba5b862f3730e37cfdc4fd806c22f221"));127add(new TestData("RFC 7539 Test Vector 3",128"1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0",129"000000000000000000000002",13042, Cipher.ENCRYPT_MODE,131"2754776173206272696c6c69672c20616e642074686520736c6974687920746f" +132"7665730a446964206779726520616e642067696d626c6520696e207468652077" +133"6162653a0a416c6c206d696d737920776572652074686520626f726f676f7665" +134"732c0a416e6420746865206d6f6d65207261746873206f757467726162652e",135null,136"62e6347f95ed87a45ffae7426f27a1df5fb69110044c0d73118effa95b01e5cf" +137"166d3df2d721caf9b21e5fb14c616871fd84c54f9d65b283196c7fe4f60553eb" +138"f39c6402c42234e32a356b3e764312a61a5532055716ead6962568f87d3f3f77" +139"04c6a8d1bcd1bf4d50d6154b6da731b187b58dfd728afa36757a797ac188d1"));140}};141142public static final List<TestData> aeadTestList =143new LinkedList<TestData>() {{144add(new TestData("RFC 7539 Sample AEAD Test Vector",145"808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",146"070000004041424344454647",1471, Cipher.ENCRYPT_MODE,148"4c616469657320616e642047656e746c656d656e206f662074686520636c6173" +149"73206f66202739393a204966204920636f756c64206f6666657220796f75206f" +150"6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73" +151"637265656e20776f756c642062652069742e",152"50515253c0c1c2c3c4c5c6c7",153"d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6" +154"3dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b36" +155"92ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc" +156"3ff4def08e4b7a9de576d26586cec64b61161ae10b594f09e26a7e902ecbd060" +157"0691"));158add(new TestData("RFC 7539 A.5 Sample Decryption",159"1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0",160"000000000102030405060708",1611, Cipher.DECRYPT_MODE,162"64a0861575861af460f062c79be643bd5e805cfd345cf389f108670ac76c8cb2" +163"4c6cfc18755d43eea09ee94e382d26b0bdb7b73c321b0100d4f03b7f355894cf" +164"332f830e710b97ce98c8a84abd0b948114ad176e008d33bd60f982b1ff37c855" +165"9797a06ef4f0ef61c186324e2b3506383606907b6a7c02b0f9f6157b53c867e4" +166"b9166c767b804d46a59b5216cde7a4e99040c5a40433225ee282a1b0a06c523e" +167"af4534d7f83fa1155b0047718cbc546a0d072b04b3564eea1b422273f548271a" +168"0bb2316053fa76991955ebd63159434ecebb4e466dae5a1073a6727627097a10" +169"49e617d91d361094fa68f0ff77987130305beaba2eda04df997b714d6c6f2c29" +170"a6ad5cb4022b02709beead9d67890cbb22392336fea1851f38",171"f33388860000000000004e91",172"496e7465726e65742d4472616674732061726520647261667420646f63756d65" +173"6e74732076616c696420666f722061206d6178696d756d206f6620736978206d" +174"6f6e74687320616e64206d617920626520757064617465642c207265706c6163" +175"65642c206f72206f62736f6c65746564206279206f7468657220646f63756d65" +176"6e747320617420616e792074696d652e20497420697320696e617070726f7072" +177"6961746520746f2075736520496e7465726e65742d4472616674732061732072" +178"65666572656e6365206d6174657269616c206f7220746f206369746520746865" +179"6d206f74686572207468616e206173202fe2809c776f726b20696e2070726f67" +180"726573732e2fe2809d"));181}};182183184public static void main(String args[]) throws Exception {185int testsPassed = 0;186int testNumber = 0;187188System.out.println("----- Single-part (byte[]) Tests -----");189for (TestData test : testList) {190System.out.println("*** Test " + ++testNumber + ": " +191test.testName);192if (runSinglePartTest(test)) {193testsPassed++;194}195}196System.out.println();197198System.out.println("----- Single-part (ByteBuffer) Tests -----");199for (TestData test : testList) {200System.out.println("*** Test " + ++testNumber + ": " +201test.testName);202if (runByteBuffer(test)) {203testsPassed++;204}205}206System.out.println();207208System.out.println("----- Multi-part Tests -----");209for (TestData test : testList) {210System.out.println("*** Test " + ++testNumber + ": " +211test.testName);212if (runMultiPartTest(test)) {213testsPassed++;214}215}216System.out.println();217218System.out.println("----- AEAD Tests -----");219for (TestData test : aeadTestList) {220System.out.println("*** Test " + ++testNumber + ": " +221test.testName);222if (runAEADTest(test)) {223testsPassed++;224}225}226System.out.println();227228System.out.println("Total tests: " + testNumber +229", Passed: " + testsPassed + ", Failed: " +230(testNumber - testsPassed));231if (testsPassed != testNumber) {232throw new RuntimeException("One or more tests failed. " +233"Check output for details");234}235}236237private static boolean runSinglePartTest(TestData testData)238throws GeneralSecurityException {239boolean encRes = false;240boolean decRes = false;241byte[] encryptedResult;242byte[] decryptedResult;243244// Get a Cipher instance and set up the parameters245Cipher mambo = Cipher.getInstance("ChaCha20");246SecretKeySpec mamboKey = new SecretKeySpec(testData.key, "ChaCha20");247ChaCha20ParameterSpec mamboSpec = new ChaCha20ParameterSpec(248testData.nonce, testData.counter);249250// Encrypt our input251mambo.init(Cipher.ENCRYPT_MODE, mamboKey, mamboSpec);252encryptedResult = mambo.doFinal(testData.input);253254if (!Arrays.equals(encryptedResult, testData.expOutput)) {255System.out.println("ERROR - Output Mismatch!");256System.out.println("Expected:\n" +257dumpHexBytes(testData.expOutput, 16, "\n", " "));258System.out.println("Actual:\n" +259dumpHexBytes(encryptedResult, 16, "\n", " "));260System.out.println();261} else {262encRes = true;263}264265// Decrypt the result of the encryption operation266mambo = Cipher.getInstance("ChaCha20");267mambo.init(Cipher.DECRYPT_MODE, mamboKey, mamboSpec);268decryptedResult = mambo.doFinal(encryptedResult);269270if (!Arrays.equals(decryptedResult, testData.input)) {271System.out.println("ERROR - Output Mismatch!");272System.out.println("Expected:\n" +273dumpHexBytes(testData.input, 16, "\n", " "));274System.out.println("Actual:\n" +275dumpHexBytes(decryptedResult, 16, "\n", " "));276System.out.println();277} else {278decRes = true;279}280281return (encRes && decRes);282}283284private static boolean runMultiPartTest(TestData testData)285throws GeneralSecurityException {286boolean encRes = false;287boolean decRes = false;288289// Get a cipher instance and initialize it290Cipher mambo = Cipher.getInstance("ChaCha20");291SecretKeySpec mamboKey = new SecretKeySpec(testData.key, "ChaCha20");292ChaCha20ParameterSpec mamboSpec = new ChaCha20ParameterSpec(293testData.nonce, testData.counter);294295byte[] encryptedResult = new byte[testData.input.length];296mambo.init(Cipher.ENCRYPT_MODE, mamboKey, mamboSpec);297System.out.print("Encrypt - ");298doMulti(mambo, testData.input, encryptedResult);299300if (!Arrays.equals(encryptedResult, testData.expOutput)) {301System.out.println("ERROR - Output Mismatch!");302System.out.println("Expected:\n" +303dumpHexBytes(testData.expOutput, 16, "\n", " "));304System.out.println("Actual:\n" +305dumpHexBytes(encryptedResult, 16, "\n", " "));306System.out.println();307} else {308encRes = true;309}310311// Decrypt the result of the encryption operation312mambo = Cipher.getInstance("ChaCha20");313byte[] decryptedResult = new byte[encryptedResult.length];314mambo.init(Cipher.DECRYPT_MODE, mamboKey, mamboSpec);315System.out.print("Decrypt - ");316doMulti(mambo, encryptedResult, decryptedResult);317318if (!Arrays.equals(decryptedResult, testData.input)) {319System.out.println("ERROR - Output Mismatch!");320System.out.println("Expected:\n" +321dumpHexBytes(testData.input, 16, "\n", " "));322System.out.println("Actual:\n" +323dumpHexBytes(decryptedResult, 16, "\n", " "));324System.out.println();325} else {326decRes = true;327}328329return (encRes && decRes);330}331332private static void doMulti(Cipher c, byte[] input, byte[] output)333throws GeneralSecurityException {334int offset = 0;335boolean done = false;336Random randIn = new Random(System.currentTimeMillis());337338// Send small updates between 1 - 8 bytes in length until we get339// 8 or less bytes from the end of the input, then finalize.340System.out.println("Input length: " + input.length);341System.out.print("Multipart (bytes in/out): ");342while (!done) {343int mPartLen = randIn.nextInt(8) + 1;344int bytesLeft = input.length - offset;345int processed;346if (mPartLen < bytesLeft) {347System.out.print(mPartLen + "/");348processed = c.update(input, offset, mPartLen,349output, offset);350offset += processed;351System.out.print(processed + " ");352} else {353processed = c.doFinal(input, offset, bytesLeft,354output, offset);355System.out.print(bytesLeft + "/" + processed + " ");356done = true;357}358}359System.out.println();360}361362private static boolean runByteBuffer(TestData testData)363throws GeneralSecurityException {364boolean encRes = false;365boolean decRes = false;366367// Get a cipher instance and initialize it368Cipher mambo = Cipher.getInstance("ChaCha20");369SecretKeySpec mamboKey = new SecretKeySpec(testData.key, "ChaCha20");370ChaCha20ParameterSpec mamboSpec = new ChaCha20ParameterSpec(371testData.nonce, testData.counter);372mambo.init(Cipher.ENCRYPT_MODE, mamboKey, mamboSpec);373374ByteBuffer bbIn = ByteBuffer.wrap(testData.input);375ByteBuffer bbEncOut = ByteBuffer.allocate(376mambo.getOutputSize(testData.input.length));377ByteBuffer bbExpOut = ByteBuffer.wrap(testData.expOutput);378379mambo.doFinal(bbIn, bbEncOut);380bbIn.rewind();381bbEncOut.rewind();382383if (bbEncOut.compareTo(bbExpOut) != 0) {384System.out.println("ERROR - Output Mismatch!");385System.out.println("Expected:\n" +386dumpHexBytes(bbExpOut, 16, "\n", " "));387System.out.println("Actual:\n" +388dumpHexBytes(bbEncOut, 16, "\n", " "));389System.out.println();390} else {391encRes = true;392}393394// Decrypt the result of the encryption operation395mambo = Cipher.getInstance("ChaCha20");396mambo.init(Cipher.DECRYPT_MODE, mamboKey, mamboSpec);397System.out.print("Decrypt - ");398ByteBuffer bbDecOut = ByteBuffer.allocate(399mambo.getOutputSize(bbEncOut.remaining()));400401mambo.doFinal(bbEncOut, bbDecOut);402bbEncOut.rewind();403bbDecOut.rewind();404405if (bbDecOut.compareTo(bbIn) != 0) {406System.out.println("ERROR - Output Mismatch!");407System.out.println("Expected:\n" +408dumpHexBytes(bbIn, 16, "\n", " "));409System.out.println("Actual:\n" +410dumpHexBytes(bbDecOut, 16, "\n", " "));411System.out.println();412} else {413decRes = true;414}415416return (encRes && decRes);417}418419private static boolean runAEADTest(TestData testData)420throws GeneralSecurityException {421boolean result = false;422423Cipher mambo = Cipher.getInstance("ChaCha20-Poly1305");424SecretKeySpec mamboKey = new SecretKeySpec(testData.key, "ChaCha20");425IvParameterSpec mamboSpec = new IvParameterSpec(testData.nonce);426427mambo.init(testData.direction, mamboKey, mamboSpec);428429byte[] out = new byte[mambo.getOutputSize(testData.input.length)];430int outOff = 0;431try {432mambo.updateAAD(testData.aad);433outOff += mambo.update(testData.input, 0, testData.input.length,434out, outOff);435outOff += mambo.doFinal(out, outOff);436} catch (AEADBadTagException abte) {437// If we get a bad tag or derive a tag mismatch, log it438// and register it as a failure439System.out.println("FAIL: " + abte);440return false;441}442443if (!Arrays.equals(out, testData.expOutput)) {444System.out.println("ERROR - Output Mismatch!");445System.out.println("Expected:\n" +446dumpHexBytes(testData.expOutput, 16, "\n", " "));447System.out.println("Actual:\n" +448dumpHexBytes(out, 16, "\n", " "));449System.out.println();450} else {451result = true;452}453454return result;455}456457/**458* Dump the hex bytes of a buffer into string form.459*460* @param data The array of bytes to dump to stdout.461* @param itemsPerLine The number of bytes to display per line462* if the {@code lineDelim} character is blank then all bytes463* will be printed on a single line.464* @param lineDelim The delimiter between lines465* @param itemDelim The delimiter between bytes466*467* @return The hexdump of the byte array468*/469private static String dumpHexBytes(byte[] data, int itemsPerLine,470String lineDelim, String itemDelim) {471return dumpHexBytes(ByteBuffer.wrap(data), itemsPerLine, lineDelim,472itemDelim);473}474475private static String dumpHexBytes(ByteBuffer data, int itemsPerLine,476String lineDelim, String itemDelim) {477StringBuilder sb = new StringBuilder();478if (data != null) {479data.mark();480int i = 0;481while (data.remaining() > 0) {482if (i % itemsPerLine == 0 && i != 0) {483sb.append(lineDelim);484}485sb.append(String.format("%02X", data.get())).append(itemDelim);486i++;487}488data.reset();489}490491return sb.toString();492}493}494495496497