我在我的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使用它时我有错误!这两个系统之间的差异是什么?
答案 0 :(得分:2)
可能会发生这种情况,因为您没有为algorithm/mode/padding
个对象指定完整的Cipher
选项。
例如,将"RSA"
更改为"RSA/ECB/PKCS1Padding"
。并"AES"
到"AES/CBC/PKCS5Padding"
。或者任何适当的值。
原因:不同的加密提供程序具有不同的填充和模式默认值。如果您只是指定算法,则依赖于不同系统之间可能不兼容的默认值。