Convert a base64-encoded String to binary data @param str A String containing the encoded data @return An array containing the binary data, or null if the string is invalid
(String str)
| 92 | * @return An array containing the binary data, or null if the string is invalid |
| 93 | */ |
| 94 | public static byte [] |
| 95 | fromString(String str) { |
| 96 | ByteArrayOutputStream bs = new ByteArrayOutputStream(); |
| 97 | byte [] raw = str.getBytes(); |
| 98 | for (int i = 0; i < raw.length; i++) { |
| 99 | if (!Character.isWhitespace((char)raw[i])) |
| 100 | bs.write(raw[i]); |
| 101 | } |
| 102 | byte [] in = bs.toByteArray(); |
| 103 | if (in.length % 4 != 0) { |
| 104 | return null; |
| 105 | } |
| 106 | |
| 107 | bs.reset(); |
| 108 | DataOutputStream ds = new DataOutputStream(bs); |
| 109 | |
| 110 | for (int i = 0; i < (in.length + 3) / 4; i++) { |
| 111 | short [] s = new short[4]; |
| 112 | short [] t = new short[3]; |
| 113 | |
| 114 | for (int j = 0; j < 4; j++) |
| 115 | s[j] = (short) Base64.indexOf(in[i*4+j]); |
| 116 | |
| 117 | t[0] = (short) ((s[0] << 2) + (s[1] >> 4)); |
| 118 | if (s[2] == 64) { |
| 119 | t[1] = t[2] = (short) (-1); |
| 120 | if ((s[1] & 0xF) != 0) |
| 121 | return null; |
| 122 | } |
| 123 | else if (s[3] == 64) { |
| 124 | t[1] = (short) (((s[1] << 4) + (s[2] >> 2)) & 0xFF); |
| 125 | t[2] = (short) (-1); |
| 126 | if ((s[2] & 0x3) != 0) |
| 127 | return null; |
| 128 | } |
| 129 | else { |
| 130 | t[1] = (short) (((s[1] << 4) + (s[2] >> 2)) & 0xFF); |
| 131 | t[2] = (short) (((s[2] << 6) + s[3]) & 0xFF); |
| 132 | } |
| 133 | |
| 134 | try { |
| 135 | for (int j = 0; j < 3; j++) |
| 136 | if (t[j] >= 0) |
| 137 | ds.writeByte(t[j]); |
| 138 | } |
| 139 | catch (IOException e) { |
| 140 | } |
| 141 | } |
| 142 | return bs.toByteArray(); |
| 143 | } |
| 144 | |
| 145 | } |
nothing calls this directly
no test coverage detected