0

sorry for my english.

I'm interacting with the Azure admin rest API and I want to programmatically create a SAS token. In Azure documentation is explained for C # (I attach the code below) but I need to implement it in Python (I'm new) and I can't get the data encoding and signing process correctly, even though I've searched a lot of information and tested in some different ways. Could someone help me to "translate" this code?. Thank you very much.

c#

using System;   
using System.Text;   
using System.Globalization;   
using System.Security.Cryptography;   
  
public class Program   
{   
    public static void Main()   
    {   
        var id = "account-name";   
        var key = "account-key";   
        var expiry = DateTime.UtcNow.AddDays(10);   
        using (var encoder = new HMACSHA512(Encoding.UTF8.GetBytes(key)))   
        {   
            var dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture);   
            var hash = encoder.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));   
            var signature = Convert.ToBase64String(hash);   
            var encodedToken = string.Format("SharedAccessSignature uid={0}&ex={1:o}&sn={2}", id, expiry, signature);   
            Console.WriteLine(encodedToken);   
        }   
    }   
}  
Gaurav Mantri
  • 128,066
  • 12
  • 206
  • 241
GaJsu
  • 113
  • 1
  • 6
  • Please see if this helps: https://stackoverflow.com/questions/62523166/how-can-i-generate-an-azure-blob-sas-url-in-python – Gaurav Mantri Jul 10 '20 at 11:34
  • thanks, i have seen this post before but it did not work for me because I don´t have any blob container – GaJsu Jul 10 '20 at 11:42
  • Do you wish to create an Account Shared Access Signature? Please look at the SDK and you will find method for generating those as well. No need to write code for REST API wrapper in Python. It is already done in the SDK. – Gaurav Mantri Jul 10 '20 at 11:45
  • Yes, I want to create a Shared Access Signature because if I create manually In Azure Portal the token expires in one month and I don´t want to change it in the code all months. This SAS is created with an id and primary key that I obtained in Azure Portal. Thanks for the info, i will see the Azure SDK Library and I will try to get the correct way – GaJsu Jul 10 '20 at 11:59
  • Oh, one more thing. I am not sure if you shared your real account name/key in the question. If that's the case, please change them immediately. – Gaurav Mantri Jul 10 '20 at 12:05
  • Thanks for your interest. I never share any private key or id, this code is copied for Azure Documentation, you can see it in the link I attached in my question. Thanks a lot. – GaJsu Jul 10 '20 at 12:10

2 Answers2

1

Based on @GaJsu 's solution

Following is my solution:

import base64
import hmac
import hashlib
from datetime import datetime
from dateutil.relativedelta import relativedelta


identifier = 'the "Identifier" value in "management API" tab'
end_date = datetime.now() + relativedelta(months=+6)
expiry = f'{end_date.isoformat()}0Z'
key_azure = 'the key in "management API" tab, primary/secondary key'
string_to_sign = f'{identifier}\n{expiry}'
signature = (
    base64.b64encode(
        hmac.new(
            bytearray(key_azure, "utf-8"), 
            bytearray(string_to_sign,"utf-8") , 
            hashlib.sha512).digest()
    )
).decode("utf-8")
auth_sas = f"SharedAccessSignature uid={identifier}&ex={expiry}&sn={signature}"

han shih
  • 389
  • 1
  • 5
  • 13
0

Finally I can create the SAS token. Here is the code for the signature:

string_to_sign = '{}{}{}'.format(id_azure,'\n',expiry)

signature = (base64.b64encode(hmac.new(bytearray(key_azure, "utf-8") , bytearray(string_to_sign,"utf-8") , hashlib.sha512).digest())).decode("utf-8").replace("\n", "")
GaJsu
  • 113
  • 1
  • 6
  • Can you provide some detail about 'id_azure' and 'expiry'? How is the format of these strings? How to get the value from the Azure portal/generate them by myself? – han shih Jul 12 '21 at 06:58