1 18 package com.Ostermiller.util; 19 20 import java.util.*; 21 import java.io.*; 22 23 class Base64Tests { 24 25 private static class TestCase { 26 private String encoded; 27 private byte[] decoded; 28 public TestCase(String encoded, byte[] decoded){ 29 this.encoded = encoded; 30 this.decoded = decoded; 31 } 32 private void test() throws Exception { 33 String enc = Base64.encodeToString(decoded); 34 if (!encoded.equals(enc)){ 35 throw new Exception ("Decoding problem, expected '" + encoded + "' got '" + enc + "'."); 36 } 37 byte[] b = Base64.decodeToBytes(encoded); 38 if (!byteArraysEqual(b, decoded)){ 39 throw new Exception ("Encoding problem, started with '" + encoded + "'."); 40 } 41 } 42 } 43 44 private static boolean byteArraysEqual(byte[] b1, byte[] b2){ 45 if (b1.length != b2.length) return false; 46 for (int i=0; i<b1.length; i++){ 47 if (b1[i] != b2[i]) return false; 48 } 49 return true; 50 } 51 52 private static final TestCase[] testCases = new TestCase[]{ 53 new TestCase("", new byte[]{}), 54 new TestCase("aA==", new byte[]{'h'}), 55 new TestCase("dGU=", new byte[]{'t','e'}), 56 new TestCase("Y29i", new byte[]{'c','o','b'}), 57 }; 58 59 public static void main(String [] args){ 60 try { 61 for (int i=0; i<testCases.length; i++){ 62 testCases[i].test(); 63 } 64 for (int i=0; i<1024; i++){ 65 byte[] before = randBytes(); 66 byte[] after = Base64.decodeToBytes(Base64.encodeToString(before)); 67 if (!byteArraysEqual(before,after)){ 68 throw new Exception ("Could not decode and then reencode:\nbefore: " + bytesToString(before) + "\nafter: " + bytesToString(after)); 69 } 70 } 71 72 73 } catch (Exception x){ 74 x.printStackTrace(System.err); 75 System.exit(1); 76 } 77 System.exit(0); 78 } 79 80 private static String bytesToString(byte[] b){ 81 StringBuffer sb = new StringBuffer (); 82 for (int i=0; i<b.length; i++){ 83 sb.append("'").append((int)b[i]).append("',"); 84 } 85 return sb.toString(); 86 } 87 88 private static byte[] randBytes(){ 89 Random rand = new Random(); 90 byte[] bytes = new byte[rand.nextInt(128)*3]; 91 for (int i=0; i<bytes.length; i++){ 92 bytes[i] = (byte)(rand.nextInt() & 0xff); 93 } 94 return bytes; 95 } 96 } 97 | Popular Tags |