-1

I am trying to encrypt value using swift sodium with given public key. However, the encrypted value is not the same as what's produced on server side. I am not sure whether this piece of coding is right in swift. The steps are similar to how its done in java.

Assume public key is in base64 string format.

Java:

String pubKey = "w6mjd11n9w9ncKfcuR888Ygi02ou+46ocIajlcUEmQ="; 
String secret = "hithere"
byte[] pubKeyBytes = Base64.decode(pubKey,0);
SealedBox sealedDeal = new SealedBox(pubKeyBytes);
byte[] c = sealedDeal.encrypt(secret.getBytes());
String ciphertext = Base64.encodeToString(c, 0);  

Swift:

let pubKey = "w6mjd11n9w9ncKfcuR888Ygi02ou+46ocIajlcUEmQ="
let dataDecoded:NSData = NSData(base64Encoded: pubKey, options: NSData.Base64DecodingOptions(rawValue: 0))!
let secret = "hithere".toData()!
let c : Data = sodium.box.seal(message: secret, recipientPublicKey: dataDecoded as Box.PublicKey)!
let ciphertext = c.base64EncodedString(options: .init(rawValue: 0))

Please tell me know what's wrong with the swift equivalent coding. Thanks alot.

shiva
  • 13
  • 4

2 Answers2

0

The encrypted value is supposed to be different, so that ciphertexts resulting from equivalent plaintexts are indistinguishable (see Ciphertext indistinguishability).

Max
  • 1,387
  • 1
  • 15
  • 29
0

sodium.box.seal internally generates new nonce every time you are encrypting message, @Max is right, this is normal behave

You can use Detached mode to give same nonce, but this is a very bad idea

In your example you have used Anonymous Encryption I suggest you to take a look at Authenticated Encryption