Created
February 23, 2014 15:37
-
-
Save sambaiz/9172931 to your computer and use it in GitHub Desktop.
RSA暗号方式の復号@某ES-2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'uri' | |
require 'prime' | |
# RSA暗号 | |
# 公開鍵(E, N) | |
E = 47 #適当な正整数 | |
N = 323 #素数p * 素数q | |
D_RANGE = 1000 #秘密鍵の推定最大値(一応ループ回避) | |
def decryption(x, d) | |
return ((x.to_i ** d) % N).to_s(16) | |
end | |
p, q = -1, -1 | |
Prime.each((N/2) - 1) do |prime| | |
if N % prime == 0 | |
p = prime | |
q = N / prime | |
end | |
end | |
puts "p = #{p}, q = #{q}" | |
raise("N is not valid status") if p == -1 | |
lcm = (p-1).lcm(q-1) | |
p "lcm = #{lcm}" | |
for d in (0..D_RANGE+1) # d: 秘密鍵 | |
tmp = E * d | |
break if tmp % lcm == 1 | |
end | |
raise("Not found Secret key under #{D_RANGE}") if d == D_RANGE + 1 | |
puts "d = #{d}" | |
buf = "" | |
isTailPercent = true | |
File::open(ARGV[0]) {|file| | |
file.each {|line| | |
line = buf + line.strip | |
isTailPercent = (line[line.length-1] == '%') | |
line = line.split('%') | |
line = line[1..line.length-1] #1要素目は空になるため | |
i = -1 | |
loop do | |
i += 1 | |
break if i == line.length-1 | |
if (i + 1) % 3 == 0 | |
line[(i - 2)..i] = decryption(line[i-2], d), decryption(line[i-1], d), decryption(line[i], d) | |
print URI.decode('%' + line[(i - 2)..i].join("%")) | |
line = line[i+1..line.length-1] | |
i -= 3 | |
end | |
end | |
buf = (line.length >= 1 ? '%' : '') + line.join('%') + (isTailPercent ? '%' : '') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment