tink-crypto / tink

Tink is a multi-language, cross-platform, open source library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse.
https://developers.google.com/tink
Apache License 2.0
13.47k stars 1.18k forks source link

tink python process to read kms encrypted keyset. #597

Closed Rudranand closed 2 years ago

Rudranand commented 2 years ago

I am using kms to generate digital signature private keyset using tinkey. How I can read that keyset to sign the data. I have done that in java in this way

KeysetHandle handle = KeysetHandle.generateNew(KmsAeadKeyManager.createKeyTemplate(KEY_URI));
Aead kekAead = handle.getPrimitive(Aead.class);
KeysetHandle signaturePrivateKeyHandle = KeysetHandle
.read(JsonKeysetReader.withFile(new File(SIGN_PRIVATE_KEYSET_PATH)), kekAead);
PublicKeySign signer = signaturePrivateKeyHandle.getPrimitive(PublicKeySign.class);

I was try to do this in python in this way

    handle = tink.KeysetHandle.generate_new(
    aead.aead_key_templates.create_kms_aead_key_template(
            key_uri=KEY_URI))
    kekAead = handle.primitive(aead.Aead)
    with open(SIGN_PRIVATE_KEYSET_PATH_V2, 'r') as f:
      json_private_sign = f.read()
    reader = tink.JsonKeysetReader(json_private_sign)
    keyset_handle = tink.read_keyset_handle(reader, kekAead)
    signer = keyset_handle.primitive(signature.PublicKeySign)
    sig = signer.sign(ciphertext)

it's throwing error 2022-04-13 14:34:29,369 [Thread-10 ] [ERROR] ('Decryption failed.',) ERROR:root:Decryption failed. 2022-04-13 14:34:29,370 [Thread-10 ] [ERROR] Decryption failed.

morambro commented 2 years ago

Hi @Rudranand, in principle, I don't see anything wrong with the code snippet you provided. Without any more context I am not sure I can help. What I can suggest is trying to use https://github.com/google/tink/tree/master/examples/python/encrypted_keyset to decrypt the keyset (it assumes a different primitive, but the decryption step should work assuming you are using Cloud KMS).

Note: I noticed the Python example uses a constant named SIGN_PRIVATE_KEYSET_PATH_V2 while the Java example SIGN_PRIVATE_KEYSET_PATH.

Rudranand commented 2 years ago

Hi @morambro, thanks for the reply, I have resolved the error it was related to the root.pem.