samples/messagedigest/src-test/test/OldAPIToNewAPITest.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:52:23 +0200
changeset 44 716af5f2ebd1
child 46 c75861f07646
permissions -rw-r--r--
Switching to freeform project
     1 /*
     2  * To change this template, choose Tools | Templates
     3  * and open the template in the editor.
     4  */
     5 
     6 package test;
     7 
     8 import org.apidesign.api.security.*;
     9 import java.nio.ByteBuffer;
    10 import java.security.MessageDigest;
    11 import java.util.Arrays;
    12 import java.util.Random;
    13 import org.junit.After;
    14 import org.junit.BeforeClass;
    15 import org.junit.Test;
    16 import static org.junit.Assert.*;
    17 
    18 /** Compares that the MessageDigest and Digest yield the same results for
    19  * default provider.
    20  *
    21  * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
    22  */
    23 public class OldAPIToNewAPITest {
    24     private static byte[] arr;
    25     private static long time;
    26     private static byte[] resOld;
    27     private static byte[] resNew;
    28 
    29     public OldAPIToNewAPITest() {
    30     }
    31 
    32     @BeforeClass
    33     public static void setUp() {
    34         time = System.currentTimeMillis();
    35         Random r = new Random(time);
    36         arr = new byte[r.nextInt(1024)];
    37         r.nextBytes(arr);
    38     }
    39 
    40     @After
    41     public void tearDown() {
    42     }
    43 
    44     @Test
    45     public void generateHashUsingMessageDigest() throws Exception {
    46         // The java.security.Providers cannot be registered in META-INF/services
    47         // that is why one needs to either configure various properties or
    48         // make some dummy call that will initialize our bridge class.
    49         // Then the bridge class registers itself as a MessageDigest provider
    50         // in its constructor.
    51         //
    52         // This is the call:
    53         Digest initialize = Digest.getInstance("MD5");
    54         
    55         MessageDigest md = MessageDigest.getInstance("cnt");
    56         byte[] res = md.digest(arr);
    57         resOld = res;
    58     }
    59     
    60     
    61     @Test
    62     public void generateHashUsingNewDigest() throws Exception {
    63         Digest d = Digest.getInstance("cnt");
    64         ByteBuffer bb = ByteBuffer.wrap(arr);
    65         byte[] res = d.digest(bb);
    66         resNew = res;
    67     }
    68 
    69 
    70     
    71     @Test
    72     public void compareTheHashes() throws Exception {
    73         if (!Arrays.equals(resOld, resNew)) {
    74             fail("Arrays are different:\n" + Arrays.toString(resOld) + "\n" + Arrays.toString(resNew));
    75         }
    76     }
    77 }