如何使用PowerShell生成Azure IoT Central的SAS密钥
PowerShell 生成 Azure IoT Central 设备 SAS 密钥操作指南
Azure IoT Central 设备SAS密钥的计算规则:以目标设备ID为签名文本,使用对应设备连接组的主访问密钥做HMAC-SHA256哈希计算,最终将哈希结果做Base64编码,即为设备专属SAS密钥。
可直接运行的PowerShell实现代码
function New-IoTCentralDeviceKey { param( [Parameter(Mandatory = $true)] [string]$GroupPrimaryKey, [Parameter(Mandatory = $true)] [string]$DeviceId ) $keyBytes = [Convert]::FromBase64String($GroupPrimaryKey) $hmacSha256 = [System.Security.Cryptography.HMACSHA256]::new() $hmacSha256.Key = $keyBytes $hashResult = $hmacSha256.ComputeHash([Text.Encoding]::UTF8.GetBytes($DeviceId)) return [Convert]::ToBase64String($hashResult) }
调用方式
- 从Azure IoT Central门户的「设备连接」页面,复制对应设备组的主密钥,作为
GroupPrimaryKey参数传入 - 传入你要生成密钥的目标设备ID作为
DeviceId参数 - 调用示例:
# 替换为你自己的设备组主密钥和设备ID $deviceSasKey = New-IoTCentralDeviceKey -GroupPrimaryKey "粘贴你的设备组主密钥" -DeviceId "填写目标设备ID" Write-Output "生成完成,设备SAS密钥:$deviceSasKey"
Azure CLI 命令报错排查
如果你之前执行az iot central device compute-device-key命令失败,可按以下顺序排查:
- 执行
az extension add --name azure-iot确认已安装IoT扩展,已安装的话执行az extension update --name azure-iot升级到最新版本 - 检查传入的主密钥、设备ID参数无多余空格、特殊字符转义错误
- 执行
az account show确认当前CLI登录的订阅、租户和你IoT Central实例所属环境一致,必要时执行az login重新切换账号
内容的提问来源于stack exchange,提问作者Dinuka Wanasinghe
相关产品推荐
相关产品推荐

