0

我在客户端使用 Swift Sodium,因为我的服务器在通过 API 与我共享数据之前使用 libsodium 加密数据。

现在我有一个现有的私钥和一个字符串格式的公钥。我现在想在 iOS 上使用 Swift 解密加密数据。

如何使用我拥有的公钥和私钥生成 Sodium Key Pair?

另外理想情况下,我应该只使用私钥来解密数据。那么我如何只使用私钥作为字符串来做到这一点。

我的解密代码如下所示 -

func decryptData(dataString: String) -> String? {
    let sodium = Sodium()
    let privateKey = sodium?.utils.hex2bin("MY_SECRET_KEY")

    let publicKey = sodium?.utils.hex2bin("MY_PUBLIC_KEY")

    let message = dataString.data(using: .utf8)!

    if let decrypted = sodium?.box.open(anonymousCipherText: message, recipientPublicKey: publicKey!, recipientSecretKey: privateKey!){
        // authenticator is valid, decrypted contains the original message
        return String(data: decrypted, encoding: String.Encoding.utf8) as String!
    }
    return nil
}

在上面的代码中,我解密的字符串总是空的。

服务器正在使用以下功能加密数据 -

protected function crypt($response)
{
   $message = new HiddenString($response);

   $repository = \App::make(EncryptionKeysRepository::class);
   $enc = $repository->findOneBy(['device' => 'android']);
   $dir = $enc->getDevice();
   $publicKey = $enc->getPublicKey();
   $storage = storage_path();

   if(!file_exists($storage."/{$dir}/")) {
       mkdir($storage."/{$dir}/");
   }

   // save key pair to key store
   $pubFilename = \tempnam($storage."/{$dir}/", 'pub_key');
   file_put_contents($pubFilename, $publicKey);

   $public = KeyFactory::loadEncryptionPublicKey($pubFilename);
   unlink($pubFilename);
   rmdir($storage."/{$dir}/");
   $message = Crypto::seal($message, $public);

   return $message;
}

在服务器解密逻辑

protected function deCrypt($response)
{
   $repository = \App::make(EncryptionKeysRepository::class);
   $enc = $repository->findOneBy(['device' => 'android']);
   $dir = $enc->getDevice();
   $publicKey = $enc->getSecretKey();
   $storage = storage_path();

   if(!file_exists($storage."/{$dir}/")) {
       mkdir($storage."/{$dir}/");
   }

   // save key pair to key store
   $secFilename = \tempnam($storage."/{$dir}/", 'sec_key');
   file_put_contents($secFilename, $publicKey);

   $secret = KeyFactory::loadEncryptionSecretKey($secFilename);
   unlink($secFilename);
   rmdir($storage."/{$dir}/");
   $res = Crypto::unseal($response, $secret);

   $message = $res->getString();

   return response()->json(compact('message'));
}
4

1 回答 1

0

因此,在服务器端,您显然在使用 PHP,并带有一个名为 Halite 的库。

我对 Halite 不是很熟悉,但是看看它的代码,Crypto::seal()使用密封的盒子,所以Box::open(anonymousCipherText: Data, recipientPublicKey: PublicKey, recipientSecretKey: SecretKey) -> Data?在 Swift 中解密它的正确方法是。

但是,Halite 似乎也将结果编码为 BASE64 字符串(urlsafe 变体)。

因此,您需要先对此进行解码。或者,这将更有效,不要对密文进行编码。除非您必须大声朗读它们,否则密钥可能也不需要编码。

于 2017-09-20T08:39:25.260 回答