【发布时间】:2016-08-19 13:09:08
【问题描述】:
好的,这就是我面临的情况。我正在构建一个带有登录屏幕的 android 应用程序并加密信息以发送到我的服务器。加密后,我在 android 上使用 Base64 对信息进行编码,以将其发送到我的 PC 上的服务器,该服务器正在 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,所以我必须直接在手机上运行它。
【问题讨论】:
-
但是你使用 base64 是为了什么? 7bit 时代已经结束。
-
是什么让您认为 base64 是问题所在?如果是,应该直接在两端进行一些调试,而不会使加密复杂化。
-
我正在尝试通过套接字轻松移动数据并进行可能的存储。再一次,我对 base64 了解不多,但它在我的桌面应用程序中工作。我的 android 应用程序基于相同的代码。如果我能摆脱它并使用其他东西,那就太好了。原来 android 包含一个旧版本的 commons 库,所以当我尝试使用更新的库时,它只是说它找不到方法 encodeAsString。
-
Base64 不太可能是罪魁祸首.. 但我的观点是,这可以通过一些简单的调试轻松排除。 - 在客户端调试进入 base64 的内容以及在服务器端从 base64 输出的内容。是一样的吗?
-
@Edde 我设法使用手机上的通知对其进行了调试。现在加密似乎更有可能是罪魁祸首。我使用私钥/公钥加密,其中应用程序只有公钥并且我持有私钥(每个会话随机生成)。所以我想现在我必须看看那里发生了什么。我不知道为什么我认为这是问题所在。
标签: java android sockets encryption base64