Wednesday, 14 August 2019

Delete all key versions in Google KMS keyring

After some experiments with Google KMS I found that I have a few thousands keys created. Unfortunately there's no option in the google cloud console to destroy all keys in the key ring, the only thing possible to do is to "Disable all key versions" on each version by hand, which is not very exciting job to do with thousands of them. After short thinking I came out with the following simple java program which destroying all key versions in the keyring:


import java.util.concurrent.atomic.AtomicInteger;

public class CleanupKmsKeys {

private static final String KMS_PROJECT_ID = "my-development-project";

private static final String KMS_LOCATION = "global";

private static final String KMS_KEYRING = "encrypted-values";
// Destroy all key versions in {@link #KMS_KEYRING}
public static void
main(String[] args) { String keyRingName = KeyRingName.format(KMS_PROJECT_ID, KMS_LOCATION, KMS_KEYRING); warinig(keyRingName); AtomicInteger keyCount = new AtomicInteger(0); AtomicInteger keyVersionCount = new AtomicInteger(0); try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) { client.listCryptoKeys(keyRingName).iterateAll().forEach(cryptoKey -> { String name = cryptoKey.getName(); client.listCryptoKeyVersions(name).iterateAll().forEach(cryptKeyVer -> { if ( !cryptKeyVer.hasDestroyTime() && !cryptKeyVer.hasDestroyEventTime() ) { String cryptoKeyVersionName = cryptKeyVer.getName(); client.destroyCryptoKeyVersion(cryptoKeyVersionName); System.out.println(String.format( "Destroyed version %s of key %s", name, cryptoKey )); keyVersionCount.getAndIncrement(); } }); keyCount.getAndIncrement(); }); System.out.println(String.format( "Deleted %d keys and %d versions", keyCount.get(), keyVersionCount.get() )); } catch (IOException e) { System.out.println(String.format( "Failed to delete all versions, deleted %d keys and %d versions", keyCount.get(), keyVersionCount.get() )); throw new RuntimeException("Failed to destroy KMS keys"); } } private static void warinig(String keyRingName) { try { System.out.println(String.format( "I'm going to destroy all keys in %s", keyRingName )); Thread.sleep(1000); System.out.println("In 3 seconds"); Thread.sleep(1000); System.out.println("In 2 seconds"); Thread.sleep(1000); System.out.println("In 1 second"); Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException("Something went wrong"); } } }

No comments:

Post a Comment