1 /*
   2  * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /**
  25  * @test
  26  * @bug 8153029
  27  * @summary ChaCha20 Cipher Implementation (KAT)
  28  */
  29 
  30 import java.util.*;
  31 import java.security.GeneralSecurityException;
  32 import javax.crypto.Cipher;
  33 import javax.crypto.spec.ChaCha20ParameterSpec;
  34 import javax.crypto.spec.IvParameterSpec;
  35 import javax.crypto.spec.SecretKeySpec;
  36 import javax.crypto.AEADBadTagException;
  37 import java.nio.ByteBuffer;
  38 
  39 public class ChaCha20KAT {
  40     public static class TestData {
  41         public TestData(String name, String keyStr, String nonceStr, int ctr,
  42                 int dir, String inputStr, String aadStr, String outStr) {
  43             testName = Objects.requireNonNull(name);
  44             key = hex2bin(Objects.requireNonNull(keyStr));
  45             nonce = hex2bin(Objects.requireNonNull(nonceStr));
  46             if ((counter = ctr) < 0) {
  47                 throw new IllegalArgumentException(
  48                         "counter must be 0 or greater");
  49             }
  50             direction = dir;
  51             if ((direction != Cipher.ENCRYPT_MODE) &&
  52                     (direction != Cipher.DECRYPT_MODE)) {
  53                 throw new IllegalArgumentException(
  54                         "Direction must be ENCRYPT_MODE or DECRYPT_MODE");
  55             }
  56             input = hex2bin(Objects.requireNonNull(inputStr));
  57             aad = (aadStr != null) ? hex2bin(aadStr) : null;
  58             expOutput = hex2bin(Objects.requireNonNull(outStr));
  59         }
  60 
  61         public final String testName;
  62         public final byte[] key;
  63         public final byte[] nonce;
  64         public final int counter;
  65         public final int direction;
  66         public final byte[] input;
  67         public final byte[] aad;
  68         public final byte[] expOutput;
  69     }
  70 
  71     public static final List<TestData> testList = new LinkedList<TestData>() {{
  72         add(new TestData("RFC 7539 Sample Test Vector",
  73             "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
  74             "000000000000004a00000000",
  75             1, Cipher.ENCRYPT_MODE,
  76             "4c616469657320616e642047656e746c656d656e206f662074686520636c6173" +
  77             "73206f66202739393a204966204920636f756c64206f6666657220796f75206f" +
  78             "6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73" +
  79             "637265656e20776f756c642062652069742e",
  80             null,
  81             "6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0b" +
  82             "f91b65c5524733ab8f593dabcd62b3571639d624e65152ab8f530c359f0861d8" +
  83             "07ca0dbf500d6a6156a38e088a22b65e52bc514d16ccf806818ce91ab7793736" +
  84             "5af90bbf74a35be6b40b8eedf2785e42874d"));
  85         add(new TestData("RFC 7539 Test Vector 1 (all zeroes)",
  86             "0000000000000000000000000000000000000000000000000000000000000000",
  87             "000000000000000000000000",
  88             0, Cipher.ENCRYPT_MODE,
  89             "0000000000000000000000000000000000000000000000000000000000000000" +
  90             "0000000000000000000000000000000000000000000000000000000000000000",
  91             null,
  92             "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7" +
  93             "da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"));
  94         add(new TestData("RFC 7539 Test Vector 2",
  95             "0000000000000000000000000000000000000000000000000000000000000001",
  96             "000000000000000000000002",
  97             1, Cipher.ENCRYPT_MODE,
  98             "416e79207375626d697373696f6e20746f20746865204945544620696e74656e" +
  99             "6465642062792074686520436f6e7472696275746f7220666f72207075626c69" +
 100             "636174696f6e20617320616c6c206f722070617274206f6620616e2049455446" +
 101             "20496e7465726e65742d4472616674206f722052464320616e6420616e792073" +
 102             "746174656d656e74206d6164652077697468696e2074686520636f6e74657874" +
 103             "206f6620616e204945544620616374697669747920697320636f6e7369646572" +
 104             "656420616e20224945544620436f6e747269627574696f6e222e205375636820" +
 105             "73746174656d656e747320696e636c756465206f72616c2073746174656d656e" +
 106             "747320696e20494554462073657373696f6e732c2061732077656c6c20617320" +
 107             "7772697474656e20616e6420656c656374726f6e696320636f6d6d756e696361" +
 108             "74696f6e73206d61646520617420616e792074696d65206f7220706c6163652c" +
 109             "207768696368206172652061646472657373656420746f",
 110             null,
 111             "a3fbf07df3fa2fde4f376ca23e82737041605d9f4f4f57bd8cff2c1d4b7955ec" +
 112             "2a97948bd3722915c8f3d337f7d370050e9e96d647b7c39f56e031ca5eb6250d" +
 113             "4042e02785ececfa4b4bb5e8ead0440e20b6e8db09d881a7c6132f420e527950" +
 114             "42bdfa7773d8a9051447b3291ce1411c680465552aa6c405b7764d5e87bea85a" +
 115             "d00f8449ed8f72d0d662ab052691ca66424bc86d2df80ea41f43abf937d3259d" +
 116             "c4b2d0dfb48a6c9139ddd7f76966e928e635553ba76c5c879d7b35d49eb2e62b" +
 117             "0871cdac638939e25e8a1e0ef9d5280fa8ca328b351c3c765989cbcf3daa8b6c" +
 118             "cc3aaf9f3979c92b3720fc88dc95ed84a1be059c6499b9fda236e7e818b04b0b" +
 119             "c39c1e876b193bfe5569753f88128cc08aaa9b63d1a16f80ef2554d7189c411f" +
 120             "5869ca52c5b83fa36ff216b9c1d30062bebcfd2dc5bce0911934fda79a86f6e6" +
 121             "98ced759c3ff9b6477338f3da4f9cd8514ea9982ccafb341b2384dd902f3d1ab" +
 122             "7ac61dd29c6f21ba5b862f3730e37cfdc4fd806c22f221"));
 123         add(new TestData("RFC 7539 Test Vector 3",
 124             "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0",
 125             "000000000000000000000002",
 126             42, Cipher.ENCRYPT_MODE,
 127             "2754776173206272696c6c69672c20616e642074686520736c6974687920746f" +
 128             "7665730a446964206779726520616e642067696d626c6520696e207468652077" +
 129             "6162653a0a416c6c206d696d737920776572652074686520626f726f676f7665" +
 130             "732c0a416e6420746865206d6f6d65207261746873206f757467726162652e",
 131             null,
 132             "62e6347f95ed87a45ffae7426f27a1df5fb69110044c0d73118effa95b01e5cf" +
 133             "166d3df2d721caf9b21e5fb14c616871fd84c54f9d65b283196c7fe4f60553eb" +
 134             "f39c6402c42234e32a356b3e764312a61a5532055716ead6962568f87d3f3f77" +
 135             "04c6a8d1bcd1bf4d50d6154b6da731b187b58dfd728afa36757a797ac188d1"));
 136     }};
 137 
 138     public static final List<TestData> aeadTestList =
 139             new LinkedList<TestData>() {{
 140         add(new TestData("RFC 7539 Sample AEAD Test Vector",
 141             "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
 142             "070000004041424344454647",
 143             1, Cipher.ENCRYPT_MODE,
 144             "4c616469657320616e642047656e746c656d656e206f662074686520636c6173" +
 145             "73206f66202739393a204966204920636f756c64206f6666657220796f75206f" +
 146             "6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73" +
 147             "637265656e20776f756c642062652069742e",
 148             "50515253c0c1c2c3c4c5c6c7",
 149             "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6" +
 150             "3dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b36" +
 151             "92ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc" +
 152             "3ff4def08e4b7a9de576d26586cec64b61161ae10b594f09e26a7e902ecbd060" +
 153             "0691"));
 154         add(new TestData("RFC 7539 A.5 Sample Decryption",
 155             "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0",
 156             "000000000102030405060708",
 157             1, Cipher.DECRYPT_MODE,
 158             "64a0861575861af460f062c79be643bd5e805cfd345cf389f108670ac76c8cb2" +
 159             "4c6cfc18755d43eea09ee94e382d26b0bdb7b73c321b0100d4f03b7f355894cf" +
 160             "332f830e710b97ce98c8a84abd0b948114ad176e008d33bd60f982b1ff37c855" +
 161             "9797a06ef4f0ef61c186324e2b3506383606907b6a7c02b0f9f6157b53c867e4" +
 162             "b9166c767b804d46a59b5216cde7a4e99040c5a40433225ee282a1b0a06c523e" +
 163             "af4534d7f83fa1155b0047718cbc546a0d072b04b3564eea1b422273f548271a" +
 164             "0bb2316053fa76991955ebd63159434ecebb4e466dae5a1073a6727627097a10" +
 165             "49e617d91d361094fa68f0ff77987130305beaba2eda04df997b714d6c6f2c29" +
 166             "a6ad5cb4022b02709beead9d67890cbb22392336fea1851f38",
 167             "f33388860000000000004e91",
 168             "496e7465726e65742d4472616674732061726520647261667420646f63756d65" +
 169             "6e74732076616c696420666f722061206d6178696d756d206f6620736978206d" +
 170             "6f6e74687320616e64206d617920626520757064617465642c207265706c6163" +
 171             "65642c206f72206f62736f6c65746564206279206f7468657220646f63756d65" +
 172             "6e747320617420616e792074696d652e20497420697320696e617070726f7072" +
 173             "6961746520746f2075736520496e7465726e65742d4472616674732061732072" +
 174             "65666572656e6365206d6174657269616c206f7220746f206369746520746865" +
 175             "6d206f74686572207468616e206173202fe2809c776f726b20696e2070726f67" +
 176             "726573732e2fe2809d"));
 177     }};
 178 
 179 
 180     public static void main(String args[]) throws Exception {
 181         int testsPassed = 0;
 182         int testNumber = 0;
 183 
 184         System.out.println("----- Single-part (byte[]) Tests -----");
 185         for (TestData test : testList) {
 186             System.out.println("*** Test " + ++testNumber + ": " +
 187                     test.testName);
 188             if (runSinglePartTest(test)) {
 189                 testsPassed++;
 190             }
 191         }
 192         System.out.println();
 193 
 194         System.out.println("----- Single-part (ByteBuffer) Tests -----");
 195         for (TestData test : testList) {
 196             System.out.println("*** Test " + ++testNumber + ": " +
 197                     test.testName);
 198             if (runByteBuffer(test)) {
 199                 testsPassed++;
 200             }
 201         }
 202         System.out.println();
 203 
 204 
 205 
 206         System.out.println("----- Multi-part Tests -----");
 207         for (TestData test : testList) {
 208             System.out.println("*** Test " + ++testNumber + ": " +
 209                     test.testName);
 210             if (runMultiPartTest(test)) {
 211                 testsPassed++;
 212             }
 213         }
 214         System.out.println();
 215 
 216         System.out.println("----- AEAD Tests -----");
 217         for (TestData test : aeadTestList) {
 218             System.out.println("*** Test " + ++testNumber + ": " +
 219                     test.testName);
 220             if (runAEADTest(test)) {
 221                 testsPassed++;
 222             }
 223         }
 224         System.out.println();
 225 
 226         System.out.println("Total tests: " + testNumber +
 227                 ", Passed: " + testsPassed + ", Failed: " +
 228                 (testNumber - testsPassed));
 229         if (testsPassed != testNumber) {
 230             throw new RuntimeException("One or more tests failed.  " +
 231                     "Check output for details");
 232         }
 233     }
 234 
 235     private static boolean runSinglePartTest(TestData testData)
 236             throws GeneralSecurityException {
 237         boolean encRes = false;
 238         boolean decRes = false;
 239         byte[] encryptedResult;
 240         byte[] decryptedResult;
 241 
 242         // Get a Cipher instance and set up the parameters
 243         Cipher mambo = Cipher.getInstance("ChaCha20");
 244         SecretKeySpec mamboKey = new SecretKeySpec(testData.key, "ChaCha20");
 245         ChaCha20ParameterSpec mamboSpec = new ChaCha20ParameterSpec(
 246                 testData.nonce, testData.counter);
 247 
 248         // Encrypt our input
 249         mambo.init(Cipher.ENCRYPT_MODE, mamboKey, mamboSpec);
 250         encryptedResult = mambo.doFinal(testData.input);
 251 
 252         if (!Arrays.equals(encryptedResult, testData.expOutput)) {
 253             System.out.println("ERROR - Output Mismatch!");
 254             System.out.println("Expected:\n" +
 255                     dumpHexBytes(testData.expOutput, 16, "\n", " "));
 256             System.out.println("Actual:\n" +
 257                     dumpHexBytes(encryptedResult, 16, "\n", " "));
 258             System.out.println();
 259         } else {
 260             encRes = true;
 261         }
 262 
 263         // Decrypt the result of the encryption operation
 264         mambo = Cipher.getInstance("ChaCha20");
 265         mambo.init(Cipher.DECRYPT_MODE, mamboKey, mamboSpec);
 266         decryptedResult = mambo.doFinal(encryptedResult);
 267 
 268         if (!Arrays.equals(decryptedResult, testData.input)) {
 269             System.out.println("ERROR - Output Mismatch!");
 270             System.out.println("Expected:\n" +
 271                     dumpHexBytes(testData.input, 16, "\n", " "));
 272             System.out.println("Actual:\n" +
 273                     dumpHexBytes(decryptedResult, 16, "\n", " "));
 274             System.out.println();
 275         } else {
 276             decRes = true;
 277         }
 278 
 279         return (encRes && decRes);
 280     }
 281 
 282     private static boolean runMultiPartTest(TestData testData)
 283             throws GeneralSecurityException {
 284         boolean encRes = false;
 285         boolean decRes = false;
 286 
 287         // Get a cipher instance and initialize it
 288         Cipher mambo = Cipher.getInstance("ChaCha20");
 289         SecretKeySpec mamboKey = new SecretKeySpec(testData.key, "ChaCha20");
 290         ChaCha20ParameterSpec mamboSpec = new ChaCha20ParameterSpec(
 291                 testData.nonce, testData.counter);
 292 
 293         byte[] encryptedResult = new byte[testData.input.length];
 294         mambo.init(Cipher.ENCRYPT_MODE, mamboKey, mamboSpec);
 295         System.out.print("Encrypt - ");
 296         doMulti(mambo, testData.input, encryptedResult);
 297 
 298         if (!Arrays.equals(encryptedResult, testData.expOutput)) {
 299             System.out.println("ERROR - Output Mismatch!");
 300             System.out.println("Expected:\n" +
 301                     dumpHexBytes(testData.expOutput, 16, "\n", " "));
 302             System.out.println("Actual:\n" +
 303                     dumpHexBytes(encryptedResult, 16, "\n", " "));
 304             System.out.println();
 305         } else {
 306             encRes = true;
 307         }
 308 
 309         // Decrypt the result of the encryption operation
 310         mambo = Cipher.getInstance("ChaCha20");
 311         byte[] decryptedResult = new byte[encryptedResult.length];
 312         mambo.init(Cipher.DECRYPT_MODE, mamboKey, mamboSpec);
 313         System.out.print("Decrypt - ");
 314         doMulti(mambo, encryptedResult, decryptedResult);
 315 
 316         if (!Arrays.equals(decryptedResult, testData.input)) {
 317             System.out.println("ERROR - Output Mismatch!");
 318             System.out.println("Expected:\n" +
 319                     dumpHexBytes(testData.input, 16, "\n", " "));
 320             System.out.println("Actual:\n" +
 321                     dumpHexBytes(decryptedResult, 16, "\n", " "));
 322             System.out.println();
 323         } else {
 324             decRes = true;
 325         }
 326 
 327         return (encRes && decRes);
 328     }
 329 
 330     private static void doMulti(Cipher c, byte[] input, byte[] output)
 331             throws GeneralSecurityException {
 332         int offset = 0;
 333         boolean done = false;
 334         Random randIn = new Random(System.currentTimeMillis());
 335 
 336         // Send small updates between 1 - 8 bytes in length until we get
 337         // 8 or less bytes from the end of the input, then finalize.
 338         System.out.println("Input length: " + input.length);
 339         System.out.print("Multipart (bytes in/out): ");
 340         while (!done) {
 341             int mPartLen = randIn.nextInt(8) + 1;
 342             int bytesLeft = input.length - offset;
 343             int processed;
 344             if (mPartLen < bytesLeft) {
 345                 System.out.print(mPartLen + "/");
 346                 processed = c.update(input, offset, mPartLen,
 347                         output, offset);
 348                 offset += processed;
 349                 System.out.print(processed + " ");
 350             } else {
 351                 processed = c.doFinal(input, offset, bytesLeft,
 352                         output, offset);
 353                 System.out.print(bytesLeft + "/" + processed + " ");
 354                 done = true;
 355             }
 356         }
 357         System.out.println();
 358     }
 359 
 360     private static boolean runByteBuffer(TestData testData)
 361             throws GeneralSecurityException {
 362         boolean encRes = false;
 363         boolean decRes = false;
 364 
 365         // Get a cipher instance and initialize it
 366         Cipher mambo = Cipher.getInstance("ChaCha20");
 367         SecretKeySpec mamboKey = new SecretKeySpec(testData.key, "ChaCha20");
 368         ChaCha20ParameterSpec mamboSpec = new ChaCha20ParameterSpec(
 369                 testData.nonce, testData.counter);
 370         mambo.init(Cipher.ENCRYPT_MODE, mamboKey, mamboSpec);
 371 
 372         ByteBuffer bbIn = ByteBuffer.wrap(testData.input);
 373         ByteBuffer bbEncOut = ByteBuffer.allocate(
 374                 mambo.getOutputSize(testData.input.length));
 375         ByteBuffer bbExpOut = ByteBuffer.wrap(testData.expOutput);
 376 
 377         mambo.doFinal(bbIn, bbEncOut);
 378         bbIn.rewind();
 379         bbEncOut.rewind();
 380 
 381         if (bbEncOut.compareTo(bbExpOut) != 0) {
 382             System.out.println("ERROR - Output Mismatch!");
 383             System.out.println("Expected:\n" +
 384                     dumpHexBytes(bbExpOut, 16, "\n", " "));
 385             System.out.println("Actual:\n" +
 386                     dumpHexBytes(bbEncOut, 16, "\n", " "));
 387             System.out.println();
 388         } else {
 389             encRes = true;
 390         }
 391 
 392         // Decrypt the result of the encryption operation
 393         mambo = Cipher.getInstance("ChaCha20");
 394         mambo.init(Cipher.DECRYPT_MODE, mamboKey, mamboSpec);
 395         System.out.print("Decrypt - ");
 396         ByteBuffer bbDecOut = ByteBuffer.allocate(
 397                 mambo.getOutputSize(bbEncOut.remaining()));
 398 
 399         mambo.doFinal(bbEncOut, bbDecOut);
 400         bbEncOut.rewind();
 401         bbDecOut.rewind();
 402 
 403         if (bbDecOut.compareTo(bbIn) != 0) {
 404             System.out.println("ERROR - Output Mismatch!");
 405             System.out.println("Expected:\n" +
 406                     dumpHexBytes(bbIn, 16, "\n", " "));
 407             System.out.println("Actual:\n" +
 408                     dumpHexBytes(bbDecOut, 16, "\n", " "));
 409             System.out.println();
 410         } else {
 411             decRes = true;
 412         }
 413 
 414         return (encRes && decRes);
 415     }
 416 
 417     private static boolean runAEADTest(TestData testData)
 418             throws GeneralSecurityException {
 419         boolean result = false;
 420 
 421         Cipher mambo = Cipher.getInstance("ChaCha20-Poly1305");
 422         SecretKeySpec mamboKey = new SecretKeySpec(testData.key, "ChaCha20");
 423         IvParameterSpec mamboSpec = new IvParameterSpec(testData.nonce);
 424 
 425         mambo.init(testData.direction, mamboKey, mamboSpec);
 426 
 427         byte[] out = new byte[mambo.getOutputSize(testData.input.length)];
 428         int outOff = 0;
 429         try {
 430             mambo.updateAAD(testData.aad);
 431             outOff += mambo.update(testData.input, 0, testData.input.length,
 432                     out, outOff);
 433             outOff += mambo.doFinal(out, outOff);
 434         } catch (AEADBadTagException abte) {
 435             // If we get a bad tag or derive a tag mismatch, log it
 436             // and register it as a failure
 437             System.out.println("FAIL: " + abte);
 438             return false;
 439         }
 440 
 441         if (!Arrays.equals(out, testData.expOutput)) {
 442             System.out.println("ERROR - Output Mismatch!");
 443             System.out.println("Expected:\n" +
 444                     dumpHexBytes(testData.expOutput, 16, "\n", " "));
 445             System.out.println("Actual:\n" +
 446                     dumpHexBytes(out, 16, "\n", " "));
 447             System.out.println();
 448         } else {
 449             result = true;
 450         }
 451 
 452         return result;
 453     }
 454 
 455     /**
 456      * Dump the hex bytes of a buffer into string form.
 457      *
 458      * @param data The array of bytes to dump to stdout.
 459      * @param itemsPerLine The number of bytes to display per line
 460      *      if the {@code lineDelim} character is blank then all bytes
 461      *      will be printed on a single line.
 462      * @param lineDelim The delimiter between lines
 463      * @param itemDelim The delimiter between bytes
 464      *
 465      * @return The hexdump of the byte array
 466      */
 467     private static String dumpHexBytes(byte[] data, int itemsPerLine,
 468             String lineDelim, String itemDelim) {
 469         /*
 470         StringBuilder sb = new StringBuilder();
 471         if (data != null) {
 472             for (int i = 0; i < data.length; i++) {
 473                 if (i % itemsPerLine == 0 && i != 0) {
 474                     sb.append(lineDelim);
 475                 }
 476                 sb.append(String.format("%02X", data[i])).append(itemDelim);
 477             }
 478         }
 479 
 480         return sb.toString();
 481         */
 482         return dumpHexBytes(ByteBuffer.wrap(data), itemsPerLine, lineDelim,
 483                 itemDelim);
 484     }
 485 
 486     private static String dumpHexBytes(ByteBuffer data, int itemsPerLine,
 487             String lineDelim, String itemDelim) {
 488         StringBuilder sb = new StringBuilder();
 489         if (data != null) {
 490             data.mark();
 491             int i = 0;
 492             while (data.remaining() > 0) {
 493                 if (i % itemsPerLine == 0 && i != 0) {
 494                     sb.append(lineDelim);
 495                 }
 496                 sb.append(String.format("%02X", data.get())).append(itemDelim);
 497                 i++;
 498             }
 499             data.reset();
 500         }
 501 
 502         return sb.toString();
 503     }
 504 
 505     private static byte[] hex2bin(String hex) {
 506         int i;
 507         int len = hex.length();
 508         byte[] data = new byte [len / 2];
 509         for (i = 0; i < len; i += 2) {
 510             data[i / 2] = (byte)((Character.digit(hex.charAt(i), 16) << 4) +
 511                     Character.digit(hex.charAt(i + 1), 16));
 512         }
 513         return data;
 514     }
 515 
 516 }