我使用libnadium在客户端加密数据,在服务器端解密,反之亦然。
更确切地说,android端是lazyn钠,服务器端是libnadium的php包装器。
我能够正确地加密和解密从android到android,从php到php,但不能从android到php。
在服务器端,来自客户端的所有解密变量都是空的(解密后),不会抛出错误。
有谁能提供Android(Java)上正确加密和php上解密的例子,使用lazys钠和php wrapper for lib钠?
我的Android代码如下:
public String encrypt(Key privKey, Key serverPublicKey, String message, byte[] nonce) { // I use this function for every encryption
KeyPair keyPair = new KeyPair(privKey, serverPublicKey);
try {
return box.cryptoBoxEasy(message, nonce, keyPair); // box is instance of Box.Lazy class
} catch (SodiumException e) {
e.printStackTrace();
return null;
}
}
public byte[] randomNonce(){
return lazySodium.randomBytesBuf(SecretBox.NONCEBYTES); // lazySodium Is instance of LazySodiumAndroid class
}
public KeyPair generateKeyPair() {
try {
return box.cryptoBoxKeypair();
} catch (SodiumException e) {
e.printStackTrace();
return null;
}
}
以及php代码:
$nonce = sodium_hex2bin($nonce); // nonce is generated by client and send in hex
function register($name, $email, $pass, $public_key, $nonce)
{
echo $name." ".$email." ".$pass." ".$nonce." "; //only for debug
$nonce = sodium_hex2bin($nonce);
$client_to_server_kp = sodium_crypto_box_keypair_from_secretkey_and_publickey(sodium_hex2bin(KEY), sodium_hex2bin($public_key));
$name = sodium_crypto_box_open($name, $nonce, $client_to_server_kp);
$email = sodium_crypto_box_open($email, $nonce, $client_to_server_kp);
$pass = sodium_crypto_box_open($pass, $nonce, $client_to_server_kp);
// at this point these 3 variables are blank
if(empty($name) && empty($email) && empty($pass)){
return 1;
}
@$mysqli = mysqli_connect("localhost", "xxx", "xxx", "xxx");
if (@$stmt = $mysqli->prepare("INSERT INTO Users(email, name, password) VALUES (?,?,?)")) {
@$stmt->bind_param("sss", $email, $name, hash("SHA512", $pass));
@$stmt->execute();
$mysqli->close();
return $stmt->errno;
}
$mysqli->close();
}