AWS Security ChangesHomeSearch

AWS code-library high security documentation change

Service: code-library · 2025-08-01 · Security-related high

File: code-library/latest/ug/ec2_example_ec2_CreateKeyPair_section.md

Summary

Added Swift SDK example for CreateKeyPair API with private key storage in temporary directory

Security assessment

The example writes private keys to world-accessible temporary storage without specifying file permissions, demonstrating insecure handling of sensitive credentials that could lead to private key exposure.

Diff

diff --git a/code-library/latest/ug/ec2_example_ec2_CreateKeyPair_section.md b/code-library/latest/ug/ec2_example_ec2_CreateKeyPair_section.md
index 5395bce5d..951b69273 100644
--- a//code-library/latest/ug/ec2_example_ec2_CreateKeyPair_section.md
+++ b//code-library/latest/ug/ec2_example_ec2_CreateKeyPair_section.md
@@ -812,0 +813,58 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
+Swift
+    
+
+**SDK for Swift**
+    
+
+###### Note
+
+There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples). 
+    
+    
+    import AWSEC2
+    
+        /// Create a new RSA key pair and save the private key to a randomly-named
+        /// file in the temporary directory.
+        ///
+        /// - Parameter name: The name of the key pair to create.
+        ///
+        /// - Returns: The URL of the newly created `.pem` file or `nil` if unable
+        ///   to create the key pair.
+        func createKeyPair(name: String) async -> URL? {
+            do {
+                let output = try await ec2Client.createKeyPair(
+                    input: CreateKeyPairInput(
+                        keyName: name
+                    )
+                )
+    
+                guard let keyMaterial = output.keyMaterial else {
+                    return nil
+                }
+    
+                // Build the URL of the temporary private key file.
+    
+                let fileURL = URL.temporaryDirectory
+                                      .appendingPathComponent(name)
+                                      .appendingPathExtension("pem")
+    
+                do {
+                    try keyMaterial.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
+                    return fileURL
+                } catch {
+                    print("*** Failed to write the private key.")
+                    return nil
+                }
+            } catch {
+                print("*** Unable to create the key pair.")
+                return nil
+            }
+        }
+    
+    
+
+  * For API details, see [CreateKeyPair](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/createkeypair\(input:\)) in _AWS SDK for Swift API reference_. 
+
+
+
+