Same command, different results?


(Alberto González Ramírez) #1

Hi everybody.
I am working on a script to get info from Spotify via Web API.
One of the steps to get the token requires the Base64 encode of the string ClientID:ClientSecret
If I execute the same command in Terminal and AppleScript, I get different results.

What am I doing wrong?
Any ASOC class to encode/decode strings?

Thanks in advance.


(Shane Stanley) #2

Try this:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set theValue to "6f0491fb94314482b9fbd874b3b83799:555de1baa87d4154b4d1a6a53dc788fb"
set encodedValue to my encodeBase64:theValue
set decodedValue to my decodeBase64:encodedValue

on encodeBase64:theString
	set theString to current application's NSString's stringWithString:theString
	set theData to theString's dataUsingEncoding:(current application's NSUTF8StringEncoding)
	return (theData's base64EncodedStringWithOptions:(current application's NSDataBase64Encoding64CharacterLineLength)) as text
end encodeBase64:

on decodeBase64:theString
	set theData to current application's NSData's alloc()'s initWithBase64EncodedString:theString options:(current application's NSDataBase64DecodingIgnoreUnknownCharacters)
	return (current application's NSString's alloc()'s initWithData:theData encoding:(current application's NSUTF8StringEncoding)) as text
end decodeBase64:

(Alberto González Ramírez) #3

Thanks @ShaneStanley .

It works as expected.

Just one question. After encoding, I think at character 64, there is a line break.
Is it posible to get the encoded string in just “one” line?


(Shane Stanley) #4

Sure – change the (current application's NSDataBase64Encoding64CharacterLineLength) to 0.