Articles → AWS SDK AND CSHARP → Rotate The AWS Secret Key Using C#

Rotate The AWS Secret Key Using C#






Create A Secret Key




Picture showing the secret key created in AWS console
Click to Enlarge


Rotate The AWS Key Using The C# Code




using Amazon.Runtime;
using Amazon.SecretsManager;
using Amazon.SecretsManager.Model;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;


namespace AWSSecretKeyRotation
{
    class Program
    {
        static void Main(string[] args)
        {
            Program.RotateKey();
        }

        public static void RotateKey()
        {
            string secretName = "APIKey";

            try
            {
                AWSCredentials credentials = new BasicAWSCredentials("ACCESS_KEY", "SECRET_ACCESS_KEY");

                var client = new AmazonSecretsManagerClient(credentials);

                // Get the current secret value
                var getSecretValueRequest = new GetSecretValueRequest { SecretId = secretName };
                var getSecretValueResponse = client.GetSecretValue(getSecretValueRequest);

                string currentSecretValue = getSecretValueResponse.SecretString;

                Console.Write(string.Format("Current Key Value:{0}", currentSecretValue));
                //Console.Write("Press any key to continue");
                Console.ReadLine();

                // Generate a new secret value
                string newSecretValue = GenerateRandomString();

                // Update the secret with the new value
                var putSecretValueRequest = new PutSecretValueRequest
                {
                    SecretId = secretName,
                    SecretString = newSecretValue,
                    VersionStages = new List<string>() { "AWSCURRENT" }
                };

                var putSecretValueResponse = client.PutSecretValue(putSecretValueRequest);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
            Console.WriteLine("Secret rotation completed successfully!");
            Console.ReadLine();
        }

        public static string GenerateRandomString()
        {
            // create an instance of the RNGCryptoServiceProvider class
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            // create a byte array to hold the random data
            byte[] data = new byte[2];

            // fill the byte array with random data
            rng.GetBytes(data);

            // convert the byte array to a 5-digit string
            string key = (BitConverter.ToUInt16(data, 0) % 100000).ToString("D5");



            return key;
        }
    }
}



Output


Picture showing the key got rotated using C# code
Click to Enlarge




Posted By  -  Karan Gupta
 
Posted On  -  Saturday, May 27, 2023

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250