diff --git a/docs/using-the-jdbc-driver/using-plugins/UsingTheKmsEncryptionPlugin.md b/docs/using-the-jdbc-driver/using-plugins/UsingTheKmsEncryptionPlugin.md
index 75fee5f1b..f6272dadd 100644
--- a/docs/using-the-jdbc-driver/using-plugins/UsingTheKmsEncryptionPlugin.md
+++ b/docs/using-the-jdbc-driver/using-plugins/UsingTheKmsEncryptionPlugin.md
@@ -927,6 +927,26 @@ On MySQL the triggers and routines run with the privileges of their `DEFINER`, w
 
 Verify the separation by connecting as the runtime role and confirming that `INSERT INTO encrypt.key_storage ...` and `UPDATE encrypt.encryption_metadata ...` fail with a permission error, that `DROP TABLE encrypt.key_storage` and `DROP TRIGGER` on an encrypted table fail, and that `aws kms generate-data-key` with the runtime credentials is denied.
 
+### What the plugin keeps out of logs and exceptions
+
+The plugin masks master keys, KMS error text and URL credentials in its own log records, audit log entries and exception messages, at every log level:
+
+- **Master keys.** A key is shown as `arn:aws:kms:***:***:key/<first 4>***<last 4>`, whether it was configured as an ARN, `key/<id>` or a bare key id, and a key id is masked the same way everywhere it appears. A key id of 8 characters or fewer is shown as `***`. An alias is shown as `arn:aws:kms:***:***:alias/***`, and any other ARN, such as a role, as `arn:***`. This covers the allow-list in `encryptionAllowedMasterKeyArns` when the plugin logs it.
+- **KMS errors.** An error returned by KMS is logged and wrapped as its type, error code and HTTP status only, for example `KmsException[errorCode=AccessDeniedException, httpStatus=400]`. The AWS message is dropped because it repeats the key ARN and the caller's role ARN. This applies to the retry warning, to the failure logs for creating a key, generating or decrypting a data key and validating a master key, and to the messages of the exceptions the plugin throws for those failures. Those exceptions carry no cause, so the original error does not appear in a stack trace either. The master key failure logs also show the masked key and the error summary.
+- **Other errors** reported by the same code keep their type and message, with ARNs, URL credentials (`user:password@host`) and the value of any `name=value` pair whose name contains `password`, `passwd`, `pwd`, `secret`, `token` or `credential`, or is `key`, masked. Messages are cut at 200 characters.
+- **Connection URLs** that the plugin logs or puts in an exception have their user info and password parameters (any parameter whose name contains `password`, `passwd`, `pwd`, `secret`, `token` or `credential`) masked, and `ConnectionParameters.toString()` prints the names of the connection properties but not their values.
+- **Control characters** (line breaks, other ISO control characters, and invisible formatting characters such as bidirectional overrides) in a key, URL or error are replaced with `?`. A `master_key_arn` that someone rewrote in `key_storage` therefore cannot forge log lines.
+
+Masking is deliberately cautious. The user info of a URL is everything up to the last `@` before the next `?`, `#` or whitespace, so a URL whose path contains `@` (for example `jdbc:mysql://host/db@x`) is logged as `jdbc:mysql://***@x`. Hiding too much is accepted so that a password containing an unencoded `/` is never logged.
+
+What the plugin does not mask:
+
+- **A password written in a URL with `?`, `#` or a space in it.** These end the user info, so only the part before them is masked. Pass the password as the `password` property, or percent-encode those characters (`%3F`, `%23`, `%20`).
+- **A secret in a property or parameter whose name does not look like a secret**, for example `foo=<secret>`. The plugin cannot recognize it.
+- **Other values the plugin logs**: table and column names, SQL text, primary key values, the description you pass to `createMasterKey`, and errors from the database. Do not put secrets in a master key description.
+- **Anything it did not write.** Log records and exceptions from the JDBC driver, the AWS SDK or your own code are not masked, and the AWS SDK can log the full request and error text when its logging is turned up. Do not enable wire or request logging for the driver or the SDK in production.
+- **Values you read yourself.** `master_key_arn` and key ids that you read from the metadata tables with SQL (see Debugging) are shown in full, so do not paste them into shared logs.
+
 ### Data Protection
 
 - Encrypted data is stored as binary data in the database
@@ -1002,7 +1022,7 @@ Statements on tables without encrypted columns are never rejected. If you encoun
 2. **Metadata table not found**: Verify that the tables in the metadata schema exist and are accessible, and that `encryptionMetadataSchema` names that schema.
 3. **`No encryption configuration found for ...`** (from `KeyManagementUtility`): Verify the column is registered in `encrypt.encryption_metadata`, that the table and column names match exactly (case-sensitive), and that its `key_id` references a row in `encrypt.key_storage`.
 4. **`encryptionAllowedMasterKeyArns is required: list the KMS master key ARNs the KMS encryption plugin may use`**: The plugin was loaded without `encryptionAllowedMasterKeyArns`. Set it to the master keys your columns use; `SELECT DISTINCT master_key_arn FROM encrypt.key_storage` lists them. Check each one before you add it: the point of the list is that `key_storage` is not trusted.
-5. **`Refusing to use master key arn:aws:kms:***:***:key/<key id>: it is not listed in encryptionAllowedMasterKeyArns`** (SQL state `KEY07`): The column's `key_storage` row names a master key that is not on the list. The message masks the key's region and account; the full value is in `key_storage.master_key_arn`. If the key is yours, add it to the list in exactly the form stored in `key_storage.master_key_arn`. If it is not, someone changed the row: investigate before you change anything.
+5. **`Refusing to use master key arn:aws:kms:***:***:key/1234***abcd: it is not listed in encryptionAllowedMasterKeyArns`** (SQL state `KEY07`): The column's `key_storage` row names a master key that is not on the list. The message masks the key's region and account and the middle of its id (an alias is shown as `arn:aws:kms:***:***:alias/***`); the full value is in `key_storage.master_key_arn`. If the key is yours, add it to the list in exactly the form stored in `key_storage.master_key_arn`. If it is not, someone changed the row: investigate before you change anything.
 6. **`HMAC verification failed`** (driver, on read):
    - Data may have been tampered with, or the HMAC key in `encrypt.key_storage.hmac_key` changed
    - The column's data key was rotated without re-encrypting existing rows (for example with `rotateDataKey()`), or a re-encryption has not finished. See [Finishing or repairing a re-encryption](#finishing-or-repairing-a-re-encryption)
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/exception/IndependentConnectionException.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/exception/IndependentConnectionException.java
index 89c2a6aeb..0a26591f2 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/exception/IndependentConnectionException.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/exception/IndependentConnectionException.java
@@ -18,6 +18,7 @@
 
 import java.sql.SQLException;
 import org.checkerframework.checker.nullness.qual.Nullable;
+import software.amazon.jdbc.plugin.encryption.logging.Sanitizer;
 import software.amazon.jdbc.plugin.encryption.model.ConnectionParameters;
 
 /**
@@ -210,17 +211,6 @@ private static String formatMessage(
    * sensitive parameters while preserving useful debugging information.
    */
   private static @Nullable String maskSensitiveUrl(final @Nullable String jdbcUrl) {
-    if (jdbcUrl == null) {
-      return null;
-    }
-
-    // Remove password parameters from URL
-    String masked = jdbcUrl.replaceAll("([?&]password=)[^&]*", "$1***");
-    masked = masked.replaceAll("([?&]pwd=)[^&]*", "$1***");
-
-    // Remove user credentials from URL if present
-    masked = masked.replaceAll("://[^:/@]+:[^@]*@", "://***:***@");
-
-    return masked;
+    return Sanitizer.connectionUrl(jdbcUrl);
   }
 }
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/factory/EncryptingDataSourceFactory.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/factory/EncryptingDataSourceFactory.java
index 1199a2d10..ea7e1f4b9 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/factory/EncryptingDataSourceFactory.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/factory/EncryptingDataSourceFactory.java
@@ -22,6 +22,7 @@
 import javax.sql.DataSource;
 import org.checkerframework.checker.nullness.qual.Nullable;
 import software.amazon.jdbc.ds.AwsWrapperDataSource;
+import software.amazon.jdbc.plugin.encryption.logging.Sanitizer;
 import software.amazon.jdbc.plugin.encryption.model.EncryptionConfig;
 import software.amazon.jdbc.plugin.encryption.wrapper.EncryptingDataSource;
 import software.amazon.jdbc.util.Messages;
@@ -68,7 +69,8 @@ public static EncryptingDataSource create(DataSource dataSource, Properties encr
   public static EncryptingDataSource createWithAwsWrapper(
       String jdbcUrl, String username, String password, Properties encryptionProperties)
       throws SQLException {
-    logger.info(Messages.get("EncryptingDataSourceFactory.creatingWithWrapper", new Object[]{jdbcUrl}));
+    logger.info(Messages.get(
+        "EncryptingDataSourceFactory.creatingWithWrapper", new Object[]{Sanitizer.connectionUrl(jdbcUrl)}));
 
     try {
       // Create properties for AWS JDBC Wrapper
@@ -180,8 +182,8 @@ private static Properties createDefaultEncryptionProperties(String allowedMaster
     // Metadata configuration
     properties.setProperty(EncryptionConfig.METADATA_CACHE_REFRESH_INTERVAL_MS.name, "300000");
 
-    logger.fine(
-        Messages.get("EncryptingDataSourceFactory.createdDefaults", new Object[]{allowedMasterKeyArns, region}));
+    logger.fine(Messages.get(
+        "EncryptingDataSourceFactory.createdDefaults", new Object[]{Sanitizer.arnList(allowedMasterKeyArns), region}));
 
     return properties;
   }
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManagementException.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManagementException.java
index 94fab1ded..21e7e391a 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManagementException.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManagementException.java
@@ -20,6 +20,7 @@
 import java.util.HashMap;
 import java.util.Map;
 import org.checkerframework.checker.nullness.qual.Nullable;
+import software.amazon.jdbc.plugin.encryption.logging.Sanitizer;
 
 /**
  * Exception thrown when key management operations fail. Extends SQLException to integrate with JDBC
@@ -125,7 +126,7 @@ public KeyManagementException withContext(String key, final @Nullable Object val
    * @return this exception for method chaining
    */
   public KeyManagementException withKeyId(final @Nullable String keyId) {
-    return withContext("keyId", sanitizeKeyId(keyId));
+    return withContext("keyId", Sanitizer.keyId(keyId));
   }
 
   /**
@@ -135,7 +136,7 @@ public KeyManagementException withKeyId(final @Nullable String keyId) {
    * @return this exception for method chaining
    */
   public KeyManagementException withMasterKeyArn(final @Nullable String masterKeyArn) {
-    return withContext("masterKeyArn", sanitizeArn(masterKeyArn));
+    return withContext("masterKeyArn", Sanitizer.arn(masterKeyArn));
   }
 
   /**
@@ -270,46 +271,4 @@ public static KeyManagementException kmsConnectionFailed(
   public static KeyManagementException invalidKeyMetadata(String message) {
     return new KeyManagementException(message, INVALID_KEY_METADATA_STATE, null);
   }
-
-  // Sanitization methods to prevent sensitive data exposure
-
-  private @Nullable String sanitizeKeyId(final @Nullable String keyId) {
-    if (keyId == null) {
-      return null;
-    }
-    // Show only first and last 4 characters of key ID
-    if (keyId.length() > 8) {
-      return keyId.substring(0, 4) + "***" + keyId.substring(keyId.length() - 4);
-    }
-    return "***";
-  }
-
-  /**
-   * Masks a master key ARN for logs and error context: keeps only the key id, and replaces control
-   * characters, since the ARN may come from a key_storage row that someone rewrote.
-   *
-   * @param arn the master key ARN, alias, or key id
-   * @return the masked value, or null for null
-   */
-  static @Nullable String sanitizeArn(final @Nullable String arn) {
-    if (arn == null) {
-      return null;
-    }
-    // Keep only the key ID part of the ARN
-    int lastSlash = arn.lastIndexOf('/');
-    if (lastSlash != -1 && lastSlash < arn.length() - 1) {
-      return "arn:aws:kms:***:***:key/" + replaceControlCharacters(arn.substring(lastSlash + 1));
-    }
-    return "arn:aws:kms:***:***:key/***";
-  }
-
-  private static String replaceControlCharacters(final String value) {
-    final StringBuilder sb = new StringBuilder(value.length());
-    for (int i = 0; i < value.length(); i++) {
-      final char c = value.charAt(i);
-      sb.append(Character.isISOControl(c) ? '?' : c);
-    }
-    return sb.toString();
-  }
-
 }
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManagementUtility.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManagementUtility.java
index 2f2b2b1c4..c0aaef8b9 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManagementUtility.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManagementUtility.java
@@ -44,6 +44,7 @@
 import software.amazon.awssdk.services.kms.model.KeyState;
 import software.amazon.awssdk.services.kms.model.KeyUsageType;
 import software.amazon.jdbc.plugin.encryption.KmsEncryptionConnectionPlugin;
+import software.amazon.jdbc.plugin.encryption.logging.Sanitizer;
 import software.amazon.jdbc.plugin.encryption.metadata.MetadataException;
 import software.amazon.jdbc.plugin.encryption.metadata.MetadataManager;
 import software.amazon.jdbc.plugin.encryption.model.ColumnEncryptionConfig;
@@ -283,13 +284,15 @@ public String createMasterKeyWithPermissions(String description, final @Nullable
 
       kmsClient.createAlias(aliasRequest);
 
-      LOGGER.info(() -> Messages.get("KeyManagementUtility.masterKeyCreated", new Object[]{keyArn, aliasName}));
+      LOGGER.info(() -> Messages.get(
+          "KeyManagementUtility.masterKeyCreated", new Object[]{Sanitizer.arn(keyArn), aliasName}));
       return keyArn;
 
     } catch (Exception e) {
-      LOGGER.severe(() -> Messages.get("KeyManagementUtility.masterKeyFailed", new Object[]{e.getMessage()}));
+      LOGGER.severe(() -> Messages.get(
+          "KeyManagementUtility.masterKeyFailed", new Object[]{Sanitizer.errorSummary(e)}));
       throw new KeyManagementException(
-          Messages.get("KeyManagementUtility.createMasterKeyFailed", new Object[]{e.getMessage(), e}));
+          Messages.get("KeyManagementUtility.createMasterKeyFailed", new Object[]{Sanitizer.errorSummary(e)}));
     }
   }
 
@@ -326,7 +329,7 @@ public void generateAndStoreDataKey(
     }
 
     LOGGER.info(() -> Messages.get(
-        "KeyManagementUtility.generatingDataKey", new Object[]{tableName, columnName, masterKeyArn}));
+        "KeyManagementUtility.generatingDataKey", new Object[]{tableName, columnName, Sanitizer.arn(masterKeyArn)}));
 
     try {
 
@@ -466,7 +469,7 @@ public void rotateDataKey(String tableName, String columnName, @Nullable String
       LOGGER.severe(() -> Messages.get(
           "KeyManagementUtility.keyRotationFailed", new Object[]{tableName, columnName, e.getMessage()}));
       throw new KeyManagementException(
-          Messages.get("KeyManagementUtility.rotateDataKeyFailed", new Object[]{e.getMessage(), e}));
+          Messages.get("KeyManagementUtility.rotateDataKeyFailed", new Object[]{Sanitizer.errorSummary(e)}));
     }
   }
 
@@ -1416,7 +1419,8 @@ public List<String> getColumnsUsingKey(String keyId) throws KeyManagementExcepti
   public boolean validateMasterKey(String masterKeyArn) throws KeyManagementException {
     Objects.requireNonNull(masterKeyArn, "Master key ARN cannot be null");
 
-    LOGGER.finest(() -> Messages.get("KeyManagementUtility.validatingMasterKey", new Object[]{masterKeyArn}));
+    LOGGER.finest(() -> Messages.get(
+        "KeyManagementUtility.validatingMasterKey", new Object[]{Sanitizer.arn(masterKeyArn)}));
 
     try {
       DescribeKeyRequest request = DescribeKeyRequest.builder().keyId(masterKeyArn).build();
@@ -1429,14 +1433,16 @@ public boolean validateMasterKey(String masterKeyArn) throws KeyManagementExcept
               && keyMetadata.keyState() == KeyState.ENABLED
               && keyMetadata.keyUsage() == KeyUsageType.ENCRYPT_DECRYPT;
 
-      LOGGER.finest(() -> Messages.get("KeyManagementUtility.masterKeyValidated", new Object[]{masterKeyArn, isValid}));
+      LOGGER.finest(() -> Messages.get(
+          "KeyManagementUtility.masterKeyValidated", new Object[]{Sanitizer.arn(masterKeyArn), isValid}));
       return isValid;
 
     } catch (Exception e) {
       LOGGER.severe(() -> Messages.get(
-          "KeyManagementUtility.masterKeyValidationFailed", new Object[]{masterKeyArn, e.getMessage()}));
+          "KeyManagementUtility.masterKeyValidationFailed",
+          new Object[]{Sanitizer.arn(masterKeyArn), Sanitizer.errorSummary(e)}));
       throw new KeyManagementException(
-          Messages.get("KeyManagementUtility.validateMasterKeyFailed", new Object[]{e.getMessage(), e}));
+          Messages.get("KeyManagementUtility.validateMasterKeyFailed", new Object[]{Sanitizer.errorSummary(e)}));
     }
   }
 
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManager.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManager.java
index cc75eb346..80af862f4 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManager.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/key/KeyManager.java
@@ -64,6 +64,7 @@
 import software.amazon.jdbc.PluginService;
 import software.amazon.jdbc.plugin.encryption.cache.DataKeyCache;
 import software.amazon.jdbc.plugin.encryption.cache.DataKeyCache;
+import software.amazon.jdbc.plugin.encryption.logging.Sanitizer;
 import software.amazon.jdbc.plugin.encryption.model.EncryptionConfig;
 import software.amazon.jdbc.plugin.encryption.model.KeyMetadata;
 import software.amazon.jdbc.plugin.encryption.model.KeyMetadata;
@@ -171,13 +172,13 @@ public String createMasterKey(String description) throws KeyManagementException
       CreateKeyResponse response = executeWithRetry(() -> kmsClient.createKey(request));
       String keyArn = response.keyMetadata().arn();
 
-      LOGGER.info(() -> Messages.get("KeyManager.masterKeyCreated", new Object[]{keyArn}));
+      LOGGER.info(() -> Messages.get("KeyManager.masterKeyCreated", new Object[]{Sanitizer.arn(keyArn)}));
       return keyArn;
 
     } catch (Exception e) {
-      LOGGER.severe(() -> Messages.get("KeyManager.masterKeyFailed", new Object[]{e}));
+      LOGGER.severe(() -> Messages.get("KeyManager.masterKeyFailed", new Object[]{Sanitizer.errorSummary(e)}));
       throw new KeyManagementException(
-          Messages.get("KeyManager.createMasterKeyFailed", new Object[]{e.getMessage(), e}));
+          Messages.get("KeyManager.createMasterKeyFailed", new Object[]{Sanitizer.errorSummary(e)}));
     }
   }
 
@@ -192,7 +193,7 @@ public DataKeyResult generateDataKey(String masterKeyArn) throws KeyManagementEx
     authorizeMasterKey(masterKeyArn);
     Objects.requireNonNull(masterKeyArn, "Master key ARN cannot be null");
 
-    LOGGER.finest(() -> Messages.get("KeyManager.generatingDataKey", new Object[]{masterKeyArn}));
+    LOGGER.finest(() -> Messages.get("KeyManager.generatingDataKey", new Object[]{Sanitizer.arn(masterKeyArn)}));
 
     try {
       GenerateDataKeyRequest request =
@@ -207,9 +208,10 @@ public DataKeyResult generateDataKey(String masterKeyArn) throws KeyManagementEx
       return new DataKeyResult(encryptedKey);
 
     } catch (Exception e) {
-      LOGGER.severe(() -> Messages.get("KeyManager.dataKeyGenerationFailed", new Object[]{masterKeyArn, e}));
+      LOGGER.severe(() -> Messages.get(
+          "KeyManager.dataKeyGenerationFailed", new Object[]{Sanitizer.arn(masterKeyArn), Sanitizer.errorSummary(e)}));
       throw new KeyManagementException(
-          Messages.get("KeyManager.generateDataKeyFailed", new Object[]{e.getMessage(), e}));
+          Messages.get("KeyManager.generateDataKeyFailed", new Object[]{Sanitizer.errorSummary(e)}));
     }
   }
 
@@ -244,7 +246,7 @@ public byte[] decryptDataKey(String encryptedDataKey, String masterKeyArn)
       }
     }
 
-    LOGGER.finest(() -> Messages.get("KeyManager.decryptingDataKey", new Object[]{masterKeyArn}));
+    LOGGER.finest(() -> Messages.get("KeyManager.decryptingDataKey", new Object[]{Sanitizer.arn(masterKeyArn)}));
 
     byte @Nullable [] plaintextKey = null;
     try {
@@ -272,9 +274,10 @@ public byte[] decryptDataKey(String encryptedDataKey, String masterKeyArn)
       if (plaintextKey != null) {
         Arrays.fill(plaintextKey, (byte) 0);
       }
-      LOGGER.severe(() -> Messages.get("KeyManager.dataKeyDecryptionFailed", new Object[]{masterKeyArn, e}));
+      LOGGER.severe(() -> Messages.get(
+          "KeyManager.dataKeyDecryptionFailed", new Object[]{Sanitizer.arn(masterKeyArn), Sanitizer.errorSummary(e)}));
       throw new KeyManagementException(
-          Messages.get("KeyManager.decryptDataKeyFailed", new Object[]{e.getMessage(), e}));
+          Messages.get("KeyManager.decryptDataKeyFailed", new Object[]{Sanitizer.errorSummary(e)}));
     }
   }
 
@@ -478,7 +481,7 @@ void authorizeMasterKey(final @Nullable String masterKeyArn) throws KeyManagemen
     }
     // The ARN comes from key_storage and may have been written by someone else, so it is masked.
     final String message = Messages.get("KeyManager.masterKeyNotAllowed",
-        new Object[]{KeyManagementException.sanitizeArn(masterKeyArn),
+        new Object[]{Sanitizer.arn(masterKeyArn),
             EncryptionConfig.ALLOWED_MASTER_KEY_ARNS.name});
     LOGGER.warning(message);
     throw KeyManagementException.unauthorizedMasterKey(message, masterKeyArn);
@@ -515,7 +518,8 @@ private <T> T executeWithRetry(KmsOperation<T> operation) throws Exception {
           long backoffMs = calculateBackoff(attempt);
           int finalAttempt = attempt;
           LOGGER.warning(() -> Messages.get(
-              "KeyManager.retrying", new Object[]{finalAttempt + 1, maxRetries + 1, backoffMs, e.getMessage()}));
+              "KeyManager.retrying",
+              new Object[]{finalAttempt + 1, maxRetries + 1, backoffMs, Sanitizer.errorSummary(e)}));
 
           try {
             Thread.sleep(backoffMs);
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/logging/AuditLogger.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/logging/AuditLogger.java
index 5785cdf6a..e37e5264c 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/logging/AuditLogger.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/logging/AuditLogger.java
@@ -519,26 +519,13 @@ public void logConnectionHealthCheck(
   // Sanitization methods to prevent sensitive data exposure
 
   private String sanitizeArn(String arn) {
-    if (arn == null) {
-      return "null";
-    }
-    // Keep only the key ID part of the ARN for audit purposes
-    int lastSlash = arn.lastIndexOf('/');
-    if (lastSlash != -1 && lastSlash < arn.length() - 1) {
-      return "arn:aws:kms:***:***:key/" + arn.substring(lastSlash + 1);
-    }
-    return "arn:aws:kms:***:***:key/***";
+    final String masked = Sanitizer.arn(arn);
+    return masked == null ? "null" : masked;
   }
 
   private String sanitizeKeyId(String keyId) {
-    if (keyId == null) {
-      return "null";
-    }
-    // Show only first and last 4 characters of key ID
-    if (keyId.length() > 8) {
-      return keyId.substring(0, 4) + "***" + keyId.substring(keyId.length() - 4);
-    }
-    return "***";
+    final String masked = Sanitizer.keyId(keyId);
+    return masked == null ? "null" : masked;
   }
 
   private String sanitizeTableName(String tableName) {
@@ -591,17 +578,7 @@ private String sanitizeConfigDetails(String details) {
   }
 
   private String sanitizeJdbcUrl(String jdbcUrl) {
-    if (jdbcUrl == null) {
-      return "null";
-    }
-
-    // Remove password parameters from URL
-    String sanitized =
-        jdbcUrl
-            .replaceAll("(?i)[?&]password=[^&]*", "?password=***")
-            .replaceAll("(?i)[?&]pwd=[^&]*", "?pwd=***")
-            .replaceAll("(?i)://[^:]+:[^@]+@", "://***:***@");
-
-    return sanitized;
+    final String masked = Sanitizer.connectionUrl(jdbcUrl);
+    return masked == null ? "null" : masked;
   }
 }
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/logging/ErrorContext.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/logging/ErrorContext.java
index 6af22d59d..682128d24 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/logging/ErrorContext.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/logging/ErrorContext.java
@@ -83,7 +83,7 @@ public ErrorContext operation(String operation) {
    * @return This ErrorContext instance for chaining
    */
   public ErrorContext keyId(String keyId) {
-    context.put("keyId", sanitizeKeyId(keyId));
+    context.put("keyId", Sanitizer.keyId(keyId));
     return this;
   }
 
@@ -94,7 +94,7 @@ public ErrorContext keyId(String keyId) {
    * @return This ErrorContext instance for chaining
    */
   public ErrorContext masterKeyArn(String masterKeyArn) {
-    context.put("masterKeyArn", sanitizeArn(masterKeyArn));
+    context.put("masterKeyArn", Sanitizer.arn(masterKeyArn));
     return this;
   }
 
@@ -348,29 +348,6 @@ private void addContextualInfo(StringBuilder sb) {
 
   // Sanitization methods
 
-  private @Nullable String sanitizeKeyId(@Nullable String keyId) {
-    if (keyId == null) {
-      return null;
-    }
-    // Show only first and last 4 characters of key ID
-    if (keyId.length() > 8) {
-      return keyId.substring(0, 4) + "***" + keyId.substring(keyId.length() - 4);
-    }
-    return "***";
-  }
-
-  private @Nullable String sanitizeArn(@Nullable String arn) {
-    if (arn == null) {
-      return null;
-    }
-    // Keep only the key ID part of the ARN
-    int lastSlash = arn.lastIndexOf('/');
-    if (lastSlash != -1 && lastSlash < arn.length() - 1) {
-      return "arn:aws:kms:***:***:key/" + arn.substring(lastSlash + 1);
-    }
-    return "arn:aws:kms:***:***:key/***";
-  }
-
   private @Nullable String sanitizeSql(@Nullable String sql) {
     if (sql == null) {
       return null;
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/logging/Sanitizer.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/logging/Sanitizer.java
new file mode 100644
index 000000000..7e3874cd1
--- /dev/null
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/logging/Sanitizer.java
@@ -0,0 +1,362 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package software.amazon.jdbc.plugin.encryption.logging;
+
+import java.util.Locale;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
+import software.amazon.awssdk.awscore.exception.AwsServiceException;
+
+/**
+ * Redaction helpers shared by the encryption plugin's logs, error context and exception messages,
+ * so that a key id, an ARN or a connection URL is masked the same way wherever it appears. Every
+ * method returns null for null input, so callers decide how to render a missing value. None of
+ * them use backtracking regular expressions, so they run in linear time on any input.
+ *
+ * <p>What is masked: master key ARNs and key ids (the account, the region and the middle of the
+ * key id), aliases, other ARNs, the user info and password parameters of a connection URL, and
+ * the value of a password-like "name=value" pair. Control characters are replaced everywhere, so
+ * a value cannot forge log lines. Nothing else is touched: table and column names, SQL, primary
+ * keys and ordinary error text are logged as before.
+ */
+public final class Sanitizer {
+
+  private static final String ARN_PREFIX = "arn:aws:kms:***:***:key/";
+  private static final String ALIAS_ARN = "arn:aws:kms:***:***:alias/***";
+  private static final String OTHER_ARN = "arn:***";
+  private static final String MASK = "***";
+  private static final int MAX_ERROR_MESSAGE_LENGTH = 200;
+  // Names whose value is masked in a "name=value" pair, matched anywhere in the name, lower case.
+  private static final String[] SECRET_NAMES = {"password", "passwd", "pwd", "secret", "token", "credential"};
+
+  private Sanitizer() {
+  }
+
+  /**
+   * Masks a master key as the plugin accepts it: a KMS key ARN, "key/&lt;id&gt;", a bare key id or
+   * an alias. The account and region are dropped and the middle of the key id is masked the same
+   * way {@link #keyId} does, so a key id is redacted consistently wherever it appears. An alias is
+   * a name chosen by people, so none of it is kept, and an ARN that is not a KMS ARN (a role, say)
+   * is replaced whole. Control characters are replaced, since the value may come from a
+   * key_storage row that someone rewrote and a newline would forge log lines.
+   *
+   * @param value the master key ARN, alias, or key id
+   * @return the masked value, or null for null
+   */
+  public static @Nullable String arn(final @Nullable String value) {
+    if (value == null) {
+      return null;
+    }
+    final String lower = value.trim().toLowerCase(Locale.ROOT);
+    if (lower.startsWith("alias/") || lower.contains(":alias/")) {
+      return ALIAS_ARN;
+    }
+    if (lower.startsWith("arn:") && !isKmsArn(lower)) {
+      return OTHER_ARN;
+    }
+    // The key id is the part after the last '/', or the whole value when there is none.
+    final String id = value.substring(value.lastIndexOf('/') + 1);
+    return ARN_PREFIX + (id.isEmpty() ? MASK : keyId(id));
+  }
+
+  /**
+   * Masks every entry of a comma-separated list of master keys with {@link #arn}.
+   *
+   * @param commaSeparated the list, as configured
+   * @return the masked entries, comma-separated, or null for null
+   */
+  public static @Nullable String arnList(final @Nullable String commaSeparated) {
+    if (commaSeparated == null) {
+      return null;
+    }
+    final StringBuilder sb = new StringBuilder();
+    int start = 0;
+    while (start <= commaSeparated.length()) {
+      int end = commaSeparated.indexOf(',', start);
+      if (end < 0) {
+        end = commaSeparated.length();
+      }
+      final String entry = commaSeparated.substring(start, end).trim();
+      if (!entry.isEmpty()) {
+        if (sb.length() > 0) {
+          sb.append(", ");
+        }
+        sb.append(arn(entry));
+      }
+      start = end + 1;
+    }
+    return sb.toString();
+  }
+
+  /**
+   * Keeps the first and last four characters of a key id and masks the middle. Control characters
+   * are replaced.
+   *
+   * @param value the key id
+   * @return the masked value, or null for null
+   */
+  public static @Nullable String keyId(final @Nullable String value) {
+    if (value == null) {
+      return null;
+    }
+    if (value.length() > 8) {
+      return replaceControlCharacters(value.substring(0, 4)) + MASK
+          + replaceControlCharacters(value.substring(value.length() - 4));
+    }
+    return MASK;
+  }
+
+  /**
+   * Masks credentials embedded in a connection URL: the user info and the value of every
+   * password-like parameter. The user info is everything between "://" and the last '@' before
+   * the next '?', '#' or whitespace, found in a single pass, so a crafted URL cannot make this
+   * quadratic.
+   *
+   * <p>This deliberately over-masks. RFC 3986 ends the user info at the first '/', but a password
+   * with a raw '/' (the drivers expect it percent-encoded, yet people write it unencoded) then
+   * looks exactly like a path: "u:pa/ss@host/db" and "host/db@x" have the same shape, so no parser
+   * can tell them apart. Ending at the first '/' would log such a password in clear text, while
+   * going to the last '@' only costs a hidden host when a path contains '@' (it prints
+   * "***@x"). A log that hides too much is a nuisance; one that shows a password is a leak, so
+   * the ambiguity is resolved toward masking. Do not "fix" this to strict RFC parsing. For the
+   * same reason a password holding a raw '?' or '#' is not masked whole: they end the user info,
+   * because a query such as "?x=a@b" is far more common, and the drivers require them encoded.
+   *
+   * @param url the connection URL
+   * @return the masked URL, or null for null
+   */
+  public static @Nullable String connectionUrl(final @Nullable String url) {
+    if (url == null) {
+      return null;
+    }
+    return replaceControlCharacters(maskSecretPairs(maskUserInfo(url)));
+  }
+
+  private static String maskUserInfo(final String url) {
+    final int length = url.length();
+    StringBuilder sb = null;
+    int copied = 0;
+    int searchFrom = 0;
+    int schemeEnd;
+    while ((schemeEnd = url.indexOf("://", searchFrom)) >= 0) {
+      final int userInfoStart = schemeEnd + 3;
+      int end = userInfoStart;
+      int lastAt = -1;
+      int firstColon = -1;
+      while (end < length && !isUserInfoEnd(url.charAt(end))) {
+        final char c = url.charAt(end);
+        if (c == '@') {
+          lastAt = end;
+        } else if (c == ':' && firstColon < 0) {
+          firstColon = end;
+        }
+        end++;
+      }
+      // Everything up to the last '@' is treated as user info, even past a '/', because a raw '/'
+      // or '@' in a password is indistinguishable from a path (see the method comment). The
+      // known cost is that "host/db@x" loses its host; that is accepted to never leak a password.
+      if (lastAt >= 0) {
+        final boolean hasPassword = firstColon >= 0 && firstColon < lastAt;
+        if (sb == null) {
+          sb = new StringBuilder(length);
+        }
+        sb.append(url, copied, userInfoStart).append(hasPassword ? MASK + ':' + MASK : MASK);
+        copied = lastAt;
+      }
+      // Anything up to 'end' was scanned; a later "://" inside it is not a new URL.
+      searchFrom = Math.max(end, userInfoStart);
+    }
+    if (sb == null) {
+      return url;
+    }
+    return sb.append(url, copied, length).toString();
+  }
+
+  private static boolean isUserInfoEnd(final char c) {
+    return c == '?' || c == '#' || Character.isWhitespace(c);
+  }
+
+  /**
+   * Masks the value of every "name=value" pair whose name contains password, passwd, pwd, secret,
+   * token or credential, or is "key". The value ends at whitespace, '&amp;' or a quote. Each '='
+   * looks back over its own name only, so the total work is linear.
+   */
+  private static String maskSecretPairs(final String text) {
+    final int length = text.length();
+    StringBuilder sb = null;
+    int copied = 0;
+    for (int sep = text.indexOf('='); sep >= 0; sep = text.indexOf('=', sep + 1)) {
+      if (sep < copied) {
+        continue;
+      }
+      int nameStart = sep;
+      while (nameStart > copied && isNameCharacter(text.charAt(nameStart - 1))) {
+        nameStart--;
+      }
+      if (nameStart == sep || !isSecretName(text.substring(nameStart, sep))) {
+        continue;
+      }
+      int valueEnd = sep + 1;
+      while (valueEnd < length && !isValueEnd(text.charAt(valueEnd))) {
+        valueEnd++;
+      }
+      if (valueEnd == sep + 1) {
+        continue;
+      }
+      if (sb == null) {
+        sb = new StringBuilder(length);
+      }
+      sb.append(text, copied, sep + 1).append(MASK);
+      copied = valueEnd;
+    }
+    if (sb == null) {
+      return text;
+    }
+    return sb.append(text, copied, length).toString();
+  }
+
+  private static boolean isSecretName(final String name) {
+    final String lower = name.toLowerCase(Locale.ROOT);
+    if (lower.equals("key")) {
+      return true;
+    }
+    for (final String secret : SECRET_NAMES) {
+      if (lower.contains(secret)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  private static boolean isNameCharacter(final char c) {
+    return Character.isLetterOrDigit(c) || c == '_' || c == '-' || c == '.';
+  }
+
+  private static boolean isValueEnd(final char c) {
+    return c == '&' || c == '"' || c == '\'' || Character.isWhitespace(c);
+  }
+
+  /**
+   * Summarizes a failure for logs and wrapped exception messages without repeating the raw
+   * message. KMS errors such as AccessDenied repeat the key ARN and the caller's role ARN, so for
+   * an AWS service error only the exception type, error code and HTTP status are kept. For any
+   * other error the type is kept with its message, in which every ARN is masked and control
+   * characters are replaced.
+   *
+   * @param error the failure
+   * @return the summary, or null for null
+   */
+  public static @Nullable String errorSummary(final @Nullable Throwable error) {
+    if (error == null) {
+      return null;
+    }
+    final String type = error.getClass().getSimpleName();
+    if (error instanceof AwsServiceException) {
+      final AwsServiceException awsError = (AwsServiceException) error;
+      final AwsErrorDetails details = awsError.awsErrorDetails();
+      final String code = details == null ? null : details.errorCode();
+      return type + "[errorCode=" + (code == null ? "unknown" : errorMessage(code))
+          + ", httpStatus=" + awsError.statusCode() + "]";
+    }
+    final String message = errorMessage(error.getMessage());
+    return message == null || message.isEmpty() ? type : type + ": " + message;
+  }
+
+  /**
+   * Masks every ARN, URL credential and password-like "name=value" pair in free text, replaces
+   * control characters and limits the length. KMS key ARNs are masked with {@link #arn}; any other
+   * ARN (such as a role) is replaced entirely.
+   *
+   * @param message the text
+   * @return the sanitized text, or null for null
+   */
+  public static @Nullable String errorMessage(final @Nullable String message) {
+    if (message == null) {
+      return null;
+    }
+    final String cleaned = replaceControlCharacters(maskSecretPairs(maskUserInfo(maskArns(message))));
+    return cleaned.length() > MAX_ERROR_MESSAGE_LENGTH
+        ? cleaned.substring(0, MAX_ERROR_MESSAGE_LENGTH - 3) + "..."
+        : cleaned;
+  }
+
+  /**
+   * Masks every ARN in the text. A KMS key ARN is masked with {@link #arn}; any other ARN is
+   * replaced entirely. An ARN ends at whitespace, a quote, a bracket or '&amp;', ';', '|'.
+   */
+  private static String maskArns(final String message) {
+    final StringBuilder sb = new StringBuilder(message.length());
+    int copied = 0;
+    int searchFrom = 0;
+    int start;
+    while ((start = message.indexOf("arn:", searchFrom)) >= 0) {
+      // "learn:more" is not an ARN.
+      if (start > 0 && Character.isLetterOrDigit(message.charAt(start - 1))) {
+        searchFrom = start + 4;
+        continue;
+      }
+      int end = start;
+      while (end < message.length() && !isArnEnd(message.charAt(end))) {
+        end++;
+      }
+      // A trailing '.' or ',' is punctuation around the ARN, not part of it.
+      while (end > start && (message.charAt(end - 1) == '.' || message.charAt(end - 1) == ',')) {
+        end--;
+      }
+      sb.append(message, copied, start).append(arn(message.substring(start, end)));
+      copied = end;
+      searchFrom = Math.max(end, start + 4);
+    }
+    return sb.append(message, copied, message.length()).toString();
+  }
+
+  private static boolean isKmsArn(final String token) {
+    final String[] parts = token.split(":", 6);
+    return parts.length == 6 && "kms".equals(parts[2]);
+  }
+
+  private static boolean isArnEnd(final char c) {
+    return Character.isWhitespace(c) || c == '"' || c == '\'' || c == '(' || c == ')'
+        || c == '[' || c == ']' || c == '{' || c == '}' || c == '<' || c == '>' || c == '&'
+        || c == ';' || c == '|' || c == '\\';
+  }
+
+  /**
+   * Replaces control characters with '?': ISO control characters, line and paragraph separators
+   * format characters (such as bidirectional overrides) and unassigned ones, so a value cannot forge or hide log
+   * text.
+   *
+   * @param value the text
+   * @return the text without control characters
+   */
+  public static String replaceControlCharacters(final String value) {
+    final StringBuilder sb = new StringBuilder(value.length());
+    int i = 0;
+    while (i < value.length()) {
+      final int codePoint = value.codePointAt(i);
+      i += Character.charCount(codePoint);
+      final int type = Character.getType(codePoint);
+      final boolean control = Character.isISOControl(codePoint)
+          || type == Character.LINE_SEPARATOR
+          || type == Character.PARAGRAPH_SEPARATOR
+          || type == Character.FORMAT
+          || type == Character.UNASSIGNED;
+      sb.appendCodePoint(control ? '?' : codePoint);
+    }
+    return sb.toString();
+  }
+}
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/model/ConnectionParameters.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/model/ConnectionParameters.java
index 28a3f9d7f..919e2ef53 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/model/ConnectionParameters.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/model/ConnectionParameters.java
@@ -19,6 +19,7 @@
 import java.util.Objects;
 import java.util.Properties;
 import org.checkerframework.checker.nullness.qual.Nullable;
+import software.amazon.jdbc.plugin.encryption.logging.Sanitizer;
 import software.amazon.jdbc.util.Messages;
 
 /**
@@ -173,7 +174,13 @@ public String toString() {
     return String.format(
         "ConnectionParameters{jdbcUrl='%s', username='%s', password='[REDACTED]',"
             + " connectionProperties=%s, driverClassName='%s', catalog='%s', schema='%s'}",
-        jdbcUrl, username, connectionProperties, driverClassName, catalog, schema);
+        Sanitizer.connectionUrl(jdbcUrl), username, maskedProperties(), driverClassName, catalog,
+        schema);
+  }
+
+  // Connection properties routinely hold secrets (password, tokens), so only the names are printed.
+  private String maskedProperties() {
+    return connectionProperties == null ? "null" : connectionProperties.stringPropertyNames().toString();
   }
 
   /** Builder class for constructing ConnectionParameters instances. */
diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/model/KeyMetadata.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/model/KeyMetadata.java
index 6e36ef766..86d87b00b 100644
--- a/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/model/KeyMetadata.java
+++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/encryption/model/KeyMetadata.java
@@ -19,6 +19,7 @@
 import java.time.Instant;
 import java.util.Objects;
 import org.checkerframework.checker.nullness.qual.Nullable;
+import software.amazon.jdbc.plugin.encryption.logging.Sanitizer;
 
 /**
  * Metadata class for storing KMS key information including master key ARN, encrypted data key, and
@@ -151,7 +152,7 @@ public String toString() {
     return String.format(
         "KeyMetadata{keyId='%s', masterKeyArn='%s', keySpec='%s',"
             + " createdAt=%s, lastUsedAt=%s, encryptedDataKey='[REDACTED]'}",
-        keyId, masterKeyArn, keySpec, createdAt, lastUsedAt);
+        keyId, Sanitizer.arn(masterKeyArn), keySpec, createdAt, lastUsedAt);
   }
 
   public static Builder builder() {
diff --git a/wrapper/src/main/resources/aws_advanced_jdbc_wrapper_messages.properties b/wrapper/src/main/resources/aws_advanced_jdbc_wrapper_messages.properties
index 8d6eb9861..7a36eaab1 100644
--- a/wrapper/src/main/resources/aws_advanced_jdbc_wrapper_messages.properties
+++ b/wrapper/src/main/resources/aws_advanced_jdbc_wrapper_messages.properties
@@ -761,15 +761,15 @@ KmsEncryptionUtility.noIndependentDataSource=Independent DataSource: Not configu
 
 KeyManager.creatingMasterKey=Creating KMS master key with description: {0}
 KeyManager.masterKeyCreated=Successfully created KMS master key: {0}
-KeyManager.masterKeyFailed=Failed to create KMS master key
+KeyManager.masterKeyFailed=Failed to create KMS master key: {0}
 KeyManager.generatingDataKey=Generating data key using master key: {0}
 KeyManager.dataKeyGenerated=Data key generated successfully
-KeyManager.dataKeyGenerationFailed=Failed to generate data key: {0}
+KeyManager.dataKeyGenerationFailed=Failed to generate data key using master key {0}: {1}
 KeyManager.cacheHit=Cache hit for data key decryption
 KeyManager.masterKeyNotAllowed=Refusing to use master key {0}: it is not listed in {1}
 KeyManager.decryptingDataKey=Decrypting data key using master key: {0}
 KeyManager.dataKeyDecrypted=Data key decrypted successfully
-KeyManager.dataKeyDecryptionFailed=Failed to decrypt data key: {0}
+KeyManager.dataKeyDecryptionFailed=Failed to decrypt data key using master key {0}: {1}
 KeyManager.storingKeyMetadata=Storing key metadata for {0}.{1}
 KeyManager.keyMetadataStored=Key metadata stored with ID: {0}
 KeyManager.storeKeyMetadataFailed=Failed to store key metadata: {0}
@@ -796,7 +796,7 @@ KeyManagementUtility.closeConnectionFailed=Failed to close connection: {0}
 KeyManagementUtility.findingColumns=Finding columns using key ID: {0}
 KeyManagementUtility.findColumnsFailed=Failed to find columns for key: {0}
 KeyManagementUtility.validatingMasterKey=Validating master key: {0}
-KeyManagementUtility.masterKeyValidationFailed=Master key validation failed: {0}
+KeyManagementUtility.masterKeyValidationFailed=Master key validation failed for {0}: {1}
 KeyManagementUtility.removingEncryption=Removing encryption for {0}.{1}
 KeyManagementUtility.encryptionRemoved=Encryption removed for {0}.{1}
 
diff --git a/wrapper/src/test/java/software/amazon/jdbc/plugin/encryption/key/KeyManagementUtilityLoggingTest.java b/wrapper/src/test/java/software/amazon/jdbc/plugin/encryption/key/KeyManagementUtilityLoggingTest.java
new file mode 100644
index 000000000..70db0a37b
--- /dev/null
+++ b/wrapper/src/test/java/software/amazon/jdbc/plugin/encryption/key/KeyManagementUtilityLoggingTest.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package software.amazon.jdbc.plugin.encryption.key;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.sql.Connection;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
+import software.amazon.awssdk.services.kms.KmsClient;
+import software.amazon.awssdk.services.kms.model.CreateKeyRequest;
+import software.amazon.awssdk.services.kms.model.DescribeKeyRequest;
+import software.amazon.awssdk.services.kms.model.KmsException;
+import software.amazon.jdbc.plugin.encryption.metadata.MetadataManager;
+import software.amazon.jdbc.plugin.encryption.model.EncryptionConfig;
+
+public class KeyManagementUtilityLoggingTest {
+
+  private static final String KEY_UUID = "12345678-aaaa-bbbb-cccc-abcdefabcdef";
+  private static final String FULL_ARN = "arn:aws:kms:us-east-1:444444444444:key/" + KEY_UUID;
+  private static final String ROLE_ARN = "arn:aws:iam::333333333333:role/SecretRoleName";
+  private static final String KMS_MESSAGE = ROLE_ARN + " is not authorized on resource: " + FULL_ARN;
+
+  @Test
+  void validateMasterKey_logsTheMaskedKeyAndTheErrorSummary_withoutTheKmsMessage() {
+    final KmsClient kmsClient = mock(KmsClient.class);
+    when(kmsClient.describeKey(any(DescribeKeyRequest.class))).thenThrow(accessDenied());
+    final KeyManagementUtility utility = newUtility(kmsClient);
+
+    final List<LogRecord> records = new CopyOnWriteArrayList<>();
+    final KeyManagementException exception = capture(records,
+        () -> assertThrows(KeyManagementException.class, () -> utility.validateMasterKey(FULL_ARN)));
+
+    final LogRecord severe = find(records, Level.SEVERE, "Master key validation failed");
+    assertMasked(severe.getMessage());
+    assertTrue(severe.getMessage().contains("arn:aws:kms:***:***:key/1234***cdef"), severe.getMessage());
+    // The error is kept, as a summary.
+    assertTrue(severe.getMessage().contains("errorCode=AccessDeniedException, httpStatus=400"), severe.getMessage());
+    assertNull(severe.getThrown());
+    assertMasked(exception.getMessage());
+  }
+
+  @Test
+  void validateMasterKey_masksTheKeyInTheFinestLogs() throws Exception {
+    final KmsClient kmsClient = mock(KmsClient.class);
+    when(kmsClient.describeKey(any(DescribeKeyRequest.class))).thenReturn(
+        software.amazon.awssdk.services.kms.model.DescribeKeyResponse.builder().keyMetadata(
+            software.amazon.awssdk.services.kms.model.KeyMetadata.builder()
+                .enabled(true)
+                .keyState(software.amazon.awssdk.services.kms.model.KeyState.ENABLED)
+                .keyUsage(software.amazon.awssdk.services.kms.model.KeyUsageType.ENCRYPT_DECRYPT)
+                .build()).build());
+    final KeyManagementUtility utility = newUtility(kmsClient);
+
+    final Logger logger = Logger.getLogger(KeyManagementUtility.class.getName());
+    final Level previous = logger.getLevel();
+    logger.setLevel(Level.ALL);
+    final List<LogRecord> records = new CopyOnWriteArrayList<>();
+    try {
+      capture(records, () -> {
+        try {
+          return utility.validateMasterKey(FULL_ARN);
+        } catch (KeyManagementException e) {
+          throw new AssertionError(e);
+        }
+      });
+    } finally {
+      logger.setLevel(previous);
+    }
+
+    assertTrue(records.stream().anyMatch(r -> r.getMessage().startsWith("Validating master key")), records.toString());
+    records.forEach(r -> assertMasked(r.getMessage()));
+  }
+
+  @Test
+  void createMasterKey_logsAndThrowsTheErrorSummary_withoutTheKmsMessage() {
+    final KmsClient kmsClient = mock(KmsClient.class);
+    when(kmsClient.createKey(any(CreateKeyRequest.class))).thenThrow(accessDenied());
+    final KeyManagementUtility utility = newUtility(kmsClient);
+
+    final List<LogRecord> records = new CopyOnWriteArrayList<>();
+    final KeyManagementException exception = capture(records,
+        () -> assertThrows(KeyManagementException.class, () -> utility.createMasterKeyWithPermissions("test", null)));
+
+    final LogRecord severe = find(records, Level.SEVERE, "Failed to create master key");
+    assertMasked(severe.getMessage());
+    assertTrue(severe.getMessage().contains("errorCode=AccessDeniedException"), severe.getMessage());
+    assertMasked(exception.getMessage());
+  }
+
+  private static KmsException accessDenied() {
+    return (KmsException) KmsException.builder()
+        .message(KMS_MESSAGE)
+        .statusCode(400)
+        .awsErrorDetails(AwsErrorDetails.builder().errorCode("AccessDeniedException").build())
+        .build();
+  }
+
+  private static void assertMasked(final String text) {
+    assertFalse(text.contains(KEY_UUID), text);
+    assertFalse(text.contains("444444444444"), text);
+    assertFalse(text.contains("333333333333"), text);
+    assertFalse(text.contains("SecretRoleName"), text);
+  }
+
+  private static LogRecord find(final List<LogRecord> records, final Level level, final String text) {
+    return records.stream()
+        .filter(r -> r.getLevel().equals(level) && r.getMessage().contains(text))
+        .findFirst()
+        .orElseThrow(() -> new AssertionError("No " + level + " record containing '" + text + "' in " + records));
+  }
+
+  private static <T> T capture(final List<LogRecord> records, final java.util.function.Supplier<T> action) {
+    final Logger logger = Logger.getLogger(KeyManagementUtility.class.getName());
+    final Handler handler = new Handler() {
+      @Override
+      public void publish(LogRecord record) {
+        records.add(record);
+      }
+
+      @Override
+      public void flush() {
+      }
+
+      @Override
+      public void close() {
+      }
+    };
+    handler.setLevel(Level.ALL);
+    logger.addHandler(handler);
+    try {
+      return action.get();
+    } finally {
+      logger.removeHandler(handler);
+    }
+  }
+
+  private static KeyManagementUtility newUtility(final KmsClient kmsClient) {
+    final EncryptionConfig config = EncryptionConfig.builder().kmsRegion("us-east-1").maxRetries(0).build();
+    return new KeyManagementUtility(
+        mock(KeyManager.class), mock(MetadataManager.class), mock(Connection.class), kmsClient, config);
+  }
+}
diff --git a/wrapper/src/test/java/software/amazon/jdbc/plugin/encryption/key/KeyManagerTest.java b/wrapper/src/test/java/software/amazon/jdbc/plugin/encryption/key/KeyManagerTest.java
index 3c77ee1c2..9a78c6c34 100644
--- a/wrapper/src/test/java/software/amazon/jdbc/plugin/encryption/key/KeyManagerTest.java
+++ b/wrapper/src/test/java/software/amazon/jdbc/plugin/encryption/key/KeyManagerTest.java
@@ -20,6 +20,7 @@
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
@@ -34,21 +35,28 @@
 
 import java.lang.reflect.Field;
 import java.sql.Connection;
+import java.time.Duration;
 import java.util.Arrays;
 import java.util.Base64;
 import java.util.List;
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.logging.Handler;
+import java.util.logging.Level;
 import java.util.logging.LogRecord;
 import java.util.logging.Logger;
 import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
 import software.amazon.awssdk.core.SdkBytes;
 import software.amazon.awssdk.services.kms.KmsClient;
+import software.amazon.awssdk.services.kms.model.CreateKeyRequest;
+import software.amazon.awssdk.services.kms.model.CreateKeyResponse;
 import software.amazon.awssdk.services.kms.model.DecryptRequest;
 import software.amazon.awssdk.services.kms.model.DecryptResponse;
 import software.amazon.awssdk.services.kms.model.GenerateDataKeyRequest;
 import software.amazon.awssdk.services.kms.model.GenerateDataKeyResponse;
+import software.amazon.awssdk.services.kms.model.KeyMetadata;
+import software.amazon.awssdk.services.kms.model.KmsException;
 import software.amazon.jdbc.plugin.encryption.cache.DataKeyCache;
 import software.amazon.jdbc.plugin.encryption.model.EncryptionConfig;
 
@@ -56,6 +64,12 @@ public class KeyManagerTest {
 
   private static final String LISTED_ARN = "arn:aws:kms:us-east-1:111111111111:key/listed";
   private static final String UNLISTED_ARN = "arn:aws:kms:us-east-1:222222222222:key/unlisted";
+  private static final String KEY_UUID = "12345678-aaaa-bbbb-cccc-abcdefabcdef";
+  private static final String ROLE_ARN = "arn:aws:iam::333333333333:role/SecretRoleName";
+  private static final String FULL_ARN = "arn:aws:kms:us-east-1:444444444444:key/" + KEY_UUID;
+  // What KMS puts in an AccessDenied message: the key ARN and the caller's role ARN.
+  private static final String KMS_MESSAGE = ROLE_ARN + " is not authorized to perform: kms:GenerateDataKey on "
+      + "resource: " + FULL_ARN + " because no identity-based policy allows it";
   private static final String ENCRYPTED_DATA_KEY = Base64.getEncoder().encodeToString(new byte[] {1, 2, 3});
 
   @Test
@@ -130,18 +144,110 @@ public void close() {
         .orElseThrow(AssertionError::new);
     assertFalse(logged.contains("222222222222"), logged);
     assertFalse(logged.contains("\n"), logged);
-    assertTrue(logged.contains("arn:aws:kms:***:***:key/evil?SEVERE: forged line"), logged);
+    assertTrue(logged.contains("arn:aws:kms:***:***:key/evil***line"), logged);
     // The exception carries the same masked message as the log.
     assertEquals(logged, exception.getMessage());
     assertEquals(KeyManagementException.UNAUTHORIZED_MASTER_KEY_STATE, exception.getSQLState());
   }
 
   @Test
-  void sanitizeArn_keepsOnlyTheKeyId() {
-    assertEquals("arn:aws:kms:***:***:key/listed", KeyManagementException.sanitizeArn(LISTED_ARN));
-    assertEquals("arn:aws:kms:***:***:key/***", KeyManagementException.sanitizeArn("not-an-arn"));
-    assertEquals("arn:aws:kms:***:***:key/a?b", KeyManagementException.sanitizeArn("key/a\rb"));
-    assertEquals(null, KeyManagementException.sanitizeArn(null));
+  void generateDataKey_logsTheMaskedKeyAndTheErrorSummary_withoutTheKmsMessage() {
+    final KmsClient kmsClient = mock(KmsClient.class);
+    when(kmsClient.generateDataKey(any(GenerateDataKeyRequest.class))).thenThrow(accessDenied());
+    final KeyManager keyManager = newKeyManager(kmsClient, FULL_ARN);
+
+    final List<LogRecord> records = new CopyOnWriteArrayList<>();
+    final KeyManagementException exception = captureLogs(records,
+        () -> assertThrows(KeyManagementException.class, () -> keyManager.generateDataKey(FULL_ARN)));
+
+    final LogRecord severe = findRecord(records, Level.SEVERE, "Failed to generate data key");
+    assertSummaryOnly(severe.getMessage());
+    assertTrue(severe.getMessage().contains("arn:aws:kms:***:***:key/1234***cdef"), severe.getMessage());
+    // The error is kept, as a summary, and no Throwable is attached to the record.
+    assertTrue(severe.getMessage().contains("errorCode=AccessDeniedException"), severe.getMessage());
+    assertNull(severe.getThrown());
+    assertSummaryOnly(exception.getMessage());
+  }
+
+  @Test
+  void decryptDataKey_logsTheMaskedKeyAndTheErrorSummary_withoutTheKmsMessage() {
+    final KmsClient kmsClient = mock(KmsClient.class);
+    when(kmsClient.decrypt(any(DecryptRequest.class))).thenThrow(accessDenied());
+    final KeyManager keyManager = newKeyManager(kmsClient, FULL_ARN);
+
+    final List<LogRecord> records = new CopyOnWriteArrayList<>();
+    final KeyManagementException exception = captureLogs(records,
+        () -> assertThrows(KeyManagementException.class,
+            () -> keyManager.decryptDataKey(ENCRYPTED_DATA_KEY, FULL_ARN)));
+
+    final LogRecord severe = findRecord(records, Level.SEVERE, "Failed to decrypt data key");
+    assertSummaryOnly(severe.getMessage());
+    assertTrue(severe.getMessage().contains("arn:aws:kms:***:***:key/1234***cdef"), severe.getMessage());
+    assertTrue(severe.getMessage().contains("errorCode=AccessDeniedException"), severe.getMessage());
+    assertNull(severe.getThrown());
+    assertSummaryOnly(exception.getMessage());
+  }
+
+  @Test
+  void retry_logsTheErrorSummary_withoutTheKmsMessage() {
+    final KmsClient kmsClient = mock(KmsClient.class);
+    when(kmsClient.generateDataKey(any(GenerateDataKeyRequest.class)))
+        .thenThrow((KmsException) KmsException.builder()
+            .message(KMS_MESSAGE)
+            .statusCode(503)
+            .awsErrorDetails(AwsErrorDetails.builder().errorCode("ServiceUnavailable").build())
+            .build());
+    final KeyManager keyManager = new KeyManager(kmsClient, mock(Connection.class), false,
+        EncryptionConfig.builder().kmsRegion("us-east-1").maxRetries(1)
+            .retryBackoffBase(Duration.ofMillis(1)).allowedMasterKeyArns(FULL_ARN).build());
+
+    final List<LogRecord> records = new CopyOnWriteArrayList<>();
+    captureLogs(records,
+        () -> assertThrows(KeyManagementException.class, () -> keyManager.generateDataKey(FULL_ARN)));
+
+    final LogRecord warning = findRecord(records, Level.WARNING, "retrying");
+    assertSummaryOnly(warning.getMessage());
+    assertTrue(warning.getMessage().contains("errorCode=ServiceUnavailable, httpStatus=503"),
+        warning.getMessage());
+  }
+
+  @Test
+  void keyArnsAreMaskedAtEveryLevel_whenCreatingAndUsingKeys() throws Exception {
+    final KmsClient kmsClient = mock(KmsClient.class);
+    when(kmsClient.generateDataKey(any(GenerateDataKeyRequest.class)))
+        .thenReturn(GenerateDataKeyResponse.builder()
+            .ciphertextBlob(SdkBytes.fromByteArray(new byte[] {9}))
+            .plaintext(SdkBytes.fromByteArray(new byte[32]))
+            .build());
+    when(kmsClient.createKey(any(CreateKeyRequest.class)))
+        .thenReturn(CreateKeyResponse.builder()
+            .keyMetadata(KeyMetadata.builder().arn(FULL_ARN).build()).build());
+    final KeyManager keyManager = newKeyManager(kmsClient, FULL_ARN);
+
+    final Logger logger = Logger.getLogger(KeyManager.class.getName());
+    final Level previous = logger.getLevel();
+    logger.setLevel(Level.ALL);
+    final List<LogRecord> records = new CopyOnWriteArrayList<>();
+    try {
+      captureLogs(records, () -> {
+        try {
+          keyManager.generateDataKey(FULL_ARN);
+          keyManager.createMasterKey("test");
+        } catch (KeyManagementException e) {
+          throw new AssertionError(e);
+        }
+        return null;
+      });
+    } finally {
+      logger.setLevel(previous);
+    }
+
+    assertFalse(records.isEmpty());
+    for (final LogRecord record : records) {
+      assertFalse(record.getMessage().contains(KEY_UUID), record.getMessage());
+    }
+    assertNotNull(findRecord(records, Level.FINEST, "Generating data key using master key"));
+    assertNotNull(findRecord(records, Level.INFO, "Successfully created KMS master key"));
   }
 
   @Test
@@ -233,4 +339,51 @@ private static void replaceCache(KeyManager keyManager, DataKeyCache cache) thro
     ((DataKeyCache) field.get(keyManager)).shutdown();
     field.set(keyManager, cache);
   }
+
+  private static KmsException accessDenied() {
+    return (KmsException) KmsException.builder()
+        .message(KMS_MESSAGE)
+        .statusCode(400)
+        .awsErrorDetails(AwsErrorDetails.builder().errorCode("AccessDeniedException").build())
+        .build();
+  }
+
+  private static void assertSummaryOnly(final String text) {
+    assertFalse(text.contains(KEY_UUID), text);
+    assertFalse(text.contains("444444444444"), text);
+    assertFalse(text.contains("333333333333"), text);
+    assertFalse(text.contains("SecretRoleName"), text);
+  }
+
+  private static LogRecord findRecord(final List<LogRecord> records, final Level level, final String text) {
+    return records.stream()
+        .filter(r -> r.getLevel().equals(level) && r.getMessage().contains(text))
+        .findFirst()
+        .orElseThrow(() -> new AssertionError("No " + level + " record containing '" + text + "' in " + records));
+  }
+
+  private static <T> T captureLogs(final List<LogRecord> records, final java.util.function.Supplier<T> action) {
+    final Logger logger = Logger.getLogger(KeyManager.class.getName());
+    final Handler handler = new Handler() {
+      @Override
+      public void publish(LogRecord record) {
+        records.add(record);
+      }
+
+      @Override
+      public void flush() {
+      }
+
+      @Override
+      public void close() {
+      }
+    };
+    handler.setLevel(Level.ALL);
+    logger.addHandler(handler);
+    try {
+      return action.get();
+    } finally {
+      logger.removeHandler(handler);
+    }
+  }
 }
diff --git a/wrapper/src/test/java/software/amazon/jdbc/plugin/encryption/logging/SanitizerTest.java b/wrapper/src/test/java/software/amazon/jdbc/plugin/encryption/logging/SanitizerTest.java
new file mode 100644
index 000000000..aadc743be
--- /dev/null
+++ b/wrapper/src/test/java/software/amazon/jdbc/plugin/encryption/logging/SanitizerTest.java
@@ -0,0 +1,217 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License").
+ * You may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package software.amazon.jdbc.plugin.encryption.logging;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.time.Duration;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
+import software.amazon.awssdk.services.kms.model.KmsException;
+
+public class SanitizerTest {
+
+  private static final String ARN = "arn:aws:kms:us-east-1:111111111111:key/12345678-aaaa-bbbb-cccc-abcdefabcdef";
+
+  @Test
+  void arn_masksAccountRegionAndTheMiddleOfTheKeyId() {
+    assertEquals("arn:aws:kms:***:***:key/1234***cdef", Sanitizer.arn(ARN));
+    assertEquals("arn:aws:kms:***:***:key/1234***cdef", Sanitizer.arn("key/12345678-aaaa-bbbb-cccc-abcdefabcdef"));
+    assertEquals("arn:aws:kms:***:***:key/***", Sanitizer.arn("arn:aws:kms:us-east-1:111111111111:key/short"));
+    assertEquals("arn:aws:kms:***:***:key/not-***-arn", Sanitizer.arn("not-an-arn"));
+    assertEquals("arn:aws:kms:***:***:key/1234***cdef", Sanitizer.arn("12345678-aaaa-bbbb-cccc-abcdefabcdef"));
+    assertEquals("arn:aws:kms:***:***:key/mrk-***cdef", Sanitizer.arn("mrk-1234567890abcdef"));
+    assertFalse(Sanitizer.arn("alias/prod-payments-key").contains("prod"));
+    assertEquals("arn:aws:kms:***:***:key/***", Sanitizer.arn("/leading"));
+    assertEquals("arn:aws:kms:***:***:key/***", Sanitizer.arn("trailing/"));
+    assertNull(Sanitizer.arn(null));
+  }
+
+  @Test
+  void arn_masksTheKeyIdTheSameWayAsKeyId() {
+    final String id = "12345678-aaaa-bbbb-cccc-abcdefabcdef";
+    assertTrue(Sanitizer.arn(ARN).endsWith("/" + Sanitizer.keyId(id)));
+    assertFalse(Sanitizer.arn(ARN).contains(id));
+  }
+
+  @Test
+  void arn_isIdempotent() {
+    assertEquals(Sanitizer.arn(ARN), Sanitizer.arn(Sanitizer.arn(ARN)));
+  }
+
+  @Test
+  void arn_replacesControlCharactersSoAForgedArnCannotForgeLogLines() {
+    final String forged = "arn:aws:kms:us-east-1:222222222222:key/evil\nSEVERE: forged line";
+    final String masked = Sanitizer.arn(forged);
+    assertEquals("arn:aws:kms:***:***:key/evil***line", masked);
+
+    // Control characters in the part of the key id that is kept are replaced too.
+    final String edges = Sanitizer.arn("key/\n\r\u2028\u0085-middle-\u2029\n\r\u0000");
+    assertFalse(edges.contains("\n") || edges.contains("\r") || edges.contains("\u2028")
+        || edges.contains("\u2029") || edges.contains("\u0085") || edges.contains("\u0000"), edges);
+    assertEquals("arn:aws:kms:***:***:key/????***????", edges);
+    assertEquals("????***????", Sanitizer.keyId("\n\r\u2028\u0085-middle-\u2029\n\r\u0000"));
+  }
+
+  @Test
+  void arnList_masksEveryEntry() {
+    final String other = "arn:aws:kms:eu-west-1:999999999999:key/99999999-aaaa-bbbb-cccc-000000000000";
+    final String masked = Sanitizer.arnList(ARN + " , " + other + ",alias/mine,,");
+    assertEquals("arn:aws:kms:***:***:key/1234***cdef, arn:aws:kms:***:***:key/9999***0000, "
+        + "arn:aws:kms:***:***:alias/***", masked);
+    assertEquals("", Sanitizer.arnList(""));
+    assertNull(Sanitizer.arnList(null));
+  }
+
+  @Test
+  void keyId_keepsTheFirstAndLastFourCharacters() {
+    assertEquals("1234***cdef", Sanitizer.keyId("12345678-aaaa-bbbb-cccc-abcdefabcdef"));
+    assertEquals("***", Sanitizer.keyId("12345678"));
+    assertEquals("1234***6789", Sanitizer.keyId("123456789"));
+    assertNull(Sanitizer.keyId(null));
+  }
+
+  @Test
+  void connectionUrl_masksUserInfoAndPasswordParameters() {
+    assertEquals("jdbc:postgresql://***:***@host:5432/db?x=a@b&password=***&PWD=***",
+        Sanitizer.connectionUrl("jdbc:postgresql://user:p%40ss:w@rd@host:5432/db?x=a@b&password=secret&PWD=other"));
+    assertEquals("jdbc:mysql://host/db?user=u&password=***",
+        Sanitizer.connectionUrl("jdbc:mysql://host/db?user=u&password=s3"));
+    assertEquals("jdbc:mysql://host/db?pwd=***&b=1", Sanitizer.connectionUrl("jdbc:mysql://host/db?pwd=s3&b=1"));
+    assertNull(Sanitizer.connectionUrl(null));
+  }
+
+  @Test
+  void connectionUrl_doesNotOverMatch() {
+    // The host and port look like user:password to a regex that is not bounded by the authority.
+    final String plain = "jdbc:postgresql://host:5432/db?x=a@b";
+    assertEquals(plain, Sanitizer.connectionUrl(plain));
+    // A user name without a password is masked too.
+    assertEquals("jdbc:postgresql://***@host/db", Sanitizer.connectionUrl("jdbc:postgresql://user@host/db"));
+    // Deliberate: "host/db@x" has the same shape as a password containing '/', so the host is
+    // masked rather than risk logging the password. See Sanitizer.connectionUrl.
+    assertEquals("jdbc:mysql://***@x", Sanitizer.connectionUrl("jdbc:mysql://host/db@x"));
+    // A password containing '/' is masked whole.
+    assertEquals("jdbc:postgresql://***:***@host/db", Sanitizer.connectionUrl("jdbc:postgresql://u:pa/ss@host/db"));
+    // Two URLs: each authority is masked on its own, and the text between them is kept.
+    assertEquals("a://***:***@h1/x b://***:***@h2/y", Sanitizer.connectionUrl("a://u:p@h1/x b://v:q@h2/y"));
+  }
+
+  @Test
+  void connectionUrl_runsInLinearTimeOnTheOldRegexWorstCase() {
+    // The old pattern ://[^:/@]+:[^@]*@ rescanned to the end of the input from every "://x:".
+    final String crafted = new String(new char[100_000]).replace("\0", "://a:");
+    final String masked = assertTimeoutPreemptively(Duration.ofSeconds(2), () -> Sanitizer.connectionUrl(crafted));
+    assertEquals(crafted, masked);
+
+    final String withCredentials = crafted + "@host/db";
+    assertTimeoutPreemptively(Duration.ofSeconds(2), () -> Sanitizer.connectionUrl(withCredentials));
+
+    final String manyAts = "://u:" + new String(new char[100_000]).replace("\0", "@") + "host";
+    assertEquals("://***:***@host", assertTimeoutPreemptively(Duration.ofSeconds(2),
+        () -> Sanitizer.connectionUrl(manyAts)));
+  }
+
+  @Test
+  void errorSummary_ofAnAwsError_keepsOnlyTheCodeAndStatus() {
+    final KmsException error = (KmsException) KmsException.builder()
+        .message("arn:aws:iam::333333333333:role/SecretRoleName is not authorized on " + ARN)
+        .statusCode(400)
+        .awsErrorDetails(AwsErrorDetails.builder().errorCode("AccessDeniedException").build())
+        .build();
+    assertEquals("KmsException[errorCode=AccessDeniedException, httpStatus=400]", Sanitizer.errorSummary(error));
+
+    final KmsException noDetails = (KmsException) KmsException.builder().message(ARN).statusCode(500).build();
+    assertEquals("KmsException[errorCode=unknown, httpStatus=500]", Sanitizer.errorSummary(noDetails));
+    assertNull(Sanitizer.errorSummary(null));
+  }
+
+  @Test
+  void errorSummary_ofAnotherError_masksArnsInTheMessage() {
+    final String summary = Sanitizer.errorSummary(new IllegalStateException(
+        "role arn:aws:iam::333333333333:role/SecretRoleName cannot use " + ARN + ", retry.\nSEVERE: forged"));
+    assertEquals("IllegalStateException: role arn:*** cannot use "
+        + "arn:aws:kms:***:***:key/1234***cdef, retry.?SEVERE: forged", summary);
+    assertEquals("IllegalStateException", Sanitizer.errorSummary(new IllegalStateException()));
+    assertEquals("IllegalStateException", Sanitizer.errorSummary(new IllegalStateException("")));
+  }
+
+  @Test
+  void errorMessage_isBoundedAndLinear() {
+    assertEquals(200, Sanitizer.errorMessage(new String(new char[10_000]).replace("\0", "x")).length());
+    final String crafted = new String(new char[100_000]).replace("\0", "arn:");
+    assertTimeoutPreemptively(Duration.ofSeconds(2), () -> Sanitizer.errorMessage(crafted));
+    // "learn:" is not an ARN.
+    assertEquals("learn:more", Sanitizer.errorMessage("learn:more"));
+  }
+
+  @Test
+  void arn_masksAliasesCompletely() {
+    assertEquals("arn:aws:kms:***:***:alias/***",
+        Sanitizer.arn("arn:aws:kms:us-east-1:111122223333:alias/prod-payments-key"));
+    assertEquals("arn:aws:kms:***:***:alias/***", Sanitizer.arn("alias/prod-payments-key"));
+    assertEquals("arn:aws:kms:***:***:alias/***", Sanitizer.arn(" Alias/prodpayments"));
+    assertEquals(Sanitizer.arn("alias/x"), Sanitizer.arn(Sanitizer.arn("alias/x")));
+  }
+
+  @Test
+  void arn_replacesAnArnThatIsNotAKmsKeyWhole() {
+    assertEquals("arn:***", Sanitizer.arn("arn:aws:iam::123456789012:role/Administrator"));
+  }
+
+  @Test
+  void connectionUrl_masksPasswordLikeParameters() {
+    assertEquals("jdbc:postgresql://h/db?user=u&sslpassword=***",
+        Sanitizer.connectionUrl("jdbc:postgresql://h/db?user=u&sslpassword=s3cret"));
+    assertEquals("jdbc:postgresql://h/db?trustStorePassword=***&a=1",
+        Sanitizer.connectionUrl("jdbc:postgresql://h/db?trustStorePassword=x&a=1"));
+    assertEquals("jdbc:x://h/db?token=***", Sanitizer.connectionUrl("jdbc:x://h/db?token=t"));
+    // Parameters that do not look like secrets are left alone.
+    assertEquals("jdbc:x://h/db?ssl=true&user=u", Sanitizer.connectionUrl("jdbc:x://h/db?ssl=true&user=u"));
+  }
+
+  @Test
+  void errorMessage_masksUrlsAndSecretsInFreeText() {
+    final String masked = Sanitizer.errorMessage(
+        "Connection to jdbc:postgresql://u:pw@host/db?password=zzz failed, secret=abc ok");
+    assertFalse(masked.contains("pw@") || masked.contains("zzz") || masked.contains("abc"), masked);
+    assertTrue(masked.contains("failed"), masked);
+    assertEquals("arn:aws:kms:***:***:alias/***",
+        Sanitizer.errorMessage("arn:aws:kms:us-east-1:111122223333:alias/prod"));
+  }
+
+  @Test
+  void errorMessage_leavesOrdinaryTextAlone() {
+    // Table names, SQL fragments, numbers and UUIDs are not secrets and stay readable.
+    final String text = "relation orders_2024 not found at 123456789012 rows, id 12345678-1234-1234-1234-123456789012";
+    assertEquals(text, Sanitizer.errorMessage(text));
+  }
+
+  @Test
+  void errorMessage_replacesFormatAndBidiCharacters() {
+    final char[] hidden = {0x202E, 0x200B, 0x2066, 0xFEFF, 0x061C, 0x00AD};
+    final StringBuilder input = new StringBuilder();
+    for (final char c : hidden) {
+      input.append('a').append(c);
+    }
+    assertEquals("a?a?a?a?a?a?", Sanitizer.errorMessage(input.toString()));
+  }
+}
