zoukankan      html  css  js  c++  java
  • ruby AES加密解密

      最近和京东合作做一个项目,在接口对接传递参数时,参数需要通过AES加密解密。

    本来想到用gem 'aescrypt'处理,但是aescrypt的编码方式用的base64,而京东那边用的是16进制。所以就自己写了加密解密方法。

    AES 加密

    def aes_encrypt(key, encrypted_string)
        aes = OpenSSL::Cipher::Cipher.new("AES-128-ECB")
        aes.encrypt
        aes.key = key
        txt = aes.update(encrypted_string) << aes.final
        txt.unpack('H*')[0].upcase
    end
    

      

    AES 解密

    def aes_dicrypt(key, dicrypted_string)
        aes = OpenSSL::Cipher::Cipher.new("AES-128-ECB")
        aes.decrypt
        aes.key = key
        aes.update([dicrypted_string].pack('H*')) << aes.final
    end
    

      

    其中参数key,是aes加密解密的秘钥。encrypted_string和dicrypted_string是加密和解密字符串。

    “AES-128-ECB”是秘钥长度算法模式,秘钥长度有128和256两种。算法模式有"CBC", "ECB","CFB","OFB"可以选择。

  • 相关阅读:
    Remove Linked List Elements
    Count Primes
    Isomorphic Strings
    Read N Characters Given Read4 II
    Word Ladder II Graph
    Word Ladder
    Binary Tree Right Side View
    House Robber
    Find non-overlap jobs with max cost
    Find Peak Element
  • 原文地址:https://www.cnblogs.com/wangyuyu/p/4950397.html
Copyright © 2011-2022 走看看