Skip to content

Instantly share code, notes, and snippets.

@heavysixer
Created August 10, 2016 05:28
Show Gist options
  • Save heavysixer/d90f22fef5db1c61d5e3513754ff8259 to your computer and use it in GitHub Desktop.
Save heavysixer/d90f22fef5db1c61d5e3513754ff8259 to your computer and use it in GitHub Desktop.
A Book
# A simple Book Cipher
# https://en.wikipedia.org/wiki/Book_cipher
# input = <<EOF
# A book cipher is a cipher in which the key is some aspect of a book or other
# piece of text; books being common and widely available in modern times, users
# of book ciphers take the position that the details of the key are sufficiently
# well hidden from attackers in practice.
#EOF
# cipher = BookCipher.new
# encoded = cipher.encode(input)
#
# puts encoded.join(',')
# 5391,7036,5593,6738,698,6780,1939,5858,514,7374,7490,4842,3295,2173,3160,7562,2846,4042,1558,5318,2118,286,968,30,4051,6005,4617,7005,711,7589,6170,514,48,968,6572,6104,6133,4874,3030,5784,1521,7009,6416,5659,4555,2514,4188,1848,541,7378,4181,440,4979,190,7280,2873,934,2108,7320,7196,6057,5455,6154,6166,4393,2360,985,2202,5786,3468,3447,6179,6310,7355,3146,5105,6063,6642,6025,3203,3270,7027,3959,1111,6033,6282,5668,1162,455,877,1352,400,2251,5784,3316,4010,1246,4057,4221,6,2990,5352,118,4007,873,2448,3358,2488,2846,3991,5017,5102,7690,2094,2165,7476,2247,5909,7416,6869,4244,1385,2573,6642,3213,3430,4402,1391,1040,1419,2659,7151,7412,2100,2616,5279,6476,4074,6365,4752,4931,7575,4672,4883,2095,1650,4612,5617,1108,3021,1606,3967,5214,2461,6208,66,2589,1191,6014,1169,3951,7430,6392,6067,3970,1233,796,5138,7671,312,2,3405,3703,399,456,4834,2733,5879,2027,4689,2951,3391,2283,517,5238,998,1308,2521,1343,4232,3829,7241,799,1016,1959,5618,5966,2057,104,1045,5950,2004,2125,3180,4232,1183,7012,2890,7409,5784,3597,4500,3179,3852,750,2817,2239,7290,3407,1976,1292,1383,1317,493,554,655,2254,2630,5331,4696,6515,3270,2704,4065,2417,7614,1577,4465,5591,6167,1074,601,2803,6370,3267,309,5144,1367,410,4575,5516,3992,3993,5599,2823,5529,5675,1772,4558,5686,6463,7556,4525,7264,634,6800,2130,2226
#
#puts cipher.decode(encoded)
# a book cipher is a cipher in which the key is some aspect of a book or otherpiece of text books being common and widely available in modern times usersof book ciphers take the position that the details of the key are sufficiently well hidden from attackers in practice
class BookCipher
def initialize(book = nil)
default= <<EOF
When, in the course of human events, it becomes necessary for one people to
dissolve the political bonds which have connected them with another, and to
assume among the powers of the earth, the separate and equal station to which
the laws of nature and of nature's God entitle them, a decent respect to the
opinions of mankind requires that they should declare the causes which impel
them to the separation. We hold these truths to be self-evident, that all men
are created equal, that they are endowed by their Creator with certain
unalienable rights, that among these are life, liberty and the pursuit of
happiness. That to secure these rights, governments are instituted among men,
deriving their just powers from the consent of the governed. That whenever any
form of government becomes destructive to these ends, it is the right of the
people to alter or to abolish it, and to institute new government, laying its
foundation on such principles and organizing its powers in such form, as to them
shall seem most likely to effect their safety and happiness. Prudence, indeed,
will dictate that governments long established should not be changed for light
and transient causes; and accordingly all experience hath shown that mankind are
more disposed to suffer, while evils are sufferable, than to right themselves by
abolishing the forms to which they are accustomed. But when a long train of
abuses and usurpations, pursuing invariably the same object evinces a design to
reduce them under absolute despotism, it is their right, it is their duty, to
throw off such government, and to provide new guards for their future security.
Such has been the patient sufferance of these colonies; and such is now the
necessity which constrains them to alter their former systems of government.
The history of the present King of Great Britain is a history of repeated
injuries and usurpations, all having in direct object the establishment of an
absolute tyranny over these states. To prove this, let facts be submitted to a
candid world. He has refused his assent to laws, the most wholesome and
necessary for the public good. He has forbidden his governors to pass laws of
immediate and pressing importance, unless suspended in their operation till his
assent should be obtained; and when so suspended, he has utterly neglected to
attend to them. He has refused to pass other laws for the accommodation of large
districts of people, unless those people would relinquish the right of
representation in the legislature, a right inestimable to them and formidable to
tyrants only. He has called together legislative bodies at places unusual,
uncomfortable, and distant from the depository of their public records, for the
sole purpose of fatiguing them into compliance with his measures. He has
dissolved representative houses repeatedly, for opposing with manly firmness his
invasions on the rights of the people. He has refused for a long time, after
such dissolutions, to cause others to be elected; whereby the legislative
powers, incapable of annihilation, have returned to the people at large for
their exercise; the state remaining in the meantime exposed to all the dangers
of invasion from without, and convulsions within. He has endeavored to prevent
the population of these states; for that purpose obstructing the laws for
naturalization of foreigners; refusing to pass others to encourage their
migration hither, and raising the conditions of new appropriations of lands. He
has obstructed the administration of justice, by refusing his assent to laws
for establishing judiciary powers. He has made judges dependent on his will
alone, for the tenure of their offices, and the amount and payment of their
salaries. He has erected a multitude of new offices, and sent hither swarms of
officers to harass our people, and eat out their substance. He has kept among
us, in times of peace, standing armies without the consent of our legislature.
He has affected to render the military independent of and superior to civil
power. He has combined with others to subject us to a jurisdiction foreign to
our constitution, and unacknowledged by our laws; giving his assent to their
acts of pretended legislation: For quartering large bodies of armed troops among
us: For protecting them, by mock trial, from punishment for any murders which
they should commit on the inhabitants of these states: For cutting off our trade
with all parts of the world: For imposing taxes on us without our consent: For
depriving us in many cases, of the benefits of trial by jury: For transporting
us beyond seas to be tried for pretended offenses: For abolishing the free
system of English laws in a neighboring province, establishing therein an
arbitrary government, and enlarging its boundaries so as to render it at once an
example and fit instrument for introducing the same absolute rule in these
colonies: For taking away our charters, abolishing our most valuable laws, and
altering fundamentally the forms of our governments: For suspending our own
legislatures, and declaring themselves invested with power to legislate for us
in all cases whatsoever. He has abdicated government here, by declaring us out
of his protection and waging war against us. He has plundered our seas, ravaged
our coasts, burned our towns, and destroyed the lives of our people. He is at
this time transporting large armies of foreign mercenaries to complete the works
of death, desolation and tyranny, already begun with circumstances of cruelty
and perfidy scarcely paralleled in the most barbarous ages, and totally unworthy
the head of a civilized nation. He has constrained our fellow citizens taken
captive on the high seas to bear arms against their country, to become the
executioners of their friends and brethren, or to fall themselves by their
hands. He has excited domestic insurrections amongst us, and has endeavored to
bring on the inhabitants of our frontiers, the merciless Indian savages, whose
known rule of warfare, is undistinguished destruction of all ages, sexes and
conditions. In Jefferson's draft there is a part on slavery here In every stage
of these oppressions we have petitioned for redress in the most humble terms:
our repeated petitions have been answered only by repeated injury. A prince,
whose character is thus marked by every act which may define a tyrant, is unfit
to be the ruler of a free people. Nor have we been wanting in attention to our
British brethren. We have warned them from time to time of attempts by their
legislature to extend an unwarrantable jurisdiction over us. We have reminded
them of the circumstances of our emigration and settlement here. We have
appealed to their native justice and magnanimity, and we have conjured them by
the ties of our common kindred to disavow these usurpations, which, would
inevitably interrupt our connections and correspondence. We must, therefore,
acquiesce in the necessity, which denounces our separation, and hold them, as
we hold the rest of mankind, enemies in war, in peace friends. We, therefore,
the representatives of the United States of America, in General Congress,
assembled, appealing to the Supreme Judge of the world for the rectitude of our
intentions, do, in the name, and by the authority of the good people of these
colonies, solemnly publish and declare, that these united colonies are, and of
right ought to be free and independent states; that they are absolved from all
allegiance to the British Crown, and that all political connection between them
and the state of Great Britain, is and ought to be totally dissolved; and that
as free and independent states, they have full power to levy war, conclude
peace, contract alliances, establish commerce, and to do all other acts and
things which independent states may of right do. And for the support of this
declaration, with a firm reliance on the protection of Divine Providence, we
mutually pledge to each other our lives, our fortunes and our sacred honor.
EOF
@text = normalize(book || default)
@table = build_table(@text)
end
def build_table(text)
table = {}
chars = ('a'..'z').to_a
chars << [' ']
chars.flatten!
chars.each do |x|
table[x] = text.enum_for(:scan,/#{x}/).map { Regexp.last_match.begin(0) }
end
table
end
def normalize(str)
str.gsub(/[^a-z ]/i, '')
end
def encode(str)
encoded = []
normalize(str).split('').each do |s|
key = s.downcase
sample = [@table[key]].flatten.sample.to_i
encoded << sample
end
encoded
end
def decode(encoded)
encoded.map do |n|
@text[n]
end.join('')
rescue
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment