问题
Edit 2: Problem has been solved. I didn't understand how the loadkey function in php was supposed to work and I mistakenly assumed it would read a key file (it does not). The solution was to read the contents of the file into a variable and then load the variable with loadkey.
Edit: The problem seems to be with the key. I realized that loadkey is returning false, indicating that it was unable to read the key. Could there be a difference in the formats accepted by phpseclib and the keys created in java?
I am trying to encrypt a AES key in Java (android) and decrypt it in PHP to use symmetric encryption for data transfer. Currently, I am able to encrypt and decrypt a short file or string using RSA in Java, but have not been able to decrypt it in PHP.
I am using phpseclib to decrypt in PHP, and i dont get any error, but my output string is null.
This is the code I am using:
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:
<?php
include('./Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->loadKey('./key/Pri.txt'); // public key
$temprsa = $rsa->decrypt($key);
if ($temprsa==null){echo "null decrypt";}
Code used to generate keys:
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;
}
NOTE: Function escribir just writes the data byte by byte to a file.
What could be causing the problem?
来源:https://stackoverflow.com/questions/13506077/encrypting-in-java-and-decrypting-in-php-with-phpseclib