Skip to content

Instantly share code, notes, and snippets.

@sdogruyol
Created February 17, 2017 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sdogruyol/feb7042e68efe992a9f5d518634f8898 to your computer and use it in GitHub Desktop.
Save sdogruyol/feb7042e68efe992a9f5d518634f8898 to your computer and use it in GitHub Desktop.
require "openssl"
require "openssl/cipher"
require "openssl/hmac"
struct Slice
def self.from_hex(data : String)
buffer = Slice(UInt8).new(data.bytesize / 2)
i = 0
data.each_char.each_slice(2) do |(high, low)|
high = from_hex high
low = from_hex low
byte = (high << 4) + low
buffer[i] = byte
i += 1
end
buffer
end
private def self.from_hex(char)
byte = char.ord
byte -= 32 if byte >= 97 # upcase
byte -= 7 if byte >= 65 # remove non-hex gap
byte -= 48
raise ArgumentError.new("invalid hex #{char}") unless 0 <= byte <= 16
byte.to_u8
end
end
IV = "00000000000000000000000000000000"
# IV = UInt8.slice(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
CLIENT_ID = "34700515"
MAC_KEY = "C86984730E13686A0F069AE8CA71D8DA"
# MAC_KEY = UInt8.slice(200, 105, 132, 115, 14, 19, 104, 106, 15, 6, 154, 232, 202, 113, 216, 218)
ENCRYPTION_KEY = "911E1B7118F559896A5CB11048871781"
# ENCRYPTION_KEY = UInt8.slice(145, 30, 27, 113, 24, 245, 89, 137, 106, 92, 177, 16, 72, 135, 23, 129)
def generate_token
request_time = "20160201182241"
timezone = "03"
reference_no = "123"
phone_number = "905065707769"
data = CLIENT_ID + timezone + request_time.to_s + length(phone_number) + phone_number + length(reference_no.to_s) + reference_no.to_s
if data.size < 64
padding_length = 64 - data.size
data += '8'
padding_length = 64 - data.size
padding_length.times { data += '0' }
end
data
end
def encrypt(data)
data = Slice.from_hex data
encryption_key = Slice.from_hex ENCRYPTION_KEY
iv = Slice.from_hex IV
cipher = OpenSSL::Cipher.new("aes-128-cbc")
cipher.encrypt
cipher.key = encryption_key
cipher.iv = iv
encrypted_data = cipher.update data
upcased = encrypted_data.hexstring.upcase
hmac = OpenSSL::HMAC.hexdigest(:sha1, MAC_KEY, upcased)
(upcased + hmac).upcase
end
def length(no)
if no.size < 10
'0' + no.size.to_s
else
no.size.to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment