Java的:与java.util.Base64 VS android.util.Base64解码的base64字符串时,不同的结果 [英] Java: Different results when decoding base64 string with java.util.Base64 vs android.util.Base64
问题描述
我的工作一个客户机/服务器系统上,我试图做一些基本的加密。当我连接到服务器,我送一个公钥通过套接字转义字符串。我已经验证该字符串的相同的两端,换行和所有即可。
I'm working on a client/server system and I'm trying to do some basic encryption. When I connect to the server, I send a public key as an escaped string across the socket. I've verified that the string is identical on both ends, newlines and all.
在客户端(Android的),我能够使用公共/专用密钥成功地加密和解密的密钥(用于测试目的)。但是,服务器当试图去code从字符串到一个byte []公钥与失败右出了大门:
On the client (Android), I'm able to use the public/private keys to successfully encrypt and decrypt a secret key (for testing purposes). However, the server fails right out of the gate when trying to decode the public key from a String to a byte[], with:
java.lang.IllegalArgumentException: Illegal base64 character a
这似乎是preposterous,作为A绝对是一个base64字符,如果我理解正确。客户端和服务器使用共享库来处理所有的加密,所以code是几乎相同的。在仅的区别在于编码/解码的base64字符串,因为java.util.Base64是在Android上不可用。
which seems preposterous, as 'a' is absolutely a base64 character, if I understand correctly. The client and server use a shared library to handle all encryption, so the code is nearly identical. The only difference is encoding/decoding base64 Strings, since java.util.Base64 is unavailable on Android.
共享类
public abstract class EasyCrypt {
...
public PublicKey loadPublicKey(String key64) throws GeneralSecurityException {
byte[] data = decode(key64); //Calls abstract methods, shown below
X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
KeyFactory fact = KeyFactory.getInstance("RSA");
return fact.generatePublic(spec);
}
...
}
客户端(Android版)方法
import android.util.Base64;
public class ClientCrypt extends EasyCrypt {
@Override
protected byte[] decode(String s) {
return Base64.decode(s.getBytes(), Base64.DEFAULT); //Works perfectly
}
@Override
protected String encode(byte[] bytes) {
return Base64.encodeToString(bytes, Base64.DEFAULT);
}
}
服务器(Linux)的方法
import java.util.Base64;
public class ServerCrypt extends EasyCrypt{
@Override
public byte[] decode(String str){
return Base64.getDecoder().decode(str); //Throws IllegalArgumentException
}
@Override
public String encode(byte[] bytes){
return Base64.getEncoder().encodeToString(bytes);
}
}
推荐答案
在Android上,使用 Base64.NO_WRAP
而不是 Base64.DEFAULT
On android, Use Base64.NO_WRAP
instead of Base64.DEFAULT
@Override
protected String encode(byte[] bytes) {
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
这篇关于Java的:与java.util.Base64 VS android.util.Base64解码的base64字符串时,不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!