Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. | 3 // BSD-style license that can be found in the LICENSE file. |
| 4 | 4 |
| 5 class _CryptoUtils { | 5 class _CryptoUtils { |
| 6 static String bytesToHex(List<int> bytes) { | 6 static String bytesToHex(List<int> bytes) { |
| 7 var result = new StringBuffer(); | 7 var result = new StringBuffer(); |
| 8 for (var part in bytes) { | 8 for (var part in bytes) { |
| 9 result.add('${part < 16 ? '0' : ''}${part.toRadixString(16)}'); | 9 result.add('${part < 16 ? '0' : ''}${part.toRadixString(16)}'); |
| 10 } | 10 } |
| 11 return result.toString(); | 11 return result.toString(); |
| 12 } | 12 } |
| 13 | |
| 14 static String bytesToBase64(List<int> bytes) { | |
| 15 final table = | |
| 16 const [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', | |
| 17 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', | |
| 18 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', | |
| 19 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', | |
| 20 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', | |
| 21 '8', '9', '+', '/' ]; | |
| 22 | |
| 23 var result = new StringBuffer(); | |
| 24 | |
| 25 // Encode all full 24-bit blocks. | |
| 26 var i = 0; | |
| 27 for (; (i + 2) < bytes.length; i += 3) { | |
| 28 var b0 = bytes[i] & 0xff; | |
| 29 var b1 = bytes[i + 1] & 0xff; | |
| 30 var b2 = bytes[i + 2] & 0xff; | |
| 31 result.add(table[b0 >> 2]); | |
| 32 result.add(table[((b0 << 4) | (b1 >> 4)) & 0x3f]); | |
| 33 result.add(table[((b1 << 2) | (b2 >> 6)) & 0x3f]); | |
| 34 result.add(table[b2 & 0x3f]); | |
|
Søren Gjesse
2012/05/30 13:40:08
You need to insert \r\n for at least every 76 char
Mads Ager (google)
2012/05/30 15:16:10
http://tools.ietf.org/html/rfc4648
explicitly say
| |
| 35 } | |
| 36 | |
| 37 // Deal with the last non-full block if any and add padding '='. | |
| 38 if (i == bytes.length - 1) { | |
| 39 var b0 = bytes[i] & 0xff; | |
| 40 result.add(table[b0 >> 2]); | |
| 41 result.add(table[(b0 << 4) & 0x3f]); | |
| 42 result.add('='); | |
| 43 result.add('='); | |
| 44 } else if (i == bytes.length - 2) { | |
| 45 var b0 = bytes[i] & 0xff; | |
| 46 var b1 = bytes[i + 1] & 0xff; | |
| 47 result.add(table[b0 >> 2]); | |
| 48 result.add(table[((b0 << 4) | (b1 >> 4)) & 0x3f]); | |
| 49 result.add(table[(b1 << 2) & 0x3f]); | |
| 50 result.add('='); | |
| 51 } | |
| 52 | |
| 53 return result.toString(); | |
| 54 } | |
| 13 } | 55 } |
| OLD | NEW |