1 7 package org.jboss.security; 8 9 14 public class Base64Utils 15 { 16 private static final char[] base64Table = 17 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./".toCharArray(); 18 public static final String BASE64_ENCODING = "BASE64"; 19 public static final String BASE16_ENCODING = "HEX"; 20 21 public static String tob64(byte[] buffer) 25 { 26 boolean notleading = false; 27 int len = buffer.length, pos = len % 3, c; 28 byte b0 = 0, b1 = 0, b2 = 0; 29 StringBuffer sb = new StringBuffer (); 30 31 switch(pos) 32 { 33 case 1: 34 b2 = buffer[0]; 35 break; 36 case 2: 37 b1 = buffer[0]; 38 b2 = buffer[1]; 39 break; 40 } 41 do 42 { 43 c = (b0 & 0xfc) >>> 2; 44 if(notleading || c != 0) 45 { 46 sb.append(base64Table[c]); 47 notleading = true; 48 } 49 c = ((b0 & 3) << 4) | ((b1 & 0xf0) >>> 4); 50 if(notleading || c != 0) 51 { 52 sb.append(base64Table[c]); 53 notleading = true; 54 } 55 c = ((b1 & 0xf) << 2) | ((b2 & 0xc0) >>> 6); 56 if(notleading || c != 0) 57 { 58 sb.append(base64Table[c]); 59 notleading = true; 60 } 61 c = b2 & 0x3f; 62 if(notleading || c != 0) 63 { 64 sb.append(base64Table[c]); 65 notleading = true; 66 } 67 if(pos >= len) 68 break; 69 else 70 { 71 try 72 { 73 b0 = buffer[pos++]; 74 b1 = buffer[pos++]; 75 b2 = buffer[pos++]; 76 } 77 catch(ArrayIndexOutOfBoundsException e) 78 { 79 break; 80 } 81 } 82 } while(true); 83 84 if(notleading) 85 return sb.toString(); 86 else 87 return "0"; 88 } 89 90 public static byte[] fromb64(String str) throws NumberFormatException 91 { 92 int len = str.length(); 93 if(len == 0) 94 throw new NumberFormatException ("Empty Base64 string"); 95 96 byte[] a = new byte[len + 1]; 97 char c; 98 int i, j; 99 100 for(i = 0; i < len; ++i) 101 { 102 c = str.charAt(i); 103 try 104 { 105 for(j = 0; c != base64Table[j]; ++j) 106 ; 107 } catch(Exception e) 108 { 109 throw new NumberFormatException ("Illegal Base64 character"); 110 } 111 a[i] = (byte) j; 112 } 113 114 i = len - 1; 115 j = len; 116 try 117 { 118 while(true) 119 { 120 a[j] = a[i]; 121 if(--i < 0) 122 break; 123 a[j] |= (a[i] & 3) << 6; 124 --j; 125 a[j] = (byte) ((a[i] & 0x3c) >>> 2); 126 if(--i < 0) 127 break; 128 a[j] |= (a[i] & 0xf) << 4; 129 --j; 130 a[j] = (byte) ((a[i] & 0x30) >>> 4); 131 if(--i < 0) 132 break; 133 a[j] |= (a[i] << 2); 134 135 a[j-1] = 0; --j; 142 145 if(--i < 0) 146 break; 147 } 148 } 149 catch(Exception e) 150 { 151 152 } 153 154 try 155 { 156 while(a[j] == 0) 157 ++j; 158 } 159 catch(Exception e) 160 { 161 return new byte[1]; 162 } 163 164 byte[] result = new byte[len - j + 1]; 165 System.arraycopy(a, j, result, 0, len - j + 1); 166 return result; 167 } 168 169 } 170 | Popular Tags |