コード例 #1
0
        public async Task <string> Encrypt(string data, string serviceAccountId, bool createKeyIfMissing = true)
        {
            var safeId        = KeyIdCreator.Create(serviceAccountId);
            var keyring       = new KeyRingName(mProjectName, mKeyringLocation, mKeyringName);
            var cryptoKeyName =
                new CryptoKeyName(mProjectName, mKeyringLocation, mKeyringName, safeId);

            try
            {
                await mKmsService.GetCryptoKeyAsync(cryptoKeyName);
            } catch (RpcException e) when(e.StatusCode == StatusCode.NotFound && createKeyIfMissing)
            {
                var key = new CryptoKey
                {
                    Purpose         = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
                    VersionTemplate = new CryptoKeyVersionTemplate
                    {
                        ProtectionLevel = ProtectionLevel.Software
                    }
                };

                if (mRotationPeriod.HasValue)
                {
                    key.NextRotationTime = (DateTime.UtcNow + mRotationPeriod.Value).ToTimestamp();
                    key.RotationPeriod   = Duration.FromTimeSpan(mRotationPeriod.Value);
                }

                var request = await mKmsService.CreateCryptoKeyAsync(keyring, safeId, key);
            }

            var cryptoKeyPathName = new CryptoKeyPathName(mProjectName, mKeyringLocation, mKeyringName, safeId);
            var encryted          = await mKmsService.EncryptAsync(cryptoKeyPathName, ByteString.FromBase64(data));

            return(encryted.Ciphertext.ToBase64());
        }