Module: NCipher::Convert

Included in:
NCipher
Defined in:
lib/n_cipher.rb

Overview

Note:

このモジュール内のメソッドはプライベートクラスメソッドに指定されているため、外部から呼び出すことはできない

実際の暗号化、復号化を行うメソッドが定義されているモジュール

Instance Method Summary collapse

Instance Method Details

#convert(mode, string, seed, delimiter) ⇒ String

実際の変換処理を行う

Parameters:

  • mode (Symbol)

    :encodeもしくは:decodeを指定

  • string (String)

    対象文字列

  • seed (String)

    シード値

  • delimiter (String)

    区切り文字

Returns:

  • (String)

    変換された文字列オブジェクト

Raises:

  • (ArgumentError)


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/n_cipher.rb', line 65

def convert(mode, string, seed, delimiter)
  fail ArgumentError, 'Seed and delimiter are duplicated.' unless (seed.chars & delimiter.chars).size.zero?
  fail ArgumentError, 'Character is duplicated in seed.' unless seed.size == seed.chars.uniq.size

  table = convert_table(mode.to_sym, seed)
  rtn = case mode
    when :encode
      string.unpack('U*').map {|ele| ele.to_s(seed.size).gsub(/./, table).concat(delimiter) }
    when :decode
      fail ArgumentError, 'Delimiter is not include in the cipher string.' unless string.match(delimiter)
      fail ArgumentError, 'Invalid cipher string.' unless (string.chars - "#{seed}#{delimiter}".chars).size.zero?
      string.split(delimiter).map {|ele| [ele.gsub(/./, table).to_i(seed.size)].pack('U') }
    end

  rtn.join
end

#convert_table(mode, seed) ⇒ Hash

シード値から変換テーブルを構築する

Examples:

convert_table(:encode, 'あいうえお')
#=> {"0"=>"あ", "1"=>"い", "2"=>"う", "3"=>"え", "4"=>"お"}

convert_table(:decode, 'あいうえお')
#=> {"あ"=>"0", "い"=>"1", "う"=>"2", "え"=>"3", "お"=>"4"}

Parameters:

  • mode (Symbol)

    :encodeもしくは:decodeを指定

  • seed (String)

    元となるシード値

Returns:

  • (Hash)

    変換テーブル

Raises:

  • (RangeError)

    シード値が2文字以下、もしくは36文字以上の場合



45
46
47
48
49
50
51
52
53
# File 'lib/n_cipher.rb', line 45

def convert_table(mode, seed)
  fail RangeError, 'Seed must be 2 to 36 characters.' unless seed.size.between?(2, 36)

  table = [*'0'..'9', *'a'..'z'].zip(seed.chars).reject(&:one?).to_h
  case mode
  when :encode then table
  when :decode then table.invert
  end
end