identity = $identity; } public function generate_keys(){ $keyPairSign = sodium_crypto_sign_keypair(); $this->privKeySign = sodium_crypto_sign_secretkey( $keyPairSign ); $this->pubKeySign = sodium_crypto_sign_publickey( $keyPairSign ); $keyPairBox = sodium_crypto_box_keypair(); $this->privKeyCrypt = sodium_crypto_box_secretkey( $keyPairBox ); $this->pubKeyCrypt = sodium_crypto_box_publickey( $keyPairBox ); } public function get_local_pubkey( $keyType = NULL ){ if ( $keyType === 1 ){ return $this->pubKeySign; } if ( $keyType === 2 ){ return $this->pubKeyCrypt; } return $this->pubKeySign . $this->pubKeyCrypt; } public function generate_signature( $data ){ $this->lastError = ''; $data = str_replace( ["\r\n", "\r"], "\n", trim( $data ) ); $signature = sodium_crypto_sign_detached( $data, $this->privKeySign ); return base64_encode( $signature ); } public function verify_signature( $signature, $data, $pubKey = NULL ){ $this->lastError = ''; $signature = base64_decode( $signature ); if ( strlen( $signature ) != SODIUM_CRYPTO_SIGN_BYTES ){ $this->lastError = 'Invalid signature string'; return FALSE; } $pubKey = $pubKey ?? $this->pubKeySign; if ( strlen( $pubKey ) != SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES ){ $this->lastError = 'Invalid public key string'; return FALSE; } $result = sodium_crypto_sign_verify_detached( $signature, $data, $pubKey ); return $result == 1; } public function generate_hash( $data ){ $this->lastError = ''; $hash = hash( 'sha256', $data . $this->privKeySign ); return base64_encode( $hash ); } public function encrypt( $data, $pubKey = NULL ){ $this->lastError = ''; $pubKey = $pubKey ?? $this->pubKeyCrypt; $iv = openssl_random_pseudo_bytes( 16 ); $secret = sodium_crypto_scalarmult( $this->privKeyCrypt, $pubKey ); $encrypted = openssl_encrypt( $data, 'aes-256-ctr', $secret, 0, $iv ); return base64_encode( $iv ) . ':' . $encrypted; } public function decrypt( $data, $pubKey = NULL ){ $this->lastError = ''; $pubKey = $pubKey ?? $this->pubKeyCrypt; list( $iv, $encrypted ) = explode( ':', $data ) + [ '', '' ]; $iv = base64_decode( $iv ); if ( ! $iv || strlen( $iv ) != 16 ){ $this->lastError = 'ERROR: Missing or invalid initialization vector'; return FALSE; } $secret = sodium_crypto_scalarmult( $this->privKeyCrypt, $pubKey ); $decrypted = openssl_decrypt( $encrypted, 'aes-256-ctr', $secret, 0, $iv ); return $decrypted; } } // end of file crypto.class.php