我在我的 java 应用程序中使用带有公钥的 RSA 加密将数据发送到服务器。当我使用 java 执行此操作时一切正常,但是当我尝试使用 android 执行相同操作时,我在服务器中收到以下错误:
java.security.InvalidKeyException: Illegal key size or default parameters
这是我在 android 和 java 上加密数据的代码:
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.io.*;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.SecureRandom;
public class Encryption {
private static String base64Encode(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
private static void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException, GeneralSecurityException {
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] inBytes = new byte[blockSize];
byte[] outBytes = new byte[outputSize];
int inLength = 0;
boolean more = true;
while (more) {
inLength = in.read(inBytes);
if (inLength == blockSize) {
int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
out.write(outBytes, 0, outLength);
} else more = false;
}
if (inLength > 0) outBytes = cipher.doFinal(inBytes, 0, inLength);
else outBytes = cipher.doFinal();
out.write(outBytes);
}
public static String encryptWithPublicKey(String property) {
String result = null;
KeyGenerator keygen;
SecureRandom random;
Key publicKey;
SecretKey key;
Cipher cipher;
ObjectInputStream keyIn = null;
ByteArrayOutputStream baos = null;
DataOutputStream out = null;
InputStream in = null;
try {
keygen = KeyGenerator.getInstance("AES");
random = new SecureRandom();
keygen.init(random);
key = keygen.generateKey();
keyIn = new ObjectInputStream(new FileInputStream("public.key"));
publicKey = (Key) keyIn.readObject();
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.WRAP_MODE, publicKey);
byte[] wrappedKey = cipher.wrap(key);
baos = new ByteArrayOutputStream();
out = new DataOutputStream(baos);
out.writeInt(wrappedKey.length);
out.write(wrappedKey);
in = new ByteArrayInputStream(property.getBytes("UTF-8"));
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
crypt(in, out, cipher);
result = base64Encode(baos.toByteArray());
} catch (Exception ex) {
ex.printStackTrace();
} finally {
Util.close(baos);
Util.close(out);
Util.close(in);
Util.close(keyIn);
}
return result;
}
}
当我从java代码使用encryptWithPublicKey
时结果很好,但当我从android使用它时出现错误!这两个系统之间有什么区别?
最佳答案
发生这种情况的原因可能是您没有为 Cipher
对象指定完整的 algorithm/mode/padding
选项。
例如,将“RSA”更改为“RSA/ECB/PKCS1Padding”。并将“AES”更改为“AES/CBC/PKCS5Padding”。或者任何合适的值。
原因:不同的加密提供商对于填充和模式有不同的默认值。如果您只指定算法,则您将依赖默认值,而不同系统之间可能不兼容。
关于java - java和android的加密区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20312023/