use logstash filter ,aes gcm encrypted in ruby,but cannot decrypted in java

53 views Asked by At

ruby class LogStash::Filters::Cipher < LogStash::Filters::Base begin data = event.get(@source) if @mode == "encrypt" @random_iv = OpenSSL::Random.random_bytes(@iv_random_length) end @cipher.iv = @random_iv result = @cipher.update(data)[email protected] if @mode == "encrypt" if !@random_iv.nil? result = @random_iv + result end if @algorithm.downcase.include? "gcm" or @algorithm.downcase.include? "ccm" result = result + @cipher.auth_tag @logger.info("Cipher auth_tag length: ", :auth_tag_length => @cipher.auth_tag.length) @logger.info(' auth_tag '+Base64.strict_encode64(@cipher.auth_tag)) end result = Base64.strict_encode64(result).encode("utf-8") if @base64 == true end @logger.debug("Cipher algorithm: ", :algorithm => @algorithm) rescue => e # force a re-initialize on error to be safe init_cipher

    else
      @total_cipher_uses += 1

      result = result.force_encoding("utf-8")
  end # def filter
  def init_cipher

    if [email protected]?
      @cipher.reset
      @cipher = nil
    end
    @cipher = OpenSSL::Cipher::AES.new(128, :GCM)
    @total_cipher_uses = 0

    if @mode == "encrypt"
      @cipher.encrypt
    end

    if @key.length != @key_size
      @logger.debug("key length is " + @key.length.to_s + ", padding it to " + @key_size.to_s + " with '" + @key_pad.to_s + "'")
      @key = @key[0,@key_size].ljust(@key_size,@key_pad)
    end
    @cipher.key = @key
    @cipher.padding = @cipher_padding if @cipher_padding
    @cipher.padding=0
    if @algorithm.downcase.include? "gcm"
      @cipher.auth_data = @auth_data
      @logger.info("Cipher initialisation auth_data: ", :auth_data => @auth_data)
    end
  end # def init_cipher
end # class LogStash::Filters::Cipher

java:

    byte[] textBytes = Base64.getDecoder().decode(text);
    byte[] iv = new byte[16];
    ByteBuffer bb = ByteBuffer.wrap(textBytes);
    bb.get(iv);
    byte[] cipherText = new byte[bb.remaining()];
    bb.get(cipherText);
    try {
        Cipher cipher = Cipher.getInstance(mode);
        SecretKeySpec secretKeySpec = getSecretKeySpec(key);
        GCMParameterSpec gcmParameterSpec=new GCMParameterSpec(128, textBytes,0,16);
        System.out.println(Base64.getEncoder().encodeToString(gcmParameterSpec.getIV()));
        System.out.println(gcmParameterSpec.getTLen());
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec);
        cipher.updateAAD("".getBytes());
        byte[] decryptedBytes = cipher.doFinal(textBytes,16,textBytes.length-16);

        return new String(decryptedBytes, StandardCharsets.UTF_8);

I have put iv and auth_tag in ciphertext, and split iv in java, but still tag mismatch.

I test it in nodejs, it works ok. The ciphertext that nodejs encrypt can be decrypted in java.

new GCMParameterSpec(128, textBytes,0,16) I tried to change to new GCMParameterSpec(96, textBytes,0,16)

0

There are 0 answers