如何对 Map进行编码作为 Base64 字符串?

发布于 2024-08-21 04:58:42 字数 1158 浏览 3 评论 0原文

我喜欢将 java 字符串映射编码为单个 Base 64 编码字符串。编码后的字符串将被传输到远程端点,并且可能被不怀好意的人操纵。因此,最糟糕的情况应该是无效的键、值元组,但不应带来任何其他安全风险。

示例:

Map<String,String> map = ...
String encoded = Base64.encode(map);

// somewhere else
Map<String,String> map = Base64.decode(encoded);

是的,必须是 Base64。 不是这样的 或任何其他这些。是否有现有的轻量级解决方案(首选单一实用程序类)?或者我必须创建自己的?

还有比这更好的吗?

// marshalling
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(map);
oos.close();
String encoded = new String(Base64.encodeBase64(baos.toByteArray()));

// unmarshalling 
byte[] decoded = Base64.decodeBase64(encoded.getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
ObjectInputStream ois = new ObjectInputStream(bais);
map = (Map<String,String>) ois.readObject();
ois.close();

谢谢,

i like to encode a java map of strings as a single base 64 encoded string. The encoded string will be transmitted to a remote endpoint and maybe manipulated by a not nice person. So the worst thing that should happen are invaild key,value-tuples, but should not bring any other security risks aside.

Example:

Map<String,String> map = ...
String encoded = Base64.encode(map);

// somewhere else
Map<String,String> map = Base64.decode(encoded);

Yes, must be Base64. Not like that or that or any other of these. Is there an existing lightweight solution (Single Utils-Class prefered) out there? Or do i have to create my own?

Anything better than this?

// marshalling
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(map);
oos.close();
String encoded = new String(Base64.encodeBase64(baos.toByteArray()));

// unmarshalling 
byte[] decoded = Base64.decodeBase64(encoded.getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
ObjectInputStream ois = new ObjectInputStream(bais);
map = (Map<String,String>) ois.readObject();
ois.close();

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

つ可否回来 2024-08-28 04:58:42

我的主要要求是:编码字符串应尽可能短,并且仅包含拉丁字符或来自 base64 字母表的字符(不是我的要求)。没有其他要求。

使用 Google Gson 转换 映射JSON。使用 GZIPOutputStream 压缩 JSON 字符串。使用 Apache Commons 编解码器 Base64Base64OutputStream< /code>将压缩字节编码为 Base64 字符串。

开球示例:

public static void main(String[] args) throws IOException {
    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    String serialized = serialize(map);
    Map<String, String> deserialized = deserialize(serialized, new TypeToken<Map<String, String>>() {}.getType());

    System.out.println(deserialized);
}

public static String serialize(Object object) throws IOException {
    ByteArrayOutputStream byteaOut = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = null;
    try {
        gzipOut = new GZIPOutputStream(new Base64OutputStream(byteaOut));
        gzipOut.write(new Gson().toJson(object).getBytes("UTF-8"));
    } finally {
        if (gzipOut != null) try { gzipOut.close(); } catch (IOException logOrIgnore) {}
    }
    return new String(byteaOut.toByteArray());
}

public static <T> T deserialize(String string, Type type) throws IOException {
    ByteArrayOutputStream byteaOut = new ByteArrayOutputStream();
    GZIPInputStream gzipIn = null;
    try {
        gzipIn = new GZIPInputStream(new Base64InputStream(new ByteArrayInputStream(string.getBytes("UTF-8"))));
        for (int data; (data = gzipIn.read()) > -1;) {
            byteaOut.write(data);
        }
    } finally {
        if (gzipIn != null) try { gzipIn.close(); } catch (IOException logOrIgnore) {}
    }
    return new Gson().fromJson(new String(byteaOut.toByteArray()), type);
}

my primary requirements are: encoded string should be as short as possible and contain only latin characters or characters from the base64 alphabet (not my call). there are no other reqs.

Use Google Gson to convert Map to JSON. Use GZIPOutputStream to compress the JSON string. Use Apache Commons Codec Base64 or Base64OutputStream to encode the compressed bytes to a Base64 string.

Kickoff example:

public static void main(String[] args) throws IOException {
    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    String serialized = serialize(map);
    Map<String, String> deserialized = deserialize(serialized, new TypeToken<Map<String, String>>() {}.getType());

    System.out.println(deserialized);
}

public static String serialize(Object object) throws IOException {
    ByteArrayOutputStream byteaOut = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = null;
    try {
        gzipOut = new GZIPOutputStream(new Base64OutputStream(byteaOut));
        gzipOut.write(new Gson().toJson(object).getBytes("UTF-8"));
    } finally {
        if (gzipOut != null) try { gzipOut.close(); } catch (IOException logOrIgnore) {}
    }
    return new String(byteaOut.toByteArray());
}

public static <T> T deserialize(String string, Type type) throws IOException {
    ByteArrayOutputStream byteaOut = new ByteArrayOutputStream();
    GZIPInputStream gzipIn = null;
    try {
        gzipIn = new GZIPInputStream(new Base64InputStream(new ByteArrayInputStream(string.getBytes("UTF-8"))));
        for (int data; (data = gzipIn.read()) > -1;) {
            byteaOut.write(data);
        }
    } finally {
        if (gzipIn != null) try { gzipIn.close(); } catch (IOException logOrIgnore) {}
    }
    return new Gson().fromJson(new String(byteaOut.toByteArray()), type);
}
一城柳絮吹成雪 2024-08-28 04:58:42

另一种可能的方法是使用 JSON 这是一个非常轻量级的库。
那么编码将如下所示:

JSONObject jso = new JSONObject( map );
String encoded = new String(Base64.encodeBase64( jso.toString( 4 ).toByteArray()));

Another possible way would be using JSON which is a very ligthweight lib.
The the encoding then would look like this:

JSONObject jso = new JSONObject( map );
String encoded = new String(Base64.encodeBase64( jso.toString( 4 ).toByteArray()));
魔法少女 2024-08-28 04:58:42

您的解决方案有效。唯一的其他方法是自己序列化映射(迭代键和值)。这意味着您必须确保正确处理所有情况(例如,如果您将值作为 key=value 传输,则必须找到一种方法允许 = 在键/值中,并且您必须以某种方式分隔这些对,这意味着您还必须在名称中允许此分隔字符,等等)。

总而言之,很难做到正确,很容易出错,并且需要更多的代码和令人头疼的事情。另外,不要忘记您必须在解析器(接收方)中编写大量错误处理代码。

Your solution works. The only other approach would be to serialize the map yourself (iterate over the keys and values). That would mean you'd have to make sure you handle all the cases correctly (for example, if you transmit the values as key=value, you must find a way to allow = in the key/value and you must separate the pairs somehow which means you must also allow this separation character in the name, etc).

All in all, it's hard to get right, easy to get wrong and would take a whole lot more code and headache. Plus don't forget that you'd have to write a lot of error handling code in the parser (receiver side).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文