Instantly share code, notes, and snippets.
-
Save Eric-Guo/3a9446bb91100809820d0d448c94bb2b to your computer and use it in GitHub Desktop.
rails session encrypt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"crypto/hmac" | |
"crypto/sha1" | |
"crypto/aes" | |
"crypto/cipher" | |
"encoding/base64" | |
"encoding/hex" | |
"encoding/json" | |
"net/url" | |
"strings" | |
"strconv" | |
"golang.org/x/crypto/pbkdf2" | |
) | |
const ( | |
keyIterNum = 1000 | |
keySize = 64 | |
) | |
func generateKey(base, salt string) []byte { | |
return pbkdf2.Key([]byte(base), []byte(salt), keyIterNum, keySize, sha1.New) | |
} | |
func main() { | |
cookieContent := "dDdjMW5jYUNYaFpBT1BSdFgwQkk4ZWNlT214L1FnM0pyZzZ1d21nSnVTTm9zS0ljN000S1JmT3cxcTNtRld2Ny0tQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09--75d8323b0f0e41cf4d5aabee1b229b1be76b83b6" | |
var err error | |
var unescapedCookieContent string | |
if unescapedCookieContent, err = url.QueryUnescape(cookieContent); err != nil { | |
panic(err) | |
} | |
encryptedDataSignVectors := strings.SplitN(unescapedCookieContent, "--", 2) | |
encryptedData := encryptedDataSignVectors[0] | |
sign := encryptedDataSignVectors[1] | |
fmt.Printf("encrypted_data = %v\n", encryptedData) | |
fmt.Printf("sign = %v\n", sign) | |
secretKeyBase := "development_secret" | |
defaultSignSalt := "signed encrypted cookie" | |
signKey := generateKey(secretKeyBase, defaultSignSalt) | |
signHmac := hmac.New(sha1.New, signKey) | |
signHmac.Write([]byte(encryptedData)) | |
verifySign := signHmac.Sum(nil) | |
fmt.Printf("verifySign = %v\n", hex.EncodeToString(verifySign)) | |
var signDecoded []byte | |
if signDecoded, err = hex.DecodeString(sign); err != nil { | |
panic(err) | |
} | |
if !hmac.Equal(verifySign, signDecoded) { | |
panic(fmt.Errorf("verification failed")) | |
} | |
var encryptedDataBase64Decoded []byte | |
if encryptedDataBase64Decoded, err = base64.StdEncoding.DecodeString(encryptedData); err != nil { | |
panic(err) | |
} | |
encryptedContentIvVectors := strings.SplitN(string(encryptedDataBase64Decoded), "--", 2) | |
var encryptedContent []byte | |
var iv []byte | |
if encryptedContent, err = base64.StdEncoding.DecodeString(encryptedContentIvVectors[0]); err != nil { | |
panic(err) | |
} | |
if iv, err = base64.StdEncoding.DecodeString(encryptedContentIvVectors[1]); err != nil { | |
panic(err) | |
} | |
fmt.Printf("encrypted_content = %s\n", base64.StdEncoding.EncodeToString(encryptedContent)) | |
fmt.Printf("iv = %v\n", iv) | |
defaultSalt := "encrypted cookie" | |
encryptKey := generateKey(secretKeyBase, defaultSalt)[:32] | |
c, err := aes.NewCipher(encryptKey) | |
if err != nil { | |
panic(err) | |
} | |
cfb := cipher.NewCBCDecrypter(c, iv) | |
paddedSession := make([]byte, len(encryptedContent)) | |
cfb.CryptBlocks(paddedSession, encryptedContent) | |
fmt.Printf("padded_session = %s\n", strconv.QuoteToASCII(string(paddedSession))) | |
padding := int(paddedSession[len(paddedSession) - 1]) | |
sessionJSON := string(paddedSession[:(len(paddedSession) - padding)]) | |
fmt.Printf("session_json = %s\n", sessionJSON) | |
var jsonData map[string]interface{} | |
if err := json.Unmarshal([]byte(sessionJSON), &jsonData); err != nil { | |
panic(err) | |
} | |
fmt.Printf("%+v\n", jsonData) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
session = { "warden.user.user.key" => [[1],"secret"] } | |
require 'json' | |
session_json = JSON.dump(session) | |
puts session_json.inspect | |
def padding(data, block_size = 16) | |
n = block_size - data.bytesize % block_size | |
return data.force_encoding('ASCII-8BIT') + n.chr * n | |
end | |
padded_session = padding() | |
puts padded_session.inspect | |
require 'openssl' | |
require 'base64' | |
SECRET_KEY_BASE = "development_secret" | |
DEFAULT_SALT = "encrypted cookie" | |
DEFAULT_SIGN_SALT = "signed encrypted cookie" | |
DEFAULT_ITER = 1000 | |
DEFAULT_KEYLEN = 64 | |
def generate_key(secret_key_base, salt, iter = DEFAULT_ITER, keylen = DEFAULT_KEYLEN) | |
OpenSSL::PKCS5.pbkdf2_hmac_sha1(secret_key_base, salt, iter, keylen) | |
end | |
encrypt_key = generate_key(SECRET_KEY_BASE, DEFAULT_SALT)[0...32] | |
puts Base64.strict_encode64(encrypt_key) | |
cipher = OpenSSL::Cipher.new("aes-256-cbc") | |
cipher.encrypt | |
cipher.key = encrypt_key | |
iv = "\0" * 16 | |
# iv = cipher.random_iv | |
encrypted_content = cipher.update(session_json) | |
encrypted_content << cipher.final | |
puts Base64.strict_encode64(encrypted_content) | |
encrypted_data = Base64.strict_encode64( | |
Base64.strict_encode64(encrypted_content) + | |
"--" + | |
Base64.strict_encode64(iv) | |
) | |
puts encrypted_data | |
sign_key = generate_key(SECRET_KEY_BASE, DEFAULT_SIGN_SALT) | |
sign = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, sign_key, encrypted_data) | |
puts sign | |
require "uri" | |
cookie_content = URI.encode_www_form_component(encrypted_data + "--" + sign) | |
puts cookie_content | |
# If use ActiveSupport | |
# require "active_support/key_generator" | |
# require "active_support/message_encryptor" | |
# encrypt_key = ActiveSupport::KeyGenerator.new(SECRET_KEY_BASE, iterations: DEFAULT_ITER).generate_key(DEFAULT_SALT, 32) | |
# sign_key = ActiveSupport::KeyGenerator.new(SECRET_KEY_BASE, iterations: DEFAULT_ITER).generate_key(DEFAULT_SIGN_SALT, 64) | |
# encryptor = ActiveSupport::MessageEncryptor.new(encrypt_key, sign_key, serializer: JSON) | |
# puts encryptor.encrypt_and_sign(session) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment