在rails中解码已签名的cookie?

时间:2015-05-12 06:35:27

标签: ruby-on-rails ruby base64 decoding

所以我有一个签名的cookie,其值为

IjVvVGdIOW1pUU44Qkk5NFZZUl9Udnci--a3c3b748fd207ba1c537b590dd458b4855677146

我需要对其进行解码并获得以下值

5oTgH9miQN8BI94VYR_Tvw

我试过像

这样的东西
Base64.decode64(cookie_value.split('--').first)

但它给了我错误的值,它在字符串中添加了这些该死的斜杠,所以我最终得到了

"\"5oTgH9miQN8BI94VYR_Tvw\"" 

3 个答案:

答案 0 :(得分:2)

  

但它给了我错误的价值,它添加了这些该死的斜线   字符串,所以我最终

     

"\"5oTgH9miQN8BI94VYR_Tvw\""

它没有添加任何斜杠。这里的问题是您返回的字符串包含在双引号"之间。 \"这里是转义字符。

下面:

Base64.decode64 "IjVvVGdIOW1pUU44Qkk5NFZZUl9Udnci"
# => "\"5oTgH9miQN8BI94VYR_Tvw\""
puts Base64.decode64 "IjVvVGdIOW1pUU44Qkk5NFZZUl9Udnci"
# "5oTgH9miQN8BI94VYR_Tvw"

因为问题是不受欢迎的"。您可以按如下方式删除它们:

Base64.decode64(cookie_value.split('--').first).chomp('"').reverse.chomp('"').reverse
# => "5oTgH9miQN8BI94VYR_Tvw"

答案 1 :(得分:1)

请试试这个

out <- structure(list(N = 1:6, VN = c("v1", "v3", "v6", "v7a", "v18", 
"v23"), T1 = c("bigby (wolf)", "white", "red (rose)", "piggy (straw)", 
"(curse) beast", "prince"), T2 = c("jack (bean)", "snow (dwarves)", 
"beard (blue)", "bhageera (jungle) mowgli (book)", "beauty", 
"glass (slipper)"), T3 = c("hk (34)", "VL (r45)", "tg (h5)", 
"tt (HG) (45)", "gh", "vlp"), Val = c(36, 25, 0.84, 12, 78, 258
), C = c("(wolf) (bean)", "(dwarves)", "(rose) (blue)", "(straw) (jungle) (book)", 
"(curse)", "(slipper)")), .Names = c("N", "VN", "T1", "T2", "T3", 
"Val", "C"), class = "data.frame", row.names = c(NA, -6L))
out
  N  VN            T1                              T2           T3    Val                       C
1 1  v1  bigby (wolf)                     jack (bean)      hk (34)  36.00           (wolf) (bean)
2 2  v3         white                  snow (dwarves)     VL (r45)  25.00               (dwarves)
3 3  v6    red (rose)                    beard (blue)      tg (h5)   0.84           (rose) (blue)
4 4 v7a piggy (straw) bhageera (jungle) mowgli (book) tt (HG) (45)  12.00 (straw) (jungle) (book)
5 5 v18 (curse) beast                          beauty           gh  78.00                 (curse)
6 6 v23        prince                 glass (slipper)          vlp 258.00               (slipper)

你也可以解密它。

require 'rack'

puts Rack::Session::Cookie::Base64::Marshal.new.decode("IjVvVGdIOW1pUU44Qkk5NFZZUl9Udnci")

答案 2 :(得分:1)

我最终使用了以下内容:

MultiJson.load(Base64.decode64(cookie_value.split('--').first))

可能只适用于rails 4.1 +,虽然我不确定