Pi cryptography

Richard Suchenwirth 2013-07-25 - Here is a little experiment with using a substring of the (first 1000) digits of pi as a very simple one-time pad for rot-n encryption.

 set pi [join {
 141592653589793238462643383279502884197169399375105 
 82097494459230781640628620899862803482534211706798 
 21480865132823066470938446095505822317253594081284 
 81117450284102701938521105559644622948954930381964 
 42881097566593344612847564823378678316527120190914 
 56485669234603486104543266482133936072602491412737 
 24587006606315588174881520920962829254091715364367 
 89259036001133053054882046652138414695194151160943 
 30572703657595919530921861173819326117931051185480 
 74462379962749567351885752724891227938183011949129 
 83367336244065664308602139494639522473719070217986 
 09437027705392171762931767523846748184676694051320 
 00568127145263560827785771342757789609173637178721 
 46844090122495343014654958537105079227968925892354 
 20199561121290219608640344181598136297747713099605 
 18707211349999998372978049951059731732816096318595 
 02445945534690830264252230825334468503526193118817 
 10100031378387528865875332083814206171776691473035 
 98253490428755468731159562863882353787593751957781 
 8577805321712268066130019278766111959092164201989  
 } ""]
 proc picryp {str pad {sgn ""}} {
        set res ""
        foreach char [split $str ""] digit [split $pad ""] {
                append res [rot $char $sgn$digit]
        }
        return $res
 }
 proc rot {char amount} {
   set alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
     set pos [string first $char $alphabet]
     return [expr {$pos == -1 ? $char : [string index $alphabet [expr {($pos + $amount)%[string length $alphabet]}]]}]
 }

Testing:

 % set cr [picryp "Hello Tcl world" [string range $pi 42 end]]
 KnuoveUcqhyoAsh

For decrypting, add a minus sign as last argument:

 % picryp $cr [string range $pi 42 end]] -
 Hello Tcl world

Sender and receiver must only keep the integer secret. A codebreaker can of course use brute force and try all substrings of the pi digits (of course, millions of them are available on the Web) until the decrypted result makes sense, so best use this only as a wrapper around some other encryption...