Я использую .NET SDK и хочу получить пароль Windows.
Я прочитал этот документ и написал код на основе Java .
Но у меня возникла эта ошибка на последовательном порту 1 при выполнении SetMetadataRequest
, и я не могу получить зашифрованный пароль на последовательном порту 4.
------------------- сообщение об ошибке при настройке метаданных --------------------------------
"2019/09/16 12:28:36 GCEWindowsAgent: ОШИБКА account.go: 275: недопустимый символ ':' после значения верхнего уровня"
Мой код:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Compute.v1;
using Google.Apis.Compute.v1.Data;
using Google.Apis.Services;
using java.math;
using java.security;
using java.security.spec;
using java.util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace GoogleHelper
{
internal class GoogleVmHelper : VmTaskInterface
{
private ComputeService _Client;
public async Task<bool> SetMetadata()
{
// //---after instantiate of ComputeService _Client////
InstancesResource.GetRequest describeServerReq = _Client.Instances.Get("projectid", "region", "serverid");
Data.Instance describeServerRes = await describeServerReq.ExecuteAsync();
Metadata oldMetaData = describeServerRes.Metadata;
// Generate the public/private key pair for encryption and decryption.
KeyPair keys = generateKeys();
var buildedKeys = buildKeyMetadata(keys);
//Replace Metadata
string newItemString = buildedKeys.ToString();
// Get the list containing all of the Metadata entries for this instance.
var items = oldMetaData.Items;
// If the instance has no metadata, items can be returned as null.
if (items == null)
{
items = new List<Metadata.ItemsData>();
oldMetaData.Items = items;
}
// Find the "windows-keys" entry and update it.
bool isFound = false;
foreach (var item in items)
{
if (item.Key == "windows-keys")
{
// Replace item's value with the new entry.
// To prevent race conditions, production code may want to maintain a
// list where the oldest entries are removed once the 32KB limit is
// reached for the metadata entry.
item.Value = newItemString;
isFound = true;
break;
}
}
if (!isFound)
{
// "windows.keys" entry doesn't exist in the metadata - append it.
// This occurs when running password-reset for the first time on an instance.
var addItem = new Metadata.ItemsData();
addItem.Key = "windows-keys";
addItem.Value = newItemString;
items.Add(addItem);
}
oldMetaData.Items = items;
//Set Metadata
var setMetadataReq = new InstancesResource.SetMetadataRequest(_Client, oldMetaData, _Profile.ProjectID, _Task.Region, _Task.ServerID);
var serMEtaDataRes = await setMetadataReq.ExecuteAsync();
await System.Threading.Tasks.Task.Delay(30000);
//GetPassword
var getSerialPortOutputReq = new InstancesResource.GetSerialPortOutputRequest(_Client, _Profile.ProjectID, _Task.Region, _Task.ServerID);
getSerialPortOutputReq.Port = 4;
var getSerialPortOutputRes = await getSerialPortOutputReq.ExecuteAsync();
//EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY
var entries = getSerialPortOutputRes.Contents;
//EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY
return true;
}
private KeyPair generateKeys()
{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
// Key moduli for encryption/decryption are 2048 bits long.
keyGen.initialize(2048);
return keyGen.genKeyPair();
}
private JObject jsonEncode(KeyPair keys)
{
KeyFactory factory = KeyFactory.getInstance("RSA");
// Get the RSA spec for key manipulation.
RSAPublicKeySpec pubSpec = factory.getKeySpec(keys.getPublic(), typeof(RSAPublicKeySpec)) as RSAPublicKeySpec;
// Extract required parts of the key.
BigInteger modulus = pubSpec.getModulus();
BigInteger exponent = pubSpec.getPublicExponent();
// Strip out the leading 0 byte in the modulus.
byte[] arr = Arrays.copyOfRange(modulus.toByteArray(), 1, modulus.toByteArray().Length);
JObject returnJson = new JObject();
// Encode the modulus, add to returned JSON object.
String modulusString = Convert.ToBase64String(arr).Replace("\n", "");
returnJson.Add("modulus", modulusString);
// Encode exponent, add to returned JSON object.
String exponentString = Convert.ToBase64String(exponent.toByteArray()).Replace("\n", "");
returnJson.Add("exponent", exponentString);
return returnJson;
}
private JObject buildKeyMetadata(KeyPair pair)
{
// Encode the public key into the required JSON format.
var metadataValues = jsonEncode(pair);
// Add username and email.
metadataValues.Add("userName", "myusername");
metadataValues.Add("email", "myemal");
//Create the date on which the new keys expire.
//DateTime now = new DateTime();
var expiredDate = DateTime.Now + TimeSpan.FromMinutes(5);
//Format the date to match rfc3339.
DateTime utcTime = System.TimeZoneInfo.ConvertTimeToUtc(expiredDate);
String dateString = utcTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'");
//Encode the expiration date for the returned JSON dictionary.
metadataValues.Add("expireOn", dateString);
return metadataValues;
}
}
}