我正在尝试使用 SymmetricKey 解密有效负载。我已经尝试使用 ChaChaPoly 和 AES.GCM 打开sealedBox,但我仍然得到CryptoKit.CryptoKitError.authenticationFailure 这是我的实现:
let iv: [UInt8] = [0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F]
func generatePair() {
let priv = P256.KeyAgreement.PrivateKey()
privateKey = priv
publicKey = priv.publicKey
}
func createSymmetricKey(serverPublicKeyPEM: String) -> SymmetricKey? {
guard let privateKey = privateKey,
let publicKey = publicKey else { return nil }
do {
let serverPubKey = try P256.KeyAgreement.PublicKey(pemRepresentation: serverPublicKeyPEM)
let shared = try privateKey.sharedSecretFromKeyAgreement(with: serverPubKey)
let symetricKey = shared.hkdfDerivedSymmetricKey(using: SHA256.self,
salt: Data(bytes: iv, count: iv.count),
sharedInfo: publicKey.rawRepresentation + serverPubKey.rawRepresentation,
outputByteCount: 32)
return symetricKey
} catch {
//TODO: Handle Error
print("error \(error)")
return nil
}
}
func decrypt(payload: String, symmetricKey: SymmetricKey) {
guard let cipherText = Data(base64Encoded: payload) else { return }
do {
// let sealedBox = try ChaChaPoly.SealedBox(combined: cipherText)
// let decrypted = try ChaChaPoly.open(sealedBox, using: symmetricKey)
let sb = try AES.GCM.SealedBox(combined: cipherText)
let decrypted = try AES.GCM.open(sb, using: symmetricKey)
print("")
} catch {
print("error: \(error)") //here getting CryptoKit.CryptoKitError.authenticationFailure
}
}
我也知道后端的实现是怎样的:
public static String encrypt(String sessionKey, String devicePublicKey, String plainString) throws Exception {
byte[] plain = Base64.getEncoder().encodeToString(plainString.getBytes(StandardCharsets.UTF_8)).getBytes();
SecretKey key = generateSharedSecret(decodePrivateKey(sessionKey), decodePublicKey( devicePublicKey));
Cipher encryptor = Cipher.getInstance("AES/CTR/NoPadding", BouncyCastleProvider.PROVIDER_NAME);
IvParameterSpec ivSpec = new IvParameterSpec(INITIALIZATION_VECTOR);
encryptor.init(Cipher.ENCRYPT_MODE, key, ivSpec);
return Base64.getEncoder().encodeToString(encryptor.doFinal(plain, 0, plain.length));
}