Google Cloud IoT Core se retirará el 16 de agosto de 2023. Comunícate con el equipo de cuentas de Google Cloud para obtener más información.

Crear un dispositivo con RSA

Crea un dispositivo con RSA256 para la autenticación.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

Go

Si quieres obtener más información, consulta la documentación de referencia de la API de Go de Cloud IoT Core.

Para autenticarte en Cloud IoT Core, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


// createRSA creates a device in a registry given RSA X.509 credentials.
func createRSA(w io.Writer, projectID string, region string, registryID string, deviceID string, keyPath string) (*cloudiot.Device, error) {
	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope)
	if err != nil {
		return nil, err
	}
	client, err := cloudiot.New(httpClient)
	if err != nil {
		return nil, err
	}

	keyBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		return nil, err
	}

	device := cloudiot.Device{
		Id: deviceID,
		Credentials: []*cloudiot.DeviceCredential{
			{
				PublicKey: &cloudiot.PublicKeyCredential{
					Format: "RSA_X509_PEM",
					Key:    string(keyBytes),
				},
			},
		},
	}

	parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
	response, err := client.Projects.Locations.Registries.Devices.Create(parent, &device).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintf(w, "Successfully created RSA256 X.509 device: %s", deviceID)

	return response, nil
}

Java

Si quieres obtener más información, consulta la documentación de referencia de la API de Java de Cloud IoT Core.

Para autenticarte en Cloud IoT Core, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/** Create a device that is authenticated using RS256. */
protected static void createDeviceWithRs256(
    String deviceId,
    String certificateFilePath,
    String projectId,
    String cloudRegion,
    String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
  String key = Files.asCharSource(new File(certificateFilePath), StandardCharsets.UTF_8).read();
  publicKeyCredential.setKey(key);
  publicKeyCredential.setFormat("RSA_X509_PEM");

  DeviceCredential devCredential = new DeviceCredential();
  devCredential.setPublicKey(publicKeyCredential);

  System.out.println("Creating device with id: " + deviceId);
  Device device = new Device();
  device.setId(deviceId);
  device.setCredentials(Collections.singletonList(devCredential));
  Device createdDevice =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .create(registryPath, device)
          .execute();

  System.out.println("Created device: " + createdDevice.toPrettyString());
}

Node.js

Si quieres obtener más información, consulta la documentación de referencia de la API de Node.js de Cloud IoT Core.

Para autenticarte en Cloud IoT Core, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// const cloudRegion = 'us-central1';
// const deviceId = 'my-rsa-device';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const iot = require('@google-cloud/iot');

const iotClient = new iot.v1.DeviceManagerClient({
  // optional auth parameters.
});

async function createDevice() {
  // Construct request
  const regPath = iotClient.registryPath(projectId, cloudRegion, registryId);
  const device = {
    id: deviceId,
    credentials: [
      {
        publicKey: {
          format: 'RSA_X509_PEM',
          key: readFileSync(rsaCertificateFile).toString(),
        },
      },
    ],
  };

  const request = {
    parent: regPath,
    device,
  };

  const [response] = await iotClient.createDevice(request);
  console.log('Created device', response);
}

createDevice();

PHP

Si quieres obtener más información, consulta la documentación de referencia de la API de PHP de Cloud IoT Core.

Para autenticarte en Cloud IoT Core, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

use Google\Cloud\Iot\V1\DeviceManagerClient;
use Google\Cloud\Iot\V1\Device;
use Google\Cloud\Iot\V1\DeviceCredential;
use Google\Cloud\Iot\V1\PublicKeyCredential;
use Google\Cloud\Iot\V1\PublicKeyFormat;

/**
 * Create a new device with the given id, using RS256 for
 * authentication.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $deviceId IOT Device ID
 * @param string $certificateFile Path to RS256 certificate file.
 * @param string $projectId (optional) Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function create_rsa_device(
    $registryId,
    $deviceId,
    $certificateFile,
    $projectId,
    $location = 'us-central1'
) {
    print('Creating new RS256 Device' . PHP_EOL);

    // Instantiate a client.
    $deviceManager = new DeviceManagerClient();
    $registryName = $deviceManager->registryName($projectId, $location, $registryId);

    $publicKey = (new PublicKeyCredential())
        ->setFormat(PublicKeyFormat::RSA_X509_PEM)
        ->setKey(file_get_contents($certificateFile));

    $credential = (new DeviceCredential())
        ->setPublicKey($publicKey);

    $device = (new Device())
        ->setId($deviceId)
        ->setCredentials([$credential]);

    $device = $deviceManager->createDevice($registryName, $device);

    printf('Device: %s : %s' . PHP_EOL,
        $device->getNumId(),
        $device->getId());
}

Python

Si quieres obtener más información, consulta la documentación de referencia de la API de Python de Cloud IoT Core.

Para autenticarte en Cloud IoT Core, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'
# certificate_file = 'path/to/certificate.pem'

client = iot_v1.DeviceManagerClient()

parent = client.registry_path(project_id, cloud_region, registry_id)

with io.open(certificate_file) as f:
    certificate = f.read()

# Note: You can have multiple credentials associated with a device.
device_template = {
    "id": device_id,
    "credentials": [
        {
            "public_key": {
                "format": iot_v1.PublicKeyFormat.RSA_X509_PEM,
                "key": certificate,
            }
        }
    ],
}

return client.create_device(request={"parent": parent, "device": device_template})

Ruby

Si quieres obtener más información, consulta la documentación de referencia de la API de Ruby de Cloud IoT Core.

Para autenticarte en Cloud IoT Core, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region the registry is located in"
# registry_id = "The registry to create a device in"
# device_id   = "The identifier of the device to create"
# cert_path   = "The path to the RSA certificate"

require "google/apis/cloudiot_v1"

# Initialize the client and authenticate with the specified scope
Cloudiot   = Google::Apis::CloudiotV1
iot_client = Cloudiot::CloudIotService.new
iot_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the location associated with the project
parent = "projects/#{project_id}/locations/#{location_id}/registries/#{registry_id}"

credential = Google::Apis::CloudiotV1::DeviceCredential.new
credential.public_key = Google::Apis::CloudiotV1::PublicKeyCredential.new
credential.public_key.format = "RSA_X509_PEM"
credential.public_key.key = File.read cert_path

device = Cloudiot::Device.new
device.id = device_id
device.credentials = [credential]

# Create the device
device = iot_client.create_project_location_registry_device parent, device

puts "Device: #{device.id}"
puts "\tBlocked: #{device.blocked}"
puts "\tLast Event Time: #{device.last_event_time}"
puts "\tLast State Time: #{device.last_state_time}"
puts "\tName: #{device.name}"

¿Qué sigue?

Para buscar y filtrar muestras de código de otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.