Úselo CreateKeysAndCertificate con un AWS SDK o CLI - AWS SDKEjemplos de código

Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Úselo CreateKeysAndCertificate con un AWS SDK o CLI

En los siguientes ejemplos de código se muestra cómo se utiliza CreateKeysAndCertificate.

C++
SDKpara C++
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

//! Create keys and certificate for an Aws IoT device. //! This routine will save certificates and keys to an output folder, if provided. /*! \param outputFolder: Location for storing output in files, ignored when string is empty. \param certificateARNResult: A string to receive the ARN of the created certificate. \param certificateID: A string to receive the ID of the created certificate. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::IoT::createKeysAndCertificate(const Aws::String &outputFolder, Aws::String &certificateARNResult, Aws::String &certificateID, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::IoT::IoTClient client(clientConfiguration); Aws::IoT::Model::CreateKeysAndCertificateRequest createKeysAndCertificateRequest; Aws::IoT::Model::CreateKeysAndCertificateOutcome outcome = client.CreateKeysAndCertificate(createKeysAndCertificateRequest); if (outcome.IsSuccess()) { std::cout << "Successfully created a certificate and keys" << std::endl; certificateARNResult = outcome.GetResult().GetCertificateArn(); certificateID = outcome.GetResult().GetCertificateId(); std::cout << "Certificate ARN: " << certificateARNResult << ", certificate ID: " << certificateID << std::endl; if (!outputFolder.empty()) { std::cout << "Writing certificate and keys to the folder '" << outputFolder << "'." << std::endl; std::cout << "Be sure these files are stored securely." << std::endl; Aws::String certificateFilePath = outputFolder + "/certificate.pem.crt"; std::ofstream certificateFile(certificateFilePath); if (!certificateFile.is_open()) { std::cerr << "Error opening certificate file, '" << certificateFilePath << "'." << std::endl; return false; } certificateFile << outcome.GetResult().GetCertificatePem(); certificateFile.close(); const Aws::IoT::Model::KeyPair &keyPair = outcome.GetResult().GetKeyPair(); Aws::String privateKeyFilePath = outputFolder + "/private.pem.key"; std::ofstream privateKeyFile(privateKeyFilePath); if (!privateKeyFile.is_open()) { std::cerr << "Error opening private key file, '" << privateKeyFilePath << "'." << std::endl; return false; } privateKeyFile << keyPair.GetPrivateKey(); privateKeyFile.close(); Aws::String publicKeyFilePath = outputFolder + "/public.pem.key"; std::ofstream publicKeyFile(publicKeyFilePath); if (!publicKeyFile.is_open()) { std::cerr << "Error opening public key file, '" << publicKeyFilePath << "'." << std::endl; return false; } publicKeyFile << keyPair.GetPublicKey(); } } else { std::cerr << "Error creating keys and certificate: " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
CLI
AWS CLI

Para crear un RSA key pair y emitir un certificado X.509

A continuación, se create-keys-and-certificate crea un par de RSA claves de 2048 bits y se emite un certificado X.509 con la clave pública emitida. Como esta es la única vez que el AWS IoT proporciona la clave privada para este certificado, asegúrese de guardarla en un lugar seguro.

aws iot create-keys-and-certificate \ --certificate-pem-outfile "myTest.cert.pem" \ --public-key-outfile "myTest.public.key" \ --private-key-outfile "myTest.private.key"

Salida:

{ "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/9894ba17925e663f1d29c23af4582b8e3b7619c31f3fbd93adcb51ae54b83dc2", "certificateId": "9894ba17925e663f1d29c23af4582b8e3b7619c31f3fbd93adcb51ae54b83dc2", "certificatePem": " -----BEGIN CERTIFICATE----- MIICiTCCEXAMPLE6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC VVMxCzAJBgNVBAgEXAMPLEAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6 b24xFDASBgNVBAsTC0lBTSEXAMPLE2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd BgkqhkiG9w0BCQEWEG5vb25lQGFtYEXAMPLEb20wHhcNMTEwNDI1MjA0NTIxWhcN MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCEXAMPL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-----BEGIN RSA PRIVATE KEY-----\nkey omittted for security reasons\n-----END RSA PRIVATE KEY-----\n" } }

Para obtener más información, consulte Crear y registrar un certificado de dispositivo de AWS IoT en la Guía para desarrolladores de AWS IoT.

Java
SDKpara Java 2.x
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/** * Creates an IoT certificate asynchronously. * * @return The ARN of the created certificate. * <p> * This method initiates an asynchronous request to create an IoT certificate. * If the request is successful, it prints the certificate details and returns the certificate ARN. * If an exception occurs, it prints the error message. */ public String createCertificate() { CompletableFuture<CreateKeysAndCertificateResponse> future = getAsyncClient().createKeysAndCertificate(); final String[] certificateArn = {null}; future.whenComplete((response, ex) -> { if (response != null) { String certificatePem = response.certificatePem(); certificateArn[0] = response.certificateArn(); // Print the details. System.out.println("\nCertificate:"); System.out.println(certificatePem); System.out.println("\nCertificate ARN:"); System.out.println(certificateArn[0]); } else { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof IotException) { System.err.println(((IotException) cause).awsErrorDetails().errorMessage()); } else { System.err.println("Unexpected error: " + cause.getMessage()); } } }); future.join(); return certificateArn[0]; }
Kotlin
SDKpara Kotlin
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

suspend fun createCertificate(): String? { IotClient { region = "us-east-1" }.use { iotClient -> val response = iotClient.createKeysAndCertificate() val certificatePem = response.certificatePem val certificateArn = response.certificateArn // Print the details. println("\nCertificate:") println(certificatePem) println("\nCertificate ARN:") println(certificateArn) return certificateArn } }