uniapp开发app框架在提升开发效率中的独特优势与应用探索
1240
2022-09-16
API接口常用签名加密方式及示例代码
Bese64编码加密字符串
function Base64String{<#.Synopsis Base64加密#>param([Parameter(Mandatory=$true)] $string)$Bytes = [System.Text.Encoding]::UTF8.GetBytes($string)$EncodedText =[Convert]::ToBase64String($Bytes)return $EncodedText}
MD5加密字符串
function MD5Encrypt{param([Parameter(Mandatory=$true)] $string)$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider$utf8 = new-object -TypeName System.Text.UTF8Encoding$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($string)))$sign = $hash.ToLower() -replace '-', ''return $sign}
HMAC Hash加密字符串
function Get-HMACHash { [CmdletBinding()] param ( # Message to geneate a HMAC hash for [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default", ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [String] $Message, # Secret Key [Parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default", ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Alias("Key")] [String] $Secret, # Algorithm [Parameter(Mandatory = $false, Position = 2, ParameterSetName = "Default", ValueFromPipelineByPropertyName = $true)] [ValidateSet("MD5", "SHA1", "SHA256", "SHA384", "SHA512")] [Alias("alg")] [String] $Algorithm = "SHA256", # Output Format [Parameter(Mandatory = $false, Position = 2, ParameterSetName = "Default", ValueFromPipelineByPropertyName = $true)] [ValidateSet("Base64", "HEX", "hexlower")] [String] $Format = "Base64" ) $hmac = switch ($Algorithm) { "MD5" { New-Object System.Security.Cryptography.HMACMD5; break } "SHA1" { New-Object System.Security.Cryptography.HMACSHA1; break } "SHA256" { New-Object System.Security.Cryptography.HMACSHA256; break } "SHA384" { New-Object System.Security.Cryptography.HMACSHA384; break } "SHA512" { New-Object System.Security.Cryptography.HMACSHA512; break } } $hmac.key = [Text.Encoding]::UTF8.GetBytes($secret) $signature = $hmac.ComputeHash([Text.Encoding]::UTF8.GetBytes($message)) $signature = switch ($Format) { "HEX" { ($signature | ForEach-Object ToString X2 ) -join '' } "hexlower" { ($signature | ForEach-Object ToString x2 ) -join '' } Default { [Convert]::ToBase64String($signature) } } return ($signature)}$sign = Get-HMACHash -Message $signstr -Secret $secret -Algorithm SHA1 -Format Base64 #使用Get-HMACHash函数加密字符串,获取签名
RSA签名 (Powershell签名中文返回不正确,因此使用了Python签名中文,如有Powershell替代方案欢迎补充。)
pem文件是-----BEGIN PRIVATE KEY----- 开头,-----END PRIVATE KEY-----结尾的文件
#Powershell代码function RSASign{param([Parameter(Mandatory=$true)] [System.String]$String,[Parameter(Mandatory=$false)] [System.String]$dllPath="C:\Users\$env:username\Documents\WindowsPowershell\ChilkatDotNet48.dll",[Parameter(Mandatory=$false)] [System.String]$PemPath="C:\Users\$env:username\Documents\WindowsPowershell\private.pem")$chinese = "[\u4e00-\u9fa5]{1,}"if($String -match $chinese){ $rsafile = $folder + "\rsasign.py" $sign = python $rsafile "$String" return $sign}else{ if((Test-Path $PemPath) -and (Test-Path $dllPath)){ Add-Type -Path $dllPath $pkey = New-Object Chilkat.PrivateKey $success = $pkey.LoadPemFile($pempath) $pkeyXml = $pkey.GetXml() $rsa = New-Object Chilkat.Rsa $success = $rsa.ImportPrivateKey($pkeyXml) $rsa.EncodingMode = "hex" $sign = $rsa.SignStringENC($string,"sha-1") return $sign }else{ Write-Error "dll or Pem not exsit" }}}#Python代码import base64, sysfrom Crypto.Hash import SHAfrom Crypto.Signature import PKCS1_v1_5from Crypto.PublicKey import RSAmessage = sys.argv[1]digest = SHA.new()digest.update(message.encode('utf-8'))# Load private key previouly generatedwith open (r"C:\Users\username\Documents\WindowsPowerShell\private.pem", "r") as myfile: private_key = RSA.importKey(myfile.read())# Sign the messagesigner = PKCS1_v1_5.new(private_key)sig = signer.sign(digest)print(sig.hex())
忽略接口返回的证书报错
function Ignore-SelfSignedCerts {add-type @"using System.Net;using System.Security.Cryptography.X509Certificates;public class TrustAllCertsPolicy : ICertificatePolicy {public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate,WebRequest request, int certificateProblem) {return true;}}"@[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12}
使用apikey和secret获取jsON Web Token (JWT)-Python
import timeimport jwtimport sys,osapikey = sys.argv[1]secret = sys.argv[2]def get_jwt_token(apikey="", secret=""): if apikey and secret: header = { "alg": "HS256", "typ": "JWT" } expiredTime = time.time() + 90 * 60 payload = {"iss": apikey, "exp": expiredTime } jwt_token = jwt.encode(payload, secret, algorithm="HS256", headers=header).decode('ascii') return jwt_tokenresult = get_jwt_token(apikey, secret)print(result)
获取NBU Auth Header
function get-NBUAuth{<#.Synopsis获取NBU Auth Header#>param([Parameter(Mandatory=$false)] $nbumaster,[Parameter(Mandatory=$false)] $port="1556",[Parameter(Mandatory=$false)] $username,[Parameter(Mandatory=$true)] $password)$baseurl = "+ $nbumaster + ":" + $port + "/netbackup"$content_type = "application/vnd-backup+json;version=1.0"$uri = $baseurl + "/login"$body = @{ userName=$username password=$password}$response = Invoke-WebRequest -Uri $uri -Method POST -Body (ConvertTo-Json -InputObject $body) -ContentType $content_type$content = (ConvertFrom-Json -InputObject $response)$headers = @{ "Authorization" = $content.token}$result = New-Object psobject -ArgumentList @{headers = $headersbaseurl = $baseurlcontent_type = $content_type}return $result}
获取EMC datadomain Header
function Get-DDAuth{param([Parameter(Mandatory=$false)] $ddserver,[Parameter(Mandatory=$false)] $port=9090,[Parameter(Mandatory=$false)] $username = "administrator",[Parameter(Mandatory=$true)] $password)$basestring = $username + ":" + $password$basestring = ($basestring).Trim()$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($basestring))$authorization = "Basic $encodedCreds"$headers = @{ 'authorization'= $authorization 'content-type'= "application/json;charset=UTF-8"}$baseurl = "+ $ddserver + ":" + $port + "/nwrestapi/v3"$result = New-Object psobject -ArgumentList @{headers = $headersbaseurl = $baseurl}return $result}
网易API使用示例,查询账号
function Get-163Config{param([Parameter(Mandatory=$true)] [system.string]$domain,[Parameter(Mandatory=$false)] [System.String]$PemPath="C:\Users\$env:username\Documents\WindowsPowershell\private.pem") $userobject = New-Object psobject $userobject | Add-Member -MemberType NoteProperty -Name product -Value $product $userobject | Add-Member -MemberType NoteProperty -Name baseurl -Value $baseurl $userobject | Add-Member -MemberType NoteProperty -Name PemPath -Value $PemPath switch($domain){ "aaa.com" { $userobject.product = "aaaxxx" $userobject.baseurl = " } "bbb.com"{ $userobject.product = "bbbxxx" $userobject.baseurl = " } } return $userobject}function Get-TimeStamp{param([Parameter(Mandatory=$false)] [System.DateTime]$date)if(!$date){ $newdate = (get-date).AddHours(-8)}else{ $newdate = $date.AddHours(-8) } $timestamp = [System.String][math]::ceiling(($newdate - (get-date 1970.1.1)).TotalMilliseconds) return $timestamp}function RSASign{param([Parameter(Mandatory=$true)] [System.String]$String,[Parameter(Mandatory=$false)] [System.String]$dllPath="C:\Users\$env:username\Documents\WindowsPowershell\ChilkatDotNet48.dll",[Parameter(Mandatory=$false)] [System.String]$PemPath="C:\Users\$env:username\Documents\WindowsPowershell\private.pem")$chinese = "[\u4e00-\u9fa5]{1,}"if($String -match $chinese){ $rsafile = $folder + "\rsasign.py" $sign = python $rsafile "$String" return $sign}else{ if((Test-Path $PemPath) -and (Test-Path $dllPath)){ Add-Type -Path $dllPath $pkey = New-Object Chilkat.PrivateKey $success = $pkey.LoadPemFile($pempath) $pkeyXml = $pkey.GetXml() $rsa = New-Object Chilkat.Rsa $success = $rsa.ImportPrivateKey($pkeyXml) $rsa.EncodingMode = "hex" $sign = $rsa.SignStringENC($string,"sha-1") return $sign }else{ Write-Error "dll or Pem not exsit" }}}function Get-163User{param([Parameter(Mandatory=$true)] [system.string]$account_name,[Parameter(Mandatory=$true)] [system.string]$domain)$163config = Get-163Config -domain $domain$product = $163config.product$baseurl = $163config.baseurl$PemPath = $163config.PemPath$time = Get-TimeStamp$inputobject = $PSBoundParameters$inputobject.product = $product$inputobject.time = $time$newarray = $inputobject.GetEnumerator() | sort -Property key$enstr = $nullforeach($arr in $newarray){ $enstr += $arr.key + "=" + $arr.value + "&"}$enstr = $enstr -replace "\&$",""$sign = RSASign $enstr -PemPath $PemPath$inputobject.sign = $sign$newarray = $inputobject.GetEnumerator() | sort -Property key$webURL = $baseurl + "/qiyeservice/api/account/getAccount?"foreach($arr in $newarray){ $webURL += $arr.key + "=" + $arr.value + "&"}$webURL = $webURL -replace "\&$",""$hearder = @{"Content-Type" = "text/html; charset=utf-8"}$invoke = Invoke-RestMethod -Method POST -Uri "$webURL" -Headers $hearderreturn $invoke}
获取Zoom 用户
function get-zoomusers{param([Parameter(Mandatory=$true)][ValidateSet("active","inactive","pending")] $status,[Parameter(Mandatory=$true)] $page_size=30,[Parameter(Mandatory=$true)] $page_number=1)$getjwtfile = $folder + "\get_jwt_token.py"$apikey = "apikey"$secret = "secret"$token = python "$getjwtfile" "$apikey" "$secret"$authorization = "Bearer " + $token$headers = @{ 'authorization'= $authorization 'content-type'= "application/json;charset=UTF-8"}$url = "= @{ 'status'= $status 'page_size'= $page_size 'page_number'= 1}$invokeinfo = Invoke-RestMethod -Uri $url -Body $params -Headers $headersreturn $invokeinfo}
Graph API Header
function Graph_Auth_MAPI{$clientID = "clientID" $tenantName = "tenantname.onmicrosoft.com"$ClientSecret = "secert"$Username = "account"$Password = "password"$ReqTokenBody = @{ Grant_Type = "Password" client_Id = $clientID Client_Secret = $clientSecret Username = $Username Password = $Password Scope = "$TokenResponse = Invoke-RestMethod -Uri "-Method POST -Body $ReqTokenBody$headerParams = @{"Content-Type" = "application/json""Authorization"="$($TokenResponse.token_type) $($TokenResponse.access_token)"}return $headerParams}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~