[英]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 實現),因此您可能需要以不同的方式執行腳本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.