繁体   English   中英

导入jar文件到ruby脚本

[英]Importing jar file to ruby script

这是我的 ruby 脚本:

需要'java'

require_relative 'hmac_utility.jar'

dec_obj = Java::Hmac_utility::Hmac_utility.new

明文 = dec_obj.decrypt_ruby(event.get('encypted_secret_pass'), event.get('gcm_key'))

这个脚本位于一个 maven 项目中,我在其中导入了 hmac_utility jar 文件。

这是我的 java class 来自 jar 文件(这是我第一次制作 jar 文件,不确定如果我需要使用来自该类的另一个 function,主要方法将如何工作)

公共 class hmac_decryptor {

private static final Charset UTF_8 = StandardCharsets.UTF_8;
private static final int TAG_LENGTH_BIT = 128;
private static final int IV_LENGTH_BYTE = 12;
private static final int SALT_LENGTH_BYTE = 16;
private static final String CIPHER_INSTANCE = "AES/GCM/NoPadding";
private static final String HASH_ALGO = "PBKDF2WithHmacSHA256";

public static void main(String[] args) {
}

public static String decrypt_ruby(String cText, String syslogKey) {
    try {
        byte[] decode = Base64.getDecoder().decode(cText.getBytes(UTF_8));
        ByteBuffer bb = ByteBuffer.wrap(decode);
        byte[] iv = new byte[IV_LENGTH_BYTE];
        bb.get(iv);
        byte[] salt = new byte[SALT_LENGTH_BYTE];
        bb.get(salt);
        byte[] cipherText = new byte[bb.remaining()];
        bb.get(cipherText);
        SecretKey aesKeyFromPassword = getAESKeyFromPassword(syslogKey.toCharArray(), salt);
        Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
        cipher.init(Cipher.DECRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
        byte[] plainText = cipher.doFinal(cipherText);

        return new String(plainText, UTF_8);
    }
    catch(Exception e) {
        return null;
    }
}

public static SecretKey getAESKeyFromPassword(char[] password, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGO);
    KeySpec spec = new PBEKeySpec(password, salt, 2048, 256);
    SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
    return secret;
}

}

现在我的问题是我是否正确设置了 class 以用作 jar 文件,并且在 ruby 脚本中我是否以正确的方式使用 decrypt_ruby 方法?

如果你想从 Ruby 引用 Java 代码,你最好的选择是 JRuby。 请注意,JRuby 基本上是 MRI 的替代品(Ruby 的 C 实现),因此您可能需要以不同的方式执行脚本。

https://www.jruby.org/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM