Quelle est la bonne façon de convertir un octet [] en une chaîne Base64 en Java? Mieux encore serait Grails / Groovy, car il me dit que la fonction encodeAsBase64()
est obsolète. L’ sun.misc.BASE64Encoder
package sun.misc.BASE64Encoder
n’est pas recommandée et génère une chaîne de taille différente sur certaines plates-formes Windows.
Apache Commons a de nombreux utilitaires:
Paquet binary: http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html
Télécharger: http://commons.apache.org/codec/download_codec.cgi
La manière préférée de faire ceci dans groovy est:
def encoded = "Hello World".bytes.encodeBase64().toSsortingng() assert encoded == "SGVsbG8gV29ybGQ=" def decoded = new Ssortingng("SGVsbG8gV29ybGQ=".decodeBase64()) assert decoded == "Hello World"
Vous pouvez utiliser la bibliothèque open source Base64Coder
import biz.source_code.base64Coder.Base64Coder @Grab(group='biz.source_code', module='base64coder', version='2010-09-21') Ssortingng s1 = Base64Coder.encodeSsortingng("Hello world") Ssortingng s2 = Base64Coder.decodeSsortingng("SGVsbG8gd29ybGQ=")
Implémentez votre propre méthode comme ça 🙂
public class Coder { private static final Ssortingng base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; public static Ssortingng encodeAsBase64(Ssortingng toEncode) { return encodeAsBase64(toEncode.getBytes()) } public static Ssortingng encodeAsBase64(byte[] toEncode) { int pos = 0; int onhand = 0; SsortingngBuffer buffer = new SsortingngBuffer(); for(byte b in toEncode) { int read = b; int m; if(pos == 0) { m = (read >> 2) & 63; onhand = read & 3; pos = 1; } else if(pos == 1) { m = (onhand << 4) + ((read >> 4) & 15); onhand = read & 15; pos = 2; } else if(pos == 2) { m = ((read >> 6) & 3) + (onhand << 2); onhand = read & 63; buffer.append(base64code.charAt(m)); m = onhand; onhand = 0; pos = 0; } buffer.append(base64code.charAt(m)); } while(pos > 0 && pos < 4) { pos++; if(onhand == -1) { buffer.append('='); } else { int m = pos == 2 ? onhand << 4 : (pos == 3 ? onhand << 2 : onhand); onhand = -1; buffer.append(base64code.charAt(m)); } } return buffer.toString() }
}