首页 > 编程语言 > 详细

ruby 重写 java SHA1WithRSA Signature

时间:2020-11-30 17:11:56      阅读:26      评论:0      收藏:0      [点我收藏+]

java 代码

    public static String signData(String data) throws Exception
    {
        try
        {
            PrivateKey key = getPrivateKey();

            Signature sig = Signature.getInstance("SHA1WithRSA");
            sig.initSign(key);
            sig.update(data.getBytes("utf-8"));
            byte[] sigBytes = sig.sign();
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encodeBuffer(sigBytes);
        } catch (Exception e)
        {
            throw new Exception("E000012", e);
        }
    }

Ruby代码:

    def encrypt_data(params)
      cipher = OpenSSL::Cipher.new("des-ede3")
      cipher.encrypt
      cipher.key = key
      crypt = cipher.update(params.to_json.to_s.force_encoding("utf-8"))
      crypt << cipher.final()
      crypt_string = (Base64.strict_encode64(crypt))
      return convert_n(crypt_string)
    end


    # java  base64 之后是76个字符换行 MIME:输出隐射到MIME友好格式。输出每行不超过76字符
    def convert_n(str)
      str_length = str.length
      if str_length > 76
        i = 1
        while (76 * i) < str_length
          str.insert(((76 * i) + i - 1), "\n")
          i = i + 1
        end
      end
      return str
    end

JAVA解密部分代码:

    public static String decrypt(String sealTxt, String keyStr) throws Exception
    {
        try
        {
            Cipher cipher = null;
            byte[] byteFina = null;
            SecretKey key = getKey(keyStr);
            try
            {
                cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, key);
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] sealByte = decoder.decodeBuffer(sealTxt);
                byteFina = cipher.doFinal(sealByte);
                return new String(byteFina, "utf-8");
            } catch (Exception e)
            {
                throw new Exception("E000034", e);
            }
            finally
            {
                cipher = null;
            }
        } catch (Exception ee)
        {
            throw new Exception(ee);
        }
    }

Ruby代码如下:

    def decrypt_data(data)
      cipher = OpenSSL::Cipher.new("des-ede3")
      cipher.decrypt
      cipher.key = key
      crypt = cipher.update(Base64.decode64(data))
      crypt << cipher.final()
      return crypt.to_s.force_encoding("utf-8")
    end

 

ruby 重写 java SHA1WithRSA Signature

原文:https://www.cnblogs.com/tomtang/p/14062107.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!