【发布时间】:2017-09-15 23:57:45
【问题描述】:
以下非对称函数用于在android中进行加密和解密..它完美地工作。但是,当我使用下面的函数加密并使用 php 或其他函数(使用 eclipse 非常相似)解密时。我得到 null .. 填充异常错误 .. 我无法弄清楚问题 .. 因为我正在对结果进行编码..为什么它只有在我在android或eclipse中加密和解密时才有效..但在php和android之间或仅在两个java程序之间不起作用..但在eclipse和android..
安卓程序:
public String encryptAsymmetric(String input, Key key) throws GeneralSecurityException, IOException {
byte[] crypted = null;
try{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
crypted = cipher.doFinal(input.getBytes());
}catch(Exception e){
System.out.println(e.toString());
}//Base64.encodeBase64(crypted)
return new String(Base64.encode(crypted, Base64.DEFAULT));
}
public String decryptAsymmetric(String input, Key key){
byte[] output = null;
try{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);//Base64.decodeBase64(input.getBytes())
output = cipher.doFinal(Base64.decode(input.getBytes(), Base64.DEFAULT));
}catch(Exception e){
System.out.println(e.toString());
}
return new String(output);
}
Eclipse(Java 程序也是如此):
public static String encryptAsymmetric(String input, Key key){
byte[] crypted = null;
try{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
crypted = cipher.doFinal(input.getBytes());
}catch(Exception e){
System.out.println(e.toString());
}//Base64.encodeBase64(crypted)
return new String(Base64.getEncoder().encode(crypted));
}
public static String decryptAsymmetric(String input, Key key){
byte[] output = null;
try{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);//Base64.decodeBase64(input.getBytes())
output = cipher.doFinal(Base64.getDecoder().decode(input.getBytes()));
}catch(Exception e){
System.out.println(e.toString());
}
return new String(output);
}
【问题讨论】:
-
Cipher.getInstance("RSA");依赖于默认模式和填充,并且是不可可移植的。永远不要那样做。input.getBytes()依赖于默认字符集并且是not可移植的。永远不要那样做。 -
你能解释一下在这种情况下便携是什么意思
-
相同的代码在具有不同平台默认字符集的平台上会产生不同的结果,并且在 Oracle Java 平台和 Android 平台上会产生不同的结果。
-
哦,这解释了我的问题..但是我怎样才能替换“RSA”.. getBytes 函数我将寻找替代方法
-
如果我使用 input.getBytes("UTF-8"); ..这会有帮助吗?
标签: java php android encryption encryption-asymmetric