好的,这就是我面临的情况。我正在构建一个带有登录屏幕的 Android 应用程序,并对发送到我的服务器的信息进行加密。加密后,我在 android 上使用 Base64 对信息进行编码,将其发送到我的电脑上的服务器,该服务器正在以 Base64 进行解码,但它没有正确执行。我的服务器报告加密填充错误。
这是 Android 上的加密代码:
import android.util.Base64;
try {
plainText = user.getBytes("UTF-8");
user = EncryptInfo(plainText, publicKey);
} catch (UnsupportedEncodingException ex) {
ex.getStackTrace();
}
private static String EncryptInfo(byte[] data,PublicKey key){
Cipher cipher;
byte[] cipherText = null;
try {
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(data);
} catch (NoSuchAlgorithmException ex) {
ex.getStackTrace();
System.exit(1);
} catch (NoSuchPaddingException ex) {
ex.getStackTrace();
System.exit(1);
} catch (InvalidKeyException ex) {
ex.getStackTrace();
System.exit(1);
} catch (IllegalBlockSizeException ex) {
ex.getStackTrace();
System.exit(1);
} catch (BadPaddingException ex) {
ex.getStackTrace();
System.exit(1);
}
return Base64.encodeToString(cipherText, Base64.DEFAULT);
}
这是在我的电脑上运行的代码,在服务器上解码数据:
import java.util.Base64;
//Decrypt the userpassword
byte[] plainText = Base64.getDecoder().decode(encryptedData);
inputLine = decryptData(plainText);
private String decryptData(byte[] cipherText) throws UnsupportedEncodingException{
// decrypt the ciphertext using the private key
Cipher cipher;
byte[] newPlainText = null;
try {
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
newPlainText = cipher.doFinal(cipherText);
//System.out.println( "Finish decryption: " );
//System.out.println( new String(newPlainText, "UTF8") );
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
return new String(newPlainText, "UTF8");
}
我已经包含了用于 Base64 的导入。另外,这不是完整的代码,而只是相关的部分。我不完全理解 base64,我所有的搜索都没有给我带来答案,所以任何帮助将不胜感激!
编辑:我做这一切的原因是为了安全地将登录凭据传输到服务器。这在我的桌面应用程序上运行得很好。我从桌面应用程序复制了代码,但编码是唯一需要更改的内容。我相信 Base 64 是问题的一部分。无法调试该应用程序,因为我运行 amd,所以我必须在手机上运行它。
最佳答案
答案:
return Base64.encodeToString(cipherText, Base64.NO_WRAP);
调试后发现我的加密数据在中途被切断了。使用 Base64.No_Wrap 解决了我的问题。只是发布出来,让大家都知道。 Android 开发对我来说是新事物,所以我想我根本没有想到它。
关于java - 多平台Base64编解码问题(Android to PC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36852498/