how to sign a string with a private key - ruby-on-rails

I have a system that an supposed to give my partner a public key to decry-pt the text. What I want is how to sign that text using my private key. This is how am doing it but it has failed.
require 'openssl'
require 'base64'
require 'digest/sha1'
#date = Date.today.strftime("%m/%d/%Y")
text_to_sign = "#{#order.phone_no}" + "#{#order.name}" + "#{#order.pay_type}" + "#{#order.pay_type}" + "1" + "MABIRA" + "81W30DI846" + "#{#date}" + "PULL" + "1" + "#{#cart.total_price}" + "#{#order.phone_no}" + ""
cipher = OpenSSL::Cipher.new 'aes-256-cbc'
cipher.encrypt
cipher.key = cipher.random_key
cipher.iv = cipher.random_iv
encrypted = cipher.update(text_to_sign) + cipher.final
private_key = OpenSSL::PKey::RSA.new(File.read('Private.key'), password)
ciphertext = private_key.private_encrypt(encrypted)
ciphertext.encoding
signed_text = Base64.encode64(ciphertext).gsub("\n", '')
puts signed_text
signed_text

Related

Verification of signature failed Oauth 1 Upwork API

Hi I followed the upwork developers site and the twitter oauth signature generation document and I did the following:
timestamp = int(time.time())
nonce = ''.join([str(random.randint(0, 9)) for i in range(30)])
url = 'https://www.upwork.com/api/auth/v1/info.json'
quoted_url = quote('https://www.upwork.com/api/auth/v1/info.json')
to_hash = 'GET' + '&' + url + '&'
param_string = 'oauth_consumer_key=' + UPWORK_KEY + '&oauth_nonce=' + nonce + '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + str(timestamp) + '&oauth_token=' + ACCESS_TOKEN + '&oauth_verifier=' + UPWORK_VERIFIER
to_hash += quote(param_string)
hashed = hmac.new(UPWORK_SECRET + '&' + ACCESS_TOKEN_SECRET, to_hash, hashlib.sha256).hexdigest()
r = requests.get('https://www.upwork.com/api/auth/v1/info.json?oauth_consumer_key=' + UPWORK_KEY + '&oauth_signature=' + hashed + '&oauth_nonce=' + nonce + '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + str(timestamp) + '&oauth_token=' + ACCESS_TOKEN + '&oauth_verifier=' + UPWORK_VERIFIER)
r.text
But when I do this, I get:
u'{"server_time":1472207775,"error":{"status":401,"code":401,"message":"Verification of signature failed."}}'
However the following works fine:
client = upwork.Client(UPWORK_KEY, UPWORK_SECRET, oauth_access_token=ACCESS_TOKEN, oauth_access_token_secret=ACCESS_TOKEN_SECRET)
client.auth.get_info()
{u'info': {u'portrait_32_img': u'https://odesk-prod-portraits.s3.amazonaws.com/Users:dasugovinda:PortraitUrl_32?AWSAccessKeyId=1XVAX3FNQZAFC9GJCFR2&Expires=2147483647&Signature=77Ab%2BTxcps9PIYCfPIZZuDpXAiY%3D&1470127549683826', u'capacity': {u'buyer': u'yes', u'affiliate_manager': u'no', u'provider': u'yes'}, u'company_url': u'', u'has_agency': u'0', u'portrait_50_img': u'https://odesk-prod-portraits.s3.amazonaws.com/Users:dasugovinda:PortraitUrl_50?AWSAccessKeyId=1XVAX3FNQZAFC9GJCFR2&Expires=2147483647&Signature=K6Ea0Z6QSmBGcg%2BRCQUAvrai%2FKw%3D&1470127549683826', u'portrait_100_img': u'https://odesk-prod-portraits.s3.amazonaws.com/Users:dasugovinda:PortraitUrl_100?AWSAccessKeyId=1XVAX3FNQZAFC9GJCFR2&Expires=2147483647&Signature=Dht5wFsI%2FDpDDeURkY6KefP4yvc%3D&1470127549683826', u'location': {u'city': u'Santa Clara', u'state': u'CA', u'country': u'United States'}, u'ref': u'5356164', u'profile_url': u'https://www.upwork.com/users/~01d7463c22a4e5c195'}, u'auth_user': {u'timezone': u'America/Tijuana', u'first_name': u'Govinda', u'last_name': u'Dasu', u'timezone_offset': u'-25200'}, u'server_time': u'1472209119'}
Any ideas on what I'm doing wrong?
Thanks to the answer by #Blairg23 here, I figured out the following solution:
url = 'https://www.upwork.com/api/auth/v1/info.json'
auth = OAuth1(UPWORK_KEY, UPWORK_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
r = requests.get(url, auth=auth)
r.text
Just using an already-implemented version of oauth saves you a huge headache.

Rails: sending data to asana and getting a syntax error

assign task to Asana
require "rubygems"
require "JSON"
require "net/https"
api_key = "1wPBetR9.6bhINO7xO9ypG6iP2aYU8hx"
workspace_id = "5386494137624"
assignee = "craig#theaerialistpress.com"
# set up HTTPS connection
uri = URI.parse("https://app.asana.com/api/1.0/tasks")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
# set up the request
header = {
"Content-Type" => "application/json"
}
req = Net::HTTP::Post.new(uri.path, header)
req.basic_auth(api_key, '')
req.body = {
"data" => {
"workspace" => workspace_id,
"name" => "House Order: " + #order.name,
"assignee" => assignee,
"projects" => "35978729781365",
"notes" => "Name: " + #order.name +
"\nEmail: " + #order.email +
"\nEvent Date: " + #date.to_s +
"\nDesign: " + #order.design +
"\n\nPaper Color: " + #order.paper_color +
"\nFont #1: " + #order.font1 +
"\nFont #2: " + #order.font2 +
if #order.card_type1 != "none"
"\n\nCard #1: " + #order.card_type1 + "\nPaper Weight: " + #order.paper_weight1 + "\nQuantity: " + #order.quantity1 + "\nInk Color #1: " + #order.ink_color11 + "\nInk Color #2: " + #order.ink_color12 + "\nWording: " + #order.wording1 + "\nReturn Address Printing: " + #order.return_address1 + "\nGuest Address Printing: " + #order.guest_address1.to_s + "\nEnvelope Liners: " + #order.envelope_liners1
end
if #order.card_type2 != "none"
"\n\nCard #2: " + #order.card_type2 + "\nPaper Weight: " + #order.paper_weight2 + "\nQuantity: " + #order.quantity2 + "\nInk Color #2: " + #order.ink_color21 + "\nInk Color #2: " + #order.ink_color22 + "\nWording: " + #order.wording2 + "\nReturn Address Printing: " + #order.return_address2 + "\nGuest Address Printing: " + #order.guest_address2.to_s + "\nEnvelope Liners: " + #order.envelope_liners2
end
}
}.to_json()
# issue the request
res = http.start { |http| http.request(req) }
# output
body = JSON.parse(res.body)
if body['errors'] then
puts "Server returned an error: #{body['errors'][0]['message']}"
else
puts "Created task with id: #{body['data']['id']}"
end
I am getting a syntax error when I am using if statements inside the data I am sending to asana. I am very new at rails and not sure what I am doing wrong.
This is the error:
syntax error, unexpected keyword_if, expecting '}' if #order.card_type2 != "none" ^ /Users/craigrinde/Dropbox/top_secret/aerialist/app/controllers/orders_controller.rb:212: syntax error, unexpected '}', expecting keyword_end } ^

How to convert a string to a byte array in ruby on rails

I want to convert a string to a byte array before I can sign it with a private key but I have not done it before. My code is as below could anybody give me a clue on how I can do it. Thank you.
require 'openssl'
require 'base64'
require 'digest/sha1'
#date = Date.today.strftime("%m/%d/%Y")
text_to_sign = "#{#order.phone_no}" + "#{#order.name}" + "#{#order.pay_type}" + "#{#order.pay_type}" + "1" + "MABIRA" + "81W30DI846" + "#{#date}" + "PULL" + "1" + "#{#cart.total_price}" + "#{#order.phone_no}" + ""
password = 'secret'
#converting the string to byte array
byte[] buff => new byte[1024]
text = buff.text_to_sign
private_key = OpenSSL::PKey::RSA.new(File.read('Private.key'), password)
ciphertext = private_key.private_encrypt(text)
ciphertext.encoding
signed_text = Base64.encode64(ciphertext).gsub("\n", '')
puts signed_text
signed_text
Ruby has the bytes method and you can convert that to an array with to_a
http://www.ruby-doc.org/core-1.9.3/ARGF.html#method-i-bytes
string = 'some string'
byte_array = string.bytes.to_a
# [115, 111, 109, 101, 32, 115, 116, 114, 105, 110, 103]

How to sign a string in ruby on rails

I am designing a system in ruby on rails but I want to know how I can sign a text string using a private key. I am supposed to first encode text using ASCII byte array, then compute byte array hash value using SHA1 from a byte array, sign byte array of the hashed array using the private key, and then convert the signed array into base64 . This how am doing it.
require 'openssl'
require 'digest/sha1'
#date = Date.today.strftime("%m/%d/%Y")
text_to_sign = "#{#order.phone_no}" + "#{#order.name}" + "#{#order.pay_type}" + "#{#order.pay_type}" + "1" + "MABIRA" + "81W30DI846" + "#{#date}" + "PULL" + "1" + "#{#cart.total_price}" + "#{#order.phone_no}" + ""
password = 'mypassword'
hashed_text = Digest::SHA1.hexdigest(text_to_sign)
private_key = OpenSSL::PKey::RSA.new(File.read('Mabira.key'), password)
ciphertext = private_key.private_encrypt(hashed_text)
signed_text = [ciphertext].pack('m*')#encoding in base64
puts signed_text
signed_text
Any assistance is welcome.

Paypal Setexpresscheckout ItemDescription Grails

I can't set the item summary in set express checkoput. L_NAME0=A caused error
def strUsername = "***"
def strPassword = "***"
def strSignature = "***"
def strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature
def strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";
def user = session.userId +","+amt + "," + receiver + "," + address + "," + opt
def successUrl = '***
def cancelUrl = '***'
def strAPIVersion = "56.0"
def strNVP = strCredentials + "&METHOD=SetExpressCheckout&AMT=" + totalamount +"&PAYMENTACTION=Sale&RETURNURL="+ successUrl+"&CANCELURL="+ cancelUrl +"&CURRENCYCODE=SGD&ITEMAMT="+totalamount+"&L_NAME0=OHN&VERSION=" + strAPIVersion
Try updating def strAPIVersion = "56.0" to def strAPIVersion = "76.0" I think the advanced features a not available in the 56 version. I used the default set by Paypal as a test
&L_PAYMENTREQUEST_0_NAME0=10% Decaf Kona Blend Coffee
&L_PAYMENTREQUEST_0_NUMBER0=623083
&L_PAYMENTREQUEST_0_DESC0=Size: 8.8-oz
&L_PAYMENTREQUEST_0_AMT0=9.95
&L_PAYMENTREQUEST_0_QTY0=2
&L_PAYMENTREQUEST_0_NAME1=Coffee Filter bags
&L_PAYMENTREQUEST_0_NUMBER1=623084
&L_PAYMENTREQUEST_0_DESC1=Size: Two 24-piece boxes
&L_PAYMENTREQUEST_0_AMT1=39.70
&L_PAYMENTREQUEST_0_QTY1=2
&PAYMENTREQUEST_0_ITEMAMT=99.30
&PAYMENTREQUEST_0_TAXAMT=2.58
&PAYMENTREQUEST_0_SHIPPINGAMT=3.00
&PAYMENTREQUEST_0_HANDLINGAMT=2.99
&PAYMENTREQUEST_0_SHIPDISCAMT=-3.00
&PAYMENTREQUEST_0_INSURANCEAMT=1.00
&PAYMENTREQUEST_0_AMT=105.87
&ALLOWNOTE=1

Resources