我有下面的java函数,我想把它翻译成php
java函数:
private static final byte[] salt = {-44, -5, -88, 82, 116, -8, -64, -93};
private static void doCrypto(int cipherMode, char[] key, File inputFile, File outputFile) throws CryptoException {
try {
//Returns a SecretKeyFactory object that converts secret keys of the specified algorithm.
//get detail of 'PBKDF2WithHmacSHA256' (https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html)
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
//key specification
//Constructor that takes a password, salt, iteration count, and to-be-derived key length for
// generating PBEKey of variable-key-size PBE ciphers. An empty char[] is used if null is specified for password.
KeySpec spec = new PBEKeySpec(key, salt, 1000, 128);
//Generates a SecretKey object from the provided key specification (key material).
SecretKey tmp = factory.generateSecret(spec);
//provide a encoded secretKey with algorithm
secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
//Returns a Cipher object that implements the specified transformation.
cipher = Cipher.getInstance("AES") ;
cipher.init(cipherMode, secretKey);
FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
byte[] outputBytes = cipher.doFinal(inputBytes);
FileOutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);
inputStream.close();
outputStream.close();
} catch (Exception ex) {
throw new CryptoException("Error encrypting/decrypting file", ex);
}
}
下面是我翻译成的php函数
php函数
function doCrypto( $mode, $key, $inputFile, $oputputFile ){
$key = mb_convert_encoding($key, "UTF-8");
$salt = implode(array_map("chr", [ -44, -5, -88, 82, 116, -8, -64, -93 ] ));
$IVbytes = NULL;
$method = "AES-128-CBC";
$hash = openssl_pbkdf2( $key, $salt, '128', '1000', 'sha256' );
$data = file_get_contents( $inputFile );
if( 'enc' == $mode ){
$result = openssl_encrypt($data, $method, $hash, 1, $IVbytes);
} else {
$result = openssl_decrypt($data, $method, $hash, 1, $IVbytes);
}
if( !$result ){
throw new Exception( "Error encrypting/decrypting file : " . openssl_error_string() );
}
file_put_contents( $oputputFile, $result );
return true;
}
测试用例适用于php到php
但是当我收到来自java的加密文件时&试着用php解密
我一直有以下错误error:0607a082:数字信封routines:evp_cipher_ctx_set_key_length:密钥长度无效
我还尝试了用二进制模式的fopen读取文件
$handle = fopen($inputFile, "rb");
$contents = fread($handle, filesize($inputFile));
有人能指出我在这里遗漏了什么吗。
暂无答案!
目前还没有任何答案,快来回答吧!