使用Phpseclib在Java中加密并在PHP中解密

编辑2:问题已经解决。 我不明白php中的loadkey函数应该如何工作,我错误地认为它会读取一个密钥文件(它没有)。 解决方案是将文件的内容读入变量,然后使用loadkey加载变量。

编辑:问题似乎与关键。 我意识到loadkey返回false,表明它无法读取密钥。 phpseclib接受的格式和java中创建的密钥有什么不同吗?


我试图加密Java(android)中的AES密钥并在PHP中解密它以使用对称加密进行数据传输。 目前,我能够使用Java中的RSA加密和解密短文件或字符串,但无法在PHP中解密它。

我使用phpseclib在PHP中解密,我没有得到任何错误,但我的输出字符串为空。

这是我正在使用的代码:

Java的:

File archivo_llave_publica = new File(direccion); byte[] bytes_llave = leer(archivo_llave_publica); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bytes_llave); PublicKey pubKey = keyFactory.generatePublic(publicKeySpec); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] cipherData = cipher.doFinal(src); return cipherData; 

PHP:

 setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); $rsa->loadKey('./key/Pri.txt'); // public key $temprsa = $rsa->decrypt($key); if ($temprsa==null){echo "null decrypt";} 

用于生成密钥的代码:

 public void generaArchivoLlaves(String pub_file, String pri_file){ File LlavePrivada = new File(raiz.getAbsolutePath()+"/Bushfire/"+pri_file); File LlavePublica = new File(raiz.getAbsolutePath()+"/Bushfire/"+pub_file); try { KeyPair kp = generaLlaves(); byte[] privateKeyBytes = kp.getPrivate().getEncoded(); byte[] publicKeyBytes = kp.getPublic().getEncoded(); Toast.makeText(this, "Privada: "+kp.getPrivate().getFormat(), Toast.LENGTH_LONG).show(); Toast.makeText(this, "Pública: "+kp.getPublic().getFormat(), Toast.LENGTH_LONG).show(); escribir(LlavePrivada, privateKeyBytes); escribir(LlavePublica, publicKeyBytes); } catch (NoSuchAlgorithmException e) {Toast.makeText(this, "Error al generar llave", Toast.LENGTH_LONG).show();} } public KeyPair generaLlaves() throws NoSuchAlgorithmException{ KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); KeyPair kp = kpg.genKeyPair(); //Toast.makeText(this, "Se generó correctamente", Toast.LENGTH_LONG).show(); return kp; 

}

注意 :函数escribir只是逐字节地将数据写入文件。

可能导致问题的原因是什么?