01: package winstone.testCase;
02:
03: import junit.framework.TestCase;
04: import winstone.auth.BasicAuthenticationHandler;
05:
06: public class Base64Test extends TestCase {
07: public Base64Test(String name) {
08: super (name);
09: }
10:
11: // The letters a-y encoded in base 64
12: private static String ENCODED_PLUS_ONE = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eQ==";
13: private static String ENCODED_PLUS_TWO = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=";
14:
15: public void testDecode() throws Exception {
16: String decoded = decodeBase64(ENCODED_PLUS_TWO);
17: String expected = "abcdefghijklmnopqrstuvwxyz";
18: assertEquals("Straight decode failed", expected, decoded);
19:
20: decoded = decodeBase64(ENCODED_PLUS_ONE);
21: expected = "abcdefghijklmnopqrstuvwxy";
22: assertEquals("Decode failed", expected, decoded);
23: }
24:
25: public static void testVersusPostgres() throws Exception {
26: String decoded = decodeBase64("MTIzNDU2Nzg5MA==");
27: assertEquals("Straight encode failed", "1234567890", decoded);
28: }
29:
30: /**
31: * Expects the classic base64 "abcdefgh=" syntax (equals padded)
32: * and decodes it to original form
33: */
34: public static String decodeBase64(String input) {
35: char[] inBytes = input.toCharArray();
36: byte[] outBytes = new byte[(int) (inBytes.length * 0.75f)]; // always mod 4 = 0
37: int length = BasicAuthenticationHandler.decodeBase64(inBytes,
38: outBytes, 0, inBytes.length, 0);
39: return new String(outBytes, 0, length);
40: }
41:
42: public static String hexEncode(byte input[]) {
43:
44: StringBuffer out = new StringBuffer();
45:
46: for (int i = 0; i < input.length; i++)
47: out.append(Integer.toString((input[i] & 0xf0) >> 4, 16))
48: .append(Integer.toString(input[i] & 0x0f, 16));
49:
50: return out.toString();
51: }
52:
53: public static byte[] hexDecode(String input) {
54:
55: if (input == null) {
56: return null;
57: } else if (input.length() % 2 != 0) {
58: throw new RuntimeException("Invalid hex for decoding: "
59: + input);
60: } else {
61: byte output[] = new byte[input.length() / 2];
62:
63: for (int i = 0; i < output.length; i++) {
64: int twoByte = Integer.parseInt(input.substring(i * 2,
65: i * 2 + 2), 16);
66: output[i] = (byte) (twoByte & 0xff);
67: }
68: return output;
69: }
70: }
71: }
|