One-time pad: Difference between revisions

→‎Python: I didn't realize it was better to use multiple lines of import statements rather than comma-separated import statements. I am changing this back to import on different lines based on a suggestion from PyCharm Professional.
(J)
imported>EliteSuperiorIntelligenceSocialStandingWealthPowerfulRichGiftedEducatedUpperClassUpperCrustCrèmedelaCrème
(→‎Python: I didn't realize it was better to use multiple lines of import statements rather than comma-separated import statements. I am changing this back to import on different lines based on a suggestion from PyCharm Professional.)
 
(5 intermediate revisions by 3 users not shown)
Line 42:
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 385:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 393:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">-- To compile into an executable:
-- ghc -main-is OneTimePad OneTimePad.hs
-- To run:
Line 564:
-- Decrypt first parameter's contents, using the second parameter as a key.
decrypt :: T.Text -> T.Text -> T.Text
decrypt = crypt ((((+65) . flip mod 26) .) . (-))</langsyntaxhighlight>
 
{{out}}
Line 620:
Implementation (assumes linux and also uses ascii85 encoding to avoid character set problems):
 
<langsyntaxhighlight Jlang="j">require'convert/misc/vig convert/misc/ascii85'
randseq=: {{ 2!:0'dd 2>/dev/null if=/dev/urandom count=1 bs=',":y }}
genpad=: {{ EMPTY [ (randseq y) fwrite x }}
encrypt=: {{ toascii85 (fread x) 0 vig a. y }}
decrypt=: {{ (fread x) 1 vig a. fromascii85 y }}</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight Jlang="j"> 'example' genpad 1000
'example' encrypt 'this is a test'
hc>*>I2nEB,6b#MdE;~>
 
'example' decrypt 'hc>*>I2nEB,6b#MdE;~>'
this is a test</langsyntaxhighlight>
 
One time pads are files, and can managed by linux file utilities (<code>ls</code>, <code>mv</code>, <code>rm</code>, ...).
Line 642:
Implementation also includes the start and end ASCII characters. One usage shows support for uppercase only, a second usage shows allowing spaces, upper case, and lower case in the input text.
 
<langsyntaxhighlight lang="java">
import java.io.BufferedReader;
import java.io.BufferedWriter;
Line 769:
 
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 815:
=={{header|Kotlin}}==
This uses the JDK's SecureRandom class for generating cryptographically strong random numbers. For convenience all three sub-tasks are catered for by a single, menu-based, program.
<langsyntaxhighlight lang="scala">// version 1.2.31
 
import java.io.File
Line 1,056:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,155:
{{trans|Python}}
{{libheader|nimcrypto}}
<langsyntaxhighlight Nimlang="nim">import os, re, sequtils, strformat, strutils
import nimcrypto
 
Line 1,383:
 
else:
padPath.writePad(length, keySize)</langsyntaxhighlight>
 
{{out}}
Line 1,429:
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl"># 20200814 added Perl programming solution
 
use strict;
Line 1,445:
print "Ord(Cipher) : ", ( map { ord($_).' ' } (split //, $cipher) ) , "\n";
 
print "Decoded : ", OTP( $otp, $cipher, 1 ), "\n";</langsyntaxhighlight>
{{out}}
<pre>Message : show me the monKey
Line 1,458:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
"""One-time pad using an XOR cipher. Requires Python >=3.6."""
 
Line 1,467:
import secrets
import sys
 
 
# One-time pad file signature.
Line 1,476 ⟶ 1,475:
"""Generate ``n`` secure, random keys of ``size`` bytes."""
# We're generating and storing keys in their hexadecimal form to make
# one-time pad files a little more human -readable and to ensure a key
# can not start with a hyphen.
return (secrets.token_hex(size) for _ in range(n))
Line 1,549 ⟶ 1,548:
Args:
path (pathlib.Path): Path to write one-time pad to.
lengthpad_size (int): NumberThe number of keys (or pages) in the pad.
key_size (int): The number of bytes per key.
"""
if path.exists():
Line 1,656:
else:
write_pad(pad, args.length, args.key_size)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,730:
This is a fairly basic otp file generator. Uses Crypt::Random for decently high quality random numbers. (Random bytes are drawn from /dev/urandom on Unix-like systems, and CryptGenRandom() on Windows.) It will ask for a file name to save to, and the number of lines you want. Each line can be used to encode up to 48 characters of data. Default is 1000 lines, Only generating 4 lines here for demonstration purposes. Saving the file to 'rosettacode.1tp'.
 
<syntaxhighlight lang="raku" perl6line>sub MAIN {
put "Generate data for one time pad encryption.\n" ~
"File will have .1tp extension.";
Line 1,758:
xx $lines).join;
}
}</langsyntaxhighlight>
{{out}}
<pre>Generate data for one time pad encryption.
Line 1,779:
One-time-pad encryption gets it's security from the fact that the pads are used '''one time'''. As a line is used in the otp file, it needs to be marked as used, or removed so it doesn't get reused. Theoretically, you would make a copy of rosettacode.1tp and send it by secure means to the receiver of your encrypted text so that they can use it to decrypt. Since we are encrypting and decrypting on the same computer, we'll make a copy of the otp file named rosettacopy.1tp and use that for decryption so the encrypt and decrypt functions don't conflict.
 
<syntaxhighlight lang="raku" perl6line>sub s2v ($s) { $s.uc.comb(/ <[ A..Z ]> /)».ord »-» 65 }
sub v2s (@v) { (@v »%» 26 »+» 65)».chr.join }
 
Line 1,830:
say "Secret:\n$secret\n\nEncrypted:";
say my $encrypted = otp-encrypt $secret, $otp-encrypt-fn;
say "\nDecrypted:\n", otp-decrypt $encrypted, $otp-decrypt-fn;</langsyntaxhighlight>
 
{{out}}
Line 1,858:
With "randInt" from Tcl'ers wiki [http://wiki.tcl.tk/29163 Cryptographically secure random numbers using /dev/urandom]
 
<langsyntaxhighlight Tcllang="tcl">puts "# True random chars for one-time pad"
 
proc randInt { min max } {
Line 1,903:
close $fh
 
puts "# Done."</langsyntaxhighlight>
 
{{out}}
Line 1,955:
{{libheader|Wren-dynamic}}
{{libheader|Wren-str}}
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File, Directory
import "./srandom" for SRandom
import "./ioutil" for FileUtil, Input
import "./dynamic" for Enum
import "./str" for Char, Str
 
var CHARS_PER_LINE = 48
Line 2,149:
return // Quit
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,243:
 
=={{header|TypeScript}}==
<langsyntaxhighlight lang="typescript">
#!/usr/bin/env node
import { writeFileSync, existsSync, readFileSync, unlinkSync } from 'node:fs';
Line 2,553:
 
main();
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,594:
fileName.key
_________________________________________________
€d_Z�d_Z²\]«UV¯rjraIfRdlµkfY]coa
_________________________________________________
</pre>