Valtira Blog

Roku: Sign S3 URL

by Morgan Catlin - 18 Nov 2011, 13:26:50

Here's a BrightScript function to sign an S3 URL that expires in 4 hours:

Function signS3Url(bucket as Object, folder as Object, file as Object) As Object
    
    now = CreateObject("roDateTime")
    now.mark()
    
    hour = now.getHours()
    hour = hour + 4 ' expire in 4 hours
    
    day = now.getDayOfMonth()
    
    if hour > 24
        hour = hour - 24
        day = day + 1
    end if
    
    expireStr = now.getYear().toStr() + "-" + now.getMonth().toStr() + "-" + day.toStr() + " " + hour.toStr() + ":" + now.getMinutes().toStr() + ":00.000"
    now.fromISO8601String(expireStr)
    
    policy = "GET" + chr(10) + chr(10) + chr(10) + now.asSeconds().ToStr() + chr(10) + "/" + bucket + "/" + folder + "/" + urlEncode(file)
    
    hmac = CreateObject("roHMAC")
    signature_key = CreateObject("roByteArray")
    signature_key.fromAsciiString("YOUR SECRET KEY")
    signature = ""
    if hmac.setup("sha1", signature_key) = 0
             message = CreateObject("roByteArray")
             message.fromAsciiString(policy)
             result = hmac.process(message)
             signature = result.toBase64String()
    end if
    
    signature = urlEncode(signature)
    
return "https://s3.amazonaws.com/" + bucket + "/" + folder + "/" + urlEncode(file) + "?AWSAccessKeyId=YOURACCESSKEY&Expires=" + now.asSeconds().ToStr() + "&Signature=" + signature
End Function

Function urlEncode(toEncode As Object) As Object

    Http = CreateObject("roUrlTransfer")
    return Http.urlEncode(toEncode)

End Function

Categories

About Us

Valtira's team includes many bright people with useful opinions on the latest web technologies like HTML5 and cloud computing.