ruby 代码使用 java keystore,jks
java部分代码:
String encBusiData = DataSecurityUtil.encrypt(jsonString.getBytes("UTF-8"), configABS.getValue("jks_key"));
public static String encrypt(byte[] oriByte, String keyStr) throws Exception { try { byte[] sealTxt = null; SecretKey key = getKey(keyStr); Cipher cipher = null; try { cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); sealTxt = cipher.doFinal(oriByte); BASE64Encoder encoder = new BASE64Encoder(); String ret = encoder.encode(sealTxt); return ret; } catch (Exception e) { throw new Exception("E000035", e); } finally { cipher = null; } } catch (Exception ee) { throw new Exception(ee); } }
ruby 代码实现如下:
ruby需要使用gem 'keystores'
def signature(bussiness_data) keystore = OpenSSL::JKS.new key_store_password = store_password keystore.load("#{Rails.root}/config/certs/credoo_stg.jks", key_store_password) private_key = keystore.get_key(store_alias, store_password) rkey = OpenSSL::PKey::RSA.new private_key sign = rkey.sign('SHA1', bussiness_data.force_encoding("utf-8")) signature = Base64.strict_encode64(sign) return convert_n(signature) 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 void verifyData(String data, String signValue) throws Exception { try { PublicKey key = getPublicKey(); Signature sig = Signature.getInstance("SHA1WithRSA"); sig.initVerify(key); sig.update(data.getBytes("utf-8")); BASE64Decoder decoder = new BASE64Decoder(); byte[] signValueByte = decoder.decodeBuffer(signValue); if (!sig.verify(signValueByte)) { throw new Exception("E000013"); } System.out.println("验签OK!"); } catch (Exception e) { throw new Exception("E000014", e); } }
ruby代码的实现如下:
def rsa_verify(data, sign_value) public_key = OpenSSL::X509::Certificate.new(File.read("#{Rails.root}/config/certs/credoo_stg.cer")).public_key rsa = OpenSSL::PKey::RSA.new(public_key) rsa.verify("SHA1", Base64.decode64(sign_value), data) end