我已经能够使用该算法来加密和解密文件,但是当我尝试从Android向WAS服务器发送文件时,它失败。这里是加密侧RSA AES解密失败 - InvalidKeyException
Security.addProvider(new BouncyCastleProvider());
KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
keygen.init(random);
SecretKey key = keygen.generateKey();
// wrap with RSA public key
ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream (getFileLocation(PUBLIC_KEY, localTest)));
Key publicKey = (Key) keyIn.readObject();
keyIn.close();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.WRAP_MODE, publicKey);
byte[] wrappedKey = cipher.wrap(key);
DataOutputStream out = new DataOutputStream(new FileOutputStream(getFileLocation(SIGN_FILE, localTest)));
out.writeInt(wrappedKey.length);
out.write(wrappedKey);
InputStream in = new ByteArrayInputStream(message.getBytes());
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
crypt(in, out, cipher);
in.close();
out.close();
FileInputStream fis = new FileInputStream(getFileLocation(SIGN_FILE, localTest));
byte[] buffer = new byte[fis.available()];
int i =0;
while (i< buffer.length){
buffer[i]= (byte)fis.read();
i++;
}
String ss = encodeMsg(buffer);
return ss;
这里是解密侧
Security.addProvider(new BouncyCastleProvider());
byte[] arr = decodeMsg(encrypted);
DataInputStream in = new DataInputStream(new ByteArrayInputStream(arr));
int length = in.readInt();
byte[] wrappedKey = new byte[length];
in.read(wrappedKey, 0, length);
// unwrap with RSA private key
ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream (getFileLocation(PRIVATE_KEY, localTest)));
Key privateKey = (Key) keyIn.readObject();
keyIn.close();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.UNWRAP_MODE, privateKey);
Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
OutputStream out = new FileOutputStream(getFileLocation(DECRYPTED, localTest));
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
crypt(in, out, cipher);
in.close();
out.close();
FileInputStream fis = new FileInputStream(getFileLocation(DECRYPTED, localTest));
byte[] buffer = new byte[fis.available()];
int i =0;
while (i< buffer.length){//!= 0) {
buffer[i]= (byte)fis.read();
i++;
}
String ss = new String(buffer);
return ss;
同样,我的工作站上,这个工程。当对WAS Web服务器进行移动请求时,它失败。起初,它与对象类争论,所以我使用Java 1.6重新创建了密钥。我也将这场战争重新编译为Java 1.6。它的错误如下。
--cipher解开
java.security.InvalidKeyException com.ibm.crypto.provider.RSA.engineUnwrap(Unknown Source)
javax.crypto.Cipher.unwrap(Unknown Source)
com.webapp.web.security.RSAEncrypt.decrypt(RSAEncrypt.java:161)
com.webapp.web.MobileRequest.doPost(MobileRequest.java:81)
javax.servlet.http.HttpServlet.service(HttpServlet.java:738)
javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
...
是否WAS环境已经被更新来处理呢?想法? 更新密钥大小设置为2048
我不知道这是不是问题,但要摆脱* all *默认值并用明确的值替换它们。不要使用getInstance(“RSA”)'getInstance(“RSA/ECB/PKCS1PADDING”)'。不要使用'getBytes()'使用'getBytes(“UTF-8”)'。 –