require_relative '../data_conversion' module Ccrypto class SecretKey include Java::DataConversion def initialize(algo, keysize, key) @algo = algo @keysize = keysize @native_key = key @native_key = to_jce_secret_key end def to_jce_secret_key case @native_key when javax.crypto.spec.SecretKeySpec @native_key when ::Java::byte[] javax.crypto.spec.SecretKeySpec.new(@native_key, @algo.to_s) when String javax.crypto.spec.SecretKeySpec.new(to_java_bytes(@native_key), @algo.to_s) else case @native_key.ccrypto_key when javax.crypto.spec.SecretKeySpec @native_key.ccrypto_key when ::Java::byte[] javax.crypto.spec.SecretKeySpec.new(@native_key.ccrypto_key, @algo.to_s) when Ccrypto::SecretKey @native_key.ccrypto_key.native_key else raise Ccrypto::Error, "Unknown key to conver to jce #{@native_key.ccrypto_key}" end end end def to_bin case @native_key when javax.crypto.spec.SecretKeySpec @native_key.encoded else raise Ccrypto::Error, "Unsupported key type #{@native_key.class}" end end def length case @native_key when javax.crypto.spec.SecretKeySpec @native_key.encoded.length when ::Java::byte[], String @native_key.length else @native_key.key.encoded.length end end def equals?(key) case key when Ccrypto::SecretKey logger.debug "Given key is Ccrypto::SecretKey" to_jce_secret_key.encoded == key.to_jce_secret_key.encoded when javax.crypto.spec.SecretKeySpec logger.debug "Given key is java SecretKeySpec" to_jce_secret_key.encoded == key.encoded when ::Java::byte[] to_jce_secret_key.encoded == key when String to_jce_secret_key.encoded == to_java_bytes(key) else logger.debug "Not sure how to compare : #{self} / #{key}" to_jce_secret_key == key end end def ==(val) self.equals?(val) end private def logger Ccrypto::Java.logger(:seckey) end end end