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