Reputation: 160
Im newbie in BrightScript,
I would like to know how to encrypt the string. can you give me an example?
This is my code
esn = m.constants.deviceSerialID
How to encrypt the result of this?
i got research but i don't know how to use and how to put the code
https://sdkdocs.roku.com/display/sdkdoc/ifEVPCipher
Upvotes: 2
Views: 684
Reputation: 1643
Simple way with static IV (initialisation vector):
esn = m.constants.deviceSerialID
Function encrypt(args as Object) as String
iv = "f6a42a2960d374b82d7b333814cbaf8c"
cipher = CreateObject("roEVPCipher")
cipher.setup(true, "aes-256-cbc", args.key, iv, 1)
ba = CreateObject("roByteArray")
ba.FromAsciiString(args.data)
result = cipher.process(ba)
return result.ToBase64String()
End Function
encryptedString = encrypt({
key: "<symmetrical-secret-key>"
data: esn
})
The IV is just a random hex string. In this example you would need to have the same IV and secret key to decrypt the message back. The problem here is that static IVs mean we are less secure than we could be. To make this more secure you could make the IV non-static.
esn = m.constants.deviceSerialID
Function generateHexString(length As Integer) As String
hexChars = "0123456789abcdef"
hexString = ""
For i = 1 to length
hexString = hexString + hexChars.Mid(Rnd(length / 2) - 1, 1)
End for
Return hexString
End Function
Function encrypt(args as Object) as String
iv = generateHexString(32)
cipher = CreateObject("roEVPCipher")
cipher.setup(true, "aes-256-cbc", args.key, iv, 1)
ba = CreateObject("roByteArray")
ba.FromAsciiString(args.data)
result = cipher.process(ba)
' Append the IV to the front of the message
return iv + result.ToBase64String()
End Function
encryptedString = encrypt({
key: "<symmetrical-secret-key>"
data: esn
})
Now the IV changes each time you encrypt, much safer. When you come to decrypt the message you know the IV is the first 32 characters so you remove that and use it as the IV to decrypt.
Upvotes: 1