public bool VerifyAsymmetricSignatureRsa(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123",
        string message   = "my message",
        byte[] signature = null)
    {
        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Calculate the digest of the message.
        SHA256 sha256 = SHA256.Create();

        byte[] digest = sha256.ComputeHash(Encoding.UTF8.GetBytes(message));

        // Get the public key.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();
        PublicKey publicKey = client.GetPublicKey(keyVersionName);

        // Split the key into blocks and base64-decode the PEM parts.
        string[] blocks = publicKey.Pem.Split("-", StringSplitOptions.RemoveEmptyEntries);
        byte[]   pem    = Convert.FromBase64String(blocks[1]);

        // Create a new RSA key.
        RSA rsa = RSA.Create();

        rsa.ImportSubjectPublicKeyInfo(pem, out _);

        // Verify the signature.
        bool verified = rsa.VerifyHash(digest, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);

        // Return the result.
        return(verified);
    }
Пример #2
0
        /// <summary>
        /// Creates a new instance of <see cref="AuthenticodeKeyVaultSigner" />.
        /// </summary>
        /// <param name="signingAlgorithm">
        /// An instance of an asymmetric algorithm that will be used to sign. It must support signing with
        /// a private key.
        /// </param>
        /// <param name="signingCertificate">The X509 public certificate for the <paramref name="signingAlgorithm"/>.</param>
        /// <param name="timeStampConfiguration">The timestamp configuration for timestamping the file. To omit timestamping,
        /// use <see cref="TimeStampConfiguration.None"/>.</param>
        /// <param name="additionalCertificates">Any additional certificates to assist in building a certificate chain.</param>
        public AuthenticodeKeyVaultSigner(KeyManagementServiceClient client, CryptoKeyVersionName ckvn,
                                          TimeStampConfiguration timeStampConfiguration,
                                          X509Certificate2Collection additionalCertificates = null)
        {
            _client                 = client;
            _ckvn                   = ckvn;
            _signingCertificate     = additionalCertificates[0];
            _timeStampConfiguration = timeStampConfiguration ?? throw new ArgumentNullException(nameof(timeStampConfiguration));
            _signingAlgorithm       = _signingCertificate.SignatureAlgorithm.FriendlyName.Substring(0, 6).ToUpper();
            _certificateStore       = MemoryCertificateStore.Create();
            _chain                  = new X509Chain();
            if (additionalCertificates != null)
            {
                _chain.ChainPolicy.ExtraStore.AddRange(additionalCertificates);
            }
            //We don't care about the trustworthiness of the cert. We just want a chain to sign with.
            _chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;


            if (!_chain.Build(_signingCertificate))
            {
                throw new InvalidOperationException("Failed to build chain for certificate.");
            }
            for (var i = 0; i < _chain.ChainElements.Count; i++)
            {
                if (!_chain.ChainElements[i].Certificate.SubjectName.Equals(_chain.ChainElements[i].Certificate.IssuerName))
                {
                    _certificateStore.Add(_chain.ChainElements[i].Certificate);
                }
            }
            _signCallback = SignCallback;
        }
    public byte[] SignMac(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123",
        string data      = "Sample data")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Convert the data into a ByteString.
        ByteString dataByteString = ByteString.CopyFromUtf8(data);

        // Call the API.
        MacSignResponse result = client.MacSign(keyVersionName, dataByteString);

        // The data comes back as raw bytes, which may include non-printable
        // characters. To print the result, you could encode it as base64.
        // string encodedSignature = result.Mac.ToBase64();

        // Get the signature.
        byte[] signature = result.Mac.ToByteArray();

        // Return the result.
        return(signature);
    }
Пример #4
0
    public void DecryptsDataa()
    {
        var plaintext = "testing1234";

        // Get the public key.
        KeyManagementServiceClient client         = KeyManagementServiceClient.Create();
        CryptoKeyVersionName       keyVersionName = new CryptoKeyVersionName(_fixture.ProjectId, _fixture.LocationId, _fixture.KeyRingId, _fixture.AsymmetricDecryptKeyId, "1");
        var publicKey = client.GetPublicKey(keyVersionName);

        // Split the key into blocks and base64-decode the PEM parts.
        var blocks = publicKey.Pem.Split("-", StringSplitOptions.RemoveEmptyEntries);
        var pem    = Convert.FromBase64String(blocks[1]);

        // Create a new RSA key.
        var rsa = RSA.Create();

        rsa.ImportSubjectPublicKeyInfo(pem, out _);

        // Encrypt the data.
        var ciphertext = rsa.Encrypt(Encoding.UTF8.GetBytes(plaintext), RSAEncryptionPadding.OaepSHA256);

        // Run the sample code.
        var result = _sample.DecryptAsymmetric(
            projectId: _fixture.ProjectId, locationId: _fixture.LocationId, keyRingId: _fixture.KeyRingId, keyId: _fixture.AsymmetricDecryptKeyId, keyVersionId: "1",
            ciphertext: ciphertext);

        Assert.Equal(plaintext, result);
    }
    public byte[] EncryptAsymmetric(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123",
        string message   = "Sample message")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Get the public key.
        PublicKey publicKey = client.GetPublicKey(keyVersionName);

        // Split the key into blocks and base64-decode the PEM parts.
        string[] blocks = publicKey.Pem.Split("-", StringSplitOptions.RemoveEmptyEntries);
        byte[]   pem    = Convert.FromBase64String(blocks[1]);

        // Create a new RSA key.
        RSA rsa = RSA.Create();

        rsa.ImportSubjectPublicKeyInfo(pem, out _);

        // Convert the message into bytes. Cryptographic plaintexts and
        // ciphertexts are always byte arrays.
        byte[] plaintext = Encoding.UTF8.GetBytes(message);

        // Encrypt the data.
        byte[] ciphertext = rsa.Encrypt(plaintext, RSAEncryptionPadding.OaepSHA256);
        return(ciphertext);
    }
    public void EncryptsData()
    {
        var message = "testing1234";

        // Run the sample code.
        var signature = _sample.SignAsymmetric(
            projectId: _fixture.ProjectId, locationId: _fixture.LocationId, keyRingId: _fixture.KeyRingId, keyId: _fixture.AsymmetricSignRsaKeyId, keyVersionId: "1",
            message: message);

        // Calculate the hash of the message.
        var sha256 = SHA256.Create();
        var digest = sha256.ComputeHash(Encoding.UTF8.GetBytes(message));

        // Get the public key.
        KeyManagementServiceClient client         = KeyManagementServiceClient.Create();
        CryptoKeyVersionName       keyVersionName = new CryptoKeyVersionName(_fixture.ProjectId, _fixture.LocationId, _fixture.KeyRingId, _fixture.AsymmetricSignRsaKeyId, "1");
        var publicKey = client.GetPublicKey(keyVersionName);

        // Split the key into blocks and base64-decode the PEM parts.
        var blocks = publicKey.Pem.Split("-", StringSplitOptions.RemoveEmptyEntries);
        var pem    = Convert.FromBase64String(blocks[1]);

        // Create a new RSA key.
        var rsa = RSA.Create();

        rsa.ImportSubjectPublicKeyInfo(pem, out _);

        var verified = rsa.VerifyHash(digest, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);

        Assert.True(verified);
    }
        // [END kms_destroy_cryptokey_version]

        // [START kms_restore_cryptokey_version]
        public static void RestoreCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string versionId)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();

            // The CryptoKeyVersion to restore.
            CryptoKeyVersionName versionName =
                new CryptoKeyVersionName(projectId, locationId, keyRingId, cryptoKeyId, versionId);

            CryptoKeyVersion result = client.RestoreCryptoKeyVersion(versionName);

            Console.Write($"Restored Crypto Key Version: {result.Name}");
        }
Пример #8
0
        public override EncryptResponse Encrypt(EncryptRequest request, CallSettings callSettings = null)
        {
            var  key            = request.CryptoKeyPathName;
            var  keyVersionName = new CryptoKeyVersionName(key.ProjectId, key.LocationId, key.KeyRingId, key.CryptoKeyPathId, "1");
            byte xorOperand     = (byte)request.Name.GetHashCode();

            return(new EncryptResponse
            {
                Ciphertext = ByteString.CopyFrom(request.Plaintext.Select(x => (byte)(x ^ xorOperand)).Select(x => (byte)(x + 1)).ToArray()),
                Name = keyVersionName.ToString()
            });
        }
    public CryptoKeyVersion RestoreKeyVersion(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version name.
        CryptoKeyVersionName cryptoKeyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Call the API.
        CryptoKeyVersion result = client.RestoreCryptoKeyVersion(cryptoKeyVersionName);

        // Return the result.
        return(result);
    }
Пример #10
0
    public PublicKey GetPublicKey(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Call the API.
        PublicKey result = client.GetPublicKey(keyVersionName);

        // Return the ciphertext.
        return(result);
    }
Пример #11
0
        // [END kms_enable_cryptokey_version]

        // [START kms_get_cryptokey_version]
        public static void GetCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string versionId)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();

            // The CryptoKeyVersion to enable.
            CryptoKeyVersionName versionName =
                new CryptoKeyVersionName(projectId, locationId, keyRingId, cryptoKeyId, versionId);

            CryptoKeyVersion result = client.GetCryptoKeyVersion(versionName);

            Console.WriteLine($"Name: {result.Name}");
            Console.WriteLine($"Created: {result.CreateTime}");
            Console.WriteLine($"State: {result.State}");
        }
Пример #12
0
    public void EncryptsData()
    {
        var data = "testing1234";

        // Create the signature.
        KeyManagementServiceClient client         = KeyManagementServiceClient.Create();
        CryptoKeyVersionName       keyVersionName = new CryptoKeyVersionName(_fixture.ProjectId, _fixture.LocationId, _fixture.KeyRingId, _fixture.MacKeyId, "1");
        MacSignResponse            result         = client.MacSign(keyVersionName, ByteString.CopyFromUtf8(data));

        // Run the sample code.
        var success = _sample.VerifyMac(
            projectId: _fixture.ProjectId, locationId: _fixture.LocationId, keyRingId: _fixture.KeyRingId, keyId: _fixture.MacKeyId, keyVersionId: "1",
            data: data, signature: result.Mac.ToByteArray());

        Assert.True(success);
    }
    public void EncryptsData()
    {
        var message = "testing1234";

        // Run the sample code.
        var ciphertext = _sample.EncryptAsymmetric(
            projectId: _fixture.ProjectId, locationId: _fixture.LocationId, keyRingId: _fixture.KeyRingId, keyId: _fixture.AsymmetricDecryptKeyId, keyVersionId: "1",
            message: message);

        // Decrypt result.
        KeyManagementServiceClient client         = KeyManagementServiceClient.Create();
        CryptoKeyVersionName       keyVersionName = new CryptoKeyVersionName(_fixture.ProjectId, _fixture.LocationId, _fixture.KeyRingId, _fixture.AsymmetricDecryptKeyId, "1");
        var result = client.AsymmetricDecrypt(keyVersionName, ByteString.CopyFrom(ciphertext));

        Assert.Equal(message, result.Plaintext.ToStringUtf8());
    }
Пример #14
0
        // [END kms_disable_cryptokey_version]

        // [START kms_enable_cryptokey_version]
        public static void EnableCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string versionId)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();

            // The CryptoKeyVersion to enable.
            CryptoKeyVersionName versionName =
                new CryptoKeyVersionName(projectId, locationId, keyRingId, cryptoKeyId, versionId);

            CryptoKeyVersion version = client.GetCryptoKeyVersion(versionName);

            version.State = CryptoKeyVersion.Types.CryptoKeyVersionState.Enabled;
            FieldMask fieldMask = new FieldMask();

            fieldMask.Paths.Add("state");

            CryptoKeyVersion patchResult = client.UpdateCryptoKeyVersion(version, fieldMask);

            Console.Write($"Enabled Crypto Key Version: {patchResult.Name}");
        }
Пример #15
0
    public string DecryptAsymmetric(
        string projectId  = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123",
        byte[] ciphertext = null)
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Call the API.
        AsymmetricDecryptResponse result = client.AsymmetricDecrypt(keyVersionName, ByteString.CopyFrom(ciphertext));

        // Get the plaintext. Cryptographic plaintexts and ciphertexts are
        // always byte arrays.
        byte[] plaintext = result.Plaintext.ToByteArray();

        // Return the result.
        return(Encoding.UTF8.GetString(plaintext));
    }
Пример #16
0
    public bool VerifyMac(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123",
        string data      = "my data",
        byte[] signature = null)
    {
        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Convert the data and signatures into ByteStrings.
        ByteString dataByteString      = ByteString.CopyFromUtf8(data);
        ByteString signatureByteString = ByteString.CopyFrom(signature);

        // Verify the signature.
        MacVerifyResponse result = client.MacVerify(keyVersionName, dataByteString, signatureByteString);

        // Return the result.
        return(result.Success);
    }
Пример #17
0
    public byte[] SignAsymmetric(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123",
        string message   = "Sample message")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key version name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Convert the message into bytes. Cryptographic plaintexts and
        // ciphertexts are always byte arrays.
        byte[] plaintext = Encoding.UTF8.GetBytes(message);

        // Calculate the digest.
        SHA256 sha256 = SHA256.Create();

        byte[] hash = sha256.ComputeHash(plaintext);

        // Build the digest.
        //
        // Note: Key algorithms will require a varying hash function. For
        // example, EC_SIGN_P384_SHA384 requires SHA-384.
        Digest digest = new Digest
        {
            Sha256 = ByteString.CopyFrom(hash),
        };

        // Call the API.
        AsymmetricSignResponse result = client.AsymmetricSign(keyVersionName, digest);

        // Get the signature.
        byte[] signature = result.Signature.ToByteArray();

        // Return the result.
        return(signature);
    }
Пример #18
0
    public void VerifiesData()
    {
        var message = "testing1234";

        // Calculate the message digest.
        var sha256 = SHA256.Create();
        var digest = sha256.ComputeHash(Encoding.UTF8.GetBytes(message));

        // Sign the data
        KeyManagementServiceClient client         = KeyManagementServiceClient.Create();
        CryptoKeyVersionName       keyVersionName = new CryptoKeyVersionName(_fixture.ProjectId, _fixture.LocationId, _fixture.KeyRingId, _fixture.AsymmetricSignRsaKeyId, "1");
        var result = client.AsymmetricSign(keyVersionName, new Digest
        {
            Sha256 = ByteString.CopyFrom(digest),
        });

        // Run the sample.
        var verified = _sample.VerifyAsymmetricSignatureRsa(
            projectId: _fixture.ProjectId, locationId: _fixture.LocationId, keyRingId: _fixture.KeyRingId, keyId: _fixture.AsymmetricSignRsaKeyId, keyVersionId: "1",
            message: message,
            signature: result.Signature.ToByteArray());

        Assert.True(verified);
    }
Пример #19
0
    public byte[] GetKeyVersionAttestation(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key name.
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId);

        // Call the API.
        CryptoKeyVersion result = client.GetCryptoKeyVersion(keyVersionName);

        // Only HSM keys have an attestation. For other key types, the attestion
        // will be nil.
        KeyOperationAttestation attestation = result.Attestation;

        if (attestation == null)
        {
            throw new InvalidOperationException("no attestation");
        }

        // Return the attestation.
        return(attestation.Content.ToByteArray());
    }