------------------------------------------------------------
การใช้งาน public , private key
link git lab ในส่วน controller
https://gitlab.com/sovernut/select_webservice/blob/master/app/controllers/airwebservice_controller.rb
ทำการเปลี่ยนข้อมูลที่จะส่งให้อยู่ในรูป ข้อความ แทน xml
โดย โค้ดที่เกี่ยวของมีดังนี้
ฝั่ง server
ส่วนเข้า รหัส
def encrypt_asym(text)
file = File.join(Rails.root, 'app', 'keys', 'public_key2.pem')
public_key = OpenSSL::PKey::RSA.new(File.read(file))
encrypt = Base64.encode64(public_key.public_encrypt(text))
return encrypt
end
จะทำการ ใช้ public key ของฝั่ง client ที่มี ทำการเข้ารหัสข้อความและ คืนค่า ที่เข้ารหัสแล้ว
ส่วนที่เป็น service
soap_action "get_all_airinfo",
:args => nil,
:return => [ AirInfomationWithEncrypt ]
def get_all_airinfo
@posts = Airinfo.all
array_of_post = []
@posts.each do |post|
hsh = {}
hsh["no"] = post.no
hsh["date"] = post.date_t.iso8601(0)
hsh["temp"] = post.temperature
hsh["humid"] = post.humid
array_of_post.push(hsh)
end
builder = Nokogiri::XML::Builder.new do |xml|
xml.root do # Wrap everything in one element.
process_array('airinformation',array_of_post,xml)
end
end
string = builder.to_xml
new_hash = { :iv => "ok" , :data => encrypt_asym(string)}
render :soap => [ :airinfomationEncrypt => new_hash ]
end
โดยเนื้อหาหลักๆ จะอยู่ตรงสีแดง ที่ทำการแปลง xml เป็นก้อน string และทำการเข้า ขั้นตอน
เข้ารหัส และส่งกลับไปใน soap service นั่นเอง ในส่วนของ :return [ airInformationWithEncrypt ] นั้น
จะเชื่อมโยงกับ โมเดลข้อมูลดังนี้
class AirInfomationWithEncrypt < WashOut::Type
map :airinfomationEncrypt => { :iv => :string , :data => :string}
end
ซึ่งจะมีการตรวจสอบความถูกต้องอัตโนมัติ
ทางฝั่ง client นั้นจะทำการ ถอดรหัสดังนี้
require 'savon'
require 'pp'
require 'openssl'
require 'base64'
client = Savon::Client.new(wsdl: "http://airwebservice.herokuapp.com/airwebservice/wsdl")
result2 = client.call(:get_all_airinfo)
private_key = OpenSSL::PKey::RSA.new(File.read('private_key.pem'))
encrypt = result2["data"]
decrypt = private_key.private_decrypt encrypt
โดยใช้ private key ที่มี ถอดรหัสออกมา โดย encrypt คือตัวแปรที่เก็บข้อความที่เข้ารหัส
ที่ได้จาก ตัว service
**** การสร้างกุญแจ ****
ซึ่งหากใช้งานกุญแจ ที่มีความยาวไม่เพียงพอต่อข้อมูล แล้วละก็ จะทำให้ เกิด error ความยาวคีย์ได้
ซึ่ง เราจะใช้งาน key ที่ขนาด 16384 จากเดิมที่มี 2048 ทีมี error
ไปเป็น
ผล จากการนำข้อมูลที่เข้ารหัสไว้มาถอด
รูปข้อมูลที่เข้ารหัสแล้ว
"<?xml version=\"1.0\"?>\n<root>\n <airinformation>\n <no>1</no>\n <date>2018-10-21T07:47:00Z</date>\n <temp>30.0</temp>\n <humid>60.0</humid>\n </airinformation>\n <airinformation>\n <no>2</no>\n
<date>2018-10-21T07:49:00Z</date>\n <temp>28.0</temp>\n <humid>62.0</humid>\n </airinformation>\n <airinformation>\n <no>3</no>\n <date>2018-10-20T22:55:55Z</date>\n <temp>25.0</temp>\n <humid>55.0</humid>\n </airinformation>\n <airinformation>\n ….
ข้อมูลที่ถูกถอดออกมา มีความถูกต้องใช้งานได้จริง