RSA code: Difference between revisions
m
→{{header|Wren}}: Minor tidy
Alextretyak (talk | contribs) (Added 11l) |
m (→{{header|Wren}}: Minor tidy) |
||
(10 intermediate revisions by 8 users not shown) | |||
Line 21:
: <math>d\times e \equiv 1 \mod (p-1)\times(q-1)</math>
The security of the code is based on the secrecy of the Private Key (decryption exponent) “<math>d</math>” and the difficulty in factoring “<math>n</math>”. Research into RSA facilitated advances in factoring and a number of [http://www.rsa.com/rsalabs/node.asp?id=2092 factoring challenges].
'''Summary of the task requirements:'''
Line 41:
{{trans|D}}
<
V e = BigInt(65537)
V d = BigInt(‘5617843187844953170308463622230283376298685’)
Line 63:
dec I/= 256
print(‘Decoded number as text: ’reversed(decTxt))</
{{out}}
Line 77:
The code below uses a thik and a thin binding of gmp.
<
WITH GMP, GMP.Integers, Ada.Text_IO, GMP.Integers.Aliased_Internal_Value, Interfaces.C;
USE GMP, Gmp.Integers, Ada.Text_IO, Interfaces.C;
Line 116:
END;
END Main;
</syntaxhighlight>
{{out}}
Line 129:
The code below uses Algol 68 Genie which provides arbitrary precision arithmetic for LONG LONG modes.
<
COMMENT
First cut. Doesn't yet do blocking and deblocking. Also, as
Line 203:
print (number to string (mod power (ciphertext, d, n)))
END
</syntaxhighlight>
{{out}}
<pre>
Line 211:
=={{header|C}}==
{{libheader|GMP}}
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 246:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 258:
{{libheader|System.Numerics}}
<
using System.Numerics;
using System.Text;
Line 285:
Console.WriteLine("As ASCII: " + decoded);
}
}</
{{out}}
Line 297:
The string is encoded as follows: each character is converted into 2 digits based on ASCII value (subtracting 32, so that SPACE=00, and so on.) To decode we simply read every 2 digits from the given integer in order, adding 32 and converting back into characters.
<
(defparameter *e* 65537)
(defparameter *d* 5617843187844953170308463622230283376298685)
Line 329:
(defun decode-rsa (message)
(decode-string (mod-exp message *d* *n* 1)))
</syntaxhighlight>
Interpreter output (the star * represents the interpreter prompt):
<pre>
Line 346:
This used the D module of the Modular Exponentiation Task.
{{trans|Go}}
<
import std.stdio, std.bigint, std.algorithm, std.string, std.range,
modular_exponentiation;
Line 380:
decTxt ~= (dec & 0xff).toInt;
writeln("Decoded number as text: ", decTxt.retro);
}</
{{out}}
<pre>Plain text: Rosetta Code
Line 392:
{{Trans|Go}}
Thanks for Rudy Velthuis, BigIntegers library
<syntaxhighlight lang="delphi">
program RSA_code;
Line 537:
writeln('Decoded: ', RSA.Decode(Encoded));
Readln;
end.</
{{out}}
<pre>Plain text: Rosetta Code
Encoded: 916709442744356653386978770799029131264344
Decoded: Rosetta Code</pre>
=={{header|Erlang}}==
Solution split into 2 modules, the mod module does the modulo aritmetic as per separate Rosetta Code entry.
<syntaxhighlight lang="erlang">
%%% @author Tony Wallace <tony@tony.gen.nz>
%%% @doc
%%% For details of the algorithms used see
%%% https://en.wikipedia.org/wiki/Modular_exponentiation
%%% @end
%%% Created : 21 Jul 2021 by Tony Wallace <tony@resurrection>
-module mod.
-export [mod_mult/3,mod_exp/3,binary_exp/2,test/0].
mod_mult(I1,I2,Mod) when
I1 > Mod,
is_integer(I1), is_integer(I2), is_integer(Mod) ->
mod_mult(I1 rem Mod,I2,Mod);
mod_mult(I1,I2,Mod) when
I2 > Mod,
is_integer(I1), is_integer(I2), is_integer(Mod) ->
mod_mult(I1,I2 rem Mod,Mod);
mod_mult(I1,I2,Mod) when
is_integer(I1), is_integer(I2), is_integer(Mod) ->
(I1 * I2) rem Mod.
mod_exp(Base,Exp,Mod) when
is_integer(Base),
is_integer(Exp),
is_integer(Mod),
Base > 0,
Exp > 0,
Mod > 0 ->
binary_exp_mod(Base,Exp,Mod);
mod_exp(_,0,_) -> 1.
binary_exp(Base,Exponent) when
is_integer(Base),
is_integer(Exponent),
Base > 0,
Exponent > 0 ->
binary_exp(Base,Exponent,1);
binary_exp(_,0) ->
1.
binary_exp(_,0,Result) ->
Result;
binary_exp(Base,Exponent,Acc) ->
binary_exp(Base*Base,Exponent bsr 1,Acc * exp_factor(Base,Exponent)).
binary_exp_mod(Base,Exponent,Mod) ->
binary_exp_mod(Base rem Mod,Exponent,Mod,1).
binary_exp_mod(_,0,_,Result) ->
Result;
binary_exp_mod(Base,Exponent,Mod,Acc) ->
binary_exp_mod((Base*Base) rem Mod,
Exponent bsr 1,Mod,(Acc * exp_factor(Base,Exponent))rem Mod).
exp_factor(_,0) ->
1;
exp_factor(Base,1) ->
Base;
exp_factor(Base,Exponent) ->
exp_factor(Base,Exponent band 1).
test() ->
445 = mod_exp(4,13,497),
%% Rosetta code example:
R = 1527229998585248450016808958343740453059 =
mod_exp(2988348162058574136915891421498819466320163312926952423791023078876139,
2351399303373464486466122544523690094744975233415544072992656881240319,
binary_exp(10,40)),
R.
%%%-------------------------------------------------------------------
%%% @author Tony Wallace <tony@tony.gen.nz>
%%% @doc
%%% Blocking not implemented. Runtime exception if message too long
%%% Not a practical issue as RSA usually limited to symmetric key exchange
%%% However as a key exchange tool no advantage in compressing plaintext
%%% so that is not done either.
%%% @end
%%% Created : 24 Jul 2021 by Tony Wallace <tony@resurrection>
%%%-------------------------------------------------------------------
-module rsa.
-export([key_gen/2,encrypt/2,decrypt/2,test/0]).
-type key() :: {integer(),integer()}.
key_gen({N,D},E) ->
{{E,N},{D,N}}.
-spec encrypt(key(),integer()) -> integer().
encrypt({E,N},MessageInt)
when MessageInt < N ->
mod:mod_exp(MessageInt,E,N).
-spec decrypt(key(),integer()) -> integer().
decrypt({D,N},Message) ->
mod:mod_exp(Message,D,N).
test() ->
PlainText=10722935,
N = 9516311845790656153499716760847001433441357,
E = 65537,
D = 5617843187844953170308463622230283376298685,
{PublicKey,PrivateKey} = key_gen({N,D},E),
PlainText =:= decrypt(PrivateKey,
encrypt(PublicKey,PlainText)).
</syntaxhighlight>
Running test:
8> rsa:test().
rsa:test().
true
9>
=={{header|F Sharp|F#}}==
<
//Nigel Galloway February 12th., 2018
let RSA n g l = bigint.ModPow(l,n,g)
Line 553 ⟶ 667:
let m_out = Array.collect(fun n->Array.unfold(fun n->if n>0I then Some(byte(int (n%256I)),n/256I) else None) n|>Array.rev) g|>System.Text.Encoding.ASCII.GetString
printfn "'The magic words are SQUEAMISH OSSIFRAGE' as numbers -> %A\nEncrypted -> %A\nDecrypted -> %A\nAs text -> %A" m_in n g m_out
</syntaxhighlight>
{{out}}
<pre>
Line 564 ⟶ 678:
=={{header|FreeBASIC}}==
{{trans|C}}
<
' compile with: fbc -s console
Line 607 ⟶ 721:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre> Encoded: 916709442744356653386978770799029131264344
Line 616 ⟶ 730:
Note: see the [https://golang.org/pkg/crypto/rsa/ crypto/rsa] package
included with Go for a full implementation.
<
import (
Line 663 ⟶ 777:
}
fmt.Println("Decoded number as text:", string(db[dx:]))
}</
Output:
<pre>
Line 674 ⟶ 788:
=={{header|Haskell}}==
<
where
import Data.Char ( chr )
Line 719 ⟶ 833:
decrypted = decode $ rsa_decode d n rsa_encoded
putStrLn ("Encrypted: " ++ encrypted )
putStrLn ("And now decrypted: " ++ decrypted )</
{{out}}
<pre>Enter a test text!
Line 730 ⟶ 844:
Please read talk pages.
<
n := 9516311845790656153499716760847001433441357
Line 794 ⟶ 908:
every (m := 0) := !M + b * m
return m
end</
Output:
Line 834 ⟶ 948:
Note, for an implementation with blocking (and a much smaller key) see [http://rosettacode.org/mw/index.php?title=RSA_code&oldid=103802]
<
E=: 65537x
D=: 5617843187844953170308463622230283376298685x
Line 849 ⟶ 963:
25512506514985639724585018469
] final=: a. {~ 256x #.inv dec
Rosetta Code</
Note: as indicated at http://www.jsoftware.com/help/dictionary/special.htm, <code>N&|@^</code> does not bother with creating the exponential intermediate result.
Line 855 ⟶ 969:
=={{header|Java}}==
<
public static void main(String[] args) {
/*
Line 883 ⟶ 997:
System.out.println("As text: " + decText);
}
</syntaxhighlight>
===Alternative solution - convert to byte array then to BigInteger: ===
<
import java.math.BigInteger;
import java.util.Random;
Line 922 ⟶ 1,036:
}
}
</syntaxhighlight>
{{out}}
<pre>Message: 32745724963520459128167607565116331713761641910444445962992228853365120918629
Line 934 ⟶ 1,048:
Decrypted message(number form): 32745724963520459128167607565116331713761641910444445962992228853365120918629
Decrypted message(string): Hello World! - From Rosetta Code</pre>
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]] after correcting for a bug in the decode-to-text algorithm''' as of 2023-02-07
'''Works with gojq, the Go implementation of jq, and with fq'''
The following assumes unbounded-precision integer arithmetic.
<syntaxhighlight lang=jq>
# If $j is 0, then an error condition is raised;
# otherwise, assuming infinite-precision integer arithmetic,
# if the input and $j are integers, then the result will be an integer.
def idivide($j): (. - (. % $j)) / $j ;
# shift left
def left8: 256 * .;
# shift right
def right8: idivide(256);
def modPow($b; $e; $m):
if ($m == 1) then 0
else {b: ($b % $m), $e, r: 1}
| until( .e <= 0 or .return;
if .b == 0 then .return = 0
else if .e % 2 == 1 then .r = (.r * .b) % $m else . end
| .e |= idivide(2)
| .b = (.b * .b) % $m
end)
| if .return then .return else .r end
end;
# Convert the input integer to a stream of 8-bit integers, most significant first
def bytes:
def stream:
recurse(if . >= 256 then ./256|floor else empty end) | . % 256 ;
[stream] | reverse ;
# convert ASCII plain text to a number
def ptn:
reduce explode[] as $b (0; left8 + $b);
def n: 9516311845790656153499716760847001433441357;
def e: 65537;
def d: 5617843187844953170308463622230283376298685;
# encode a single number
def etn: . as $ptn | modPow($ptn; e; n);
# decode a single number
def dtn: . as $etn | modPow($etn; d; n);
def decode:
[recurse(right8 | select(.>0)) % 256]
| reverse
| implode;
def task($pt):
($pt|ptn) as $ptn
| if ($ptn >= n) then "Plain text message too long" | error else . end
| ($ptn|etn) as $etn
| ($etn|dtn) as $dtn
| ($ptn|decode) as $text
| "Plain text: : \($pt)",
"Plain text as a number : \($ptn)",
"Encoded : \($etn)",
"Decoded : \($dtn)",
"Decoded number as text : \($text)"
;
task("Rosetta Code"),
"",
task("Hello, Rosetta!!!!")
</syntaxhighlight>
'''Invocation''': gojq -nr -f rsa-code.jq
{{output}}
<pre>
Plain text: : Rosetta Code
Plain text as a number : 25512506514985639724585018469
Encoded : 916709442744356653386978770799029131264344
Decoded : 25512506514985639724585018469
Decoded number as text : Rosetta Code
Plain text: : Hello, Rosetta!!!!
Plain text as a number : 6306597225792201544376884997106189304144161
Encoded : 3763881655974029977658577646869029457590896
Decoded : 6306597225792201544376884997106189304144161
Decoded number as text : Hello, Rosetta!!!!
</pre>
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
bytes = parse(BigInt, "0x" * bytes2hex(collect(UInt8, clearmsg)))
return powermod(bytes, expub, nmod)
Line 955 ⟶ 1,157:
encoded = rsaencode(msg, nmod, expub)
decoded = rsadecode(encoded, nmod, dsecr)
println("\n# $msg\n -> ENCODED: $encoded\n -> DECODED: $decoded")</
{{out}}
Line 963 ⟶ 1,165:
=={{header|Kotlin}}==
<
import java.math.BigInteger
Line 990 ⟶ 1,192:
val decText = dec.toByteArray().toString(c)
println("As text : $decText")
}</
{{out}}
Line 1,001 ⟶ 1,203:
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Does not support blocking.
<syntaxhighlight lang="text">toNumPlTxt[s_] := FromDigits[ToCharacterCode[s], 256];
fromNumPlTxt[plTxt_] := FromCharacterCode[IntegerDigits[plTxt, 256]];
enc::longmess = "Message '``' is too long for n = ``.";
Line 1,022 ⟶ 1,224:
Print["Numeric plaintext: " <> IntegerString[toNumPlTxt[text]]];
Print["Encoded: " <> IntegerString[en]];
Print["Decoded: '" <> de <> "'"];</
{{out}}
<pre>Text: 'The cake is a lie!'
Line 1,033 ⟶ 1,235:
=={{header|Nim}}==
<
# nimble install stint
import stint
Line 1,082 ⟶ 1,284:
var deciphertext = translate(ciphertext, d, n, false)
echo(&"deciphered numerical plaintext in hex is:\n{deciphertext}")
echo(&"deciphered plaintext is:\n{parseHexStr(deciphertext)}\n\n")</
{{out}}
<pre>plaintext:
Line 1,157 ⟶ 1,359:
=={{header|PARI/GP}}==
<
n = 9516311845790656153499716760847001433441357;
Line 1,168 ⟶ 1,370:
encoded = lift(Mod(inttext, n) ^ e) \\ encrypted message
decoded = lift(Mod(encoded, n) ^ d) \\ decrypted message
message = Strchr(digits(decoded, 256)) \\ readable message</
Output:<pre>
Line 1,181 ⟶ 1,383:
As a check: it's easy to crack this weak encrypted message without knowing secret key 'd'
<
crack = Strchr(digits(lift(Mod(encoded,n) ^ lift(Mod(1,(f[1,1]-1)*(f[2,1]-1)) / e)),256))</
Output:<pre>crack: "Rosetta Code"</pre>
Line 1,189 ⟶ 1,391:
=={{header|Perl}}==
{{trans|Raku}}
<
$n = 9516311845790656153499716760847001433441357;
Line 1,251 ⟶ 1,453:
After exponentiation with SECRET exponent we get: $numeric_message2
This turns into the string $secret_message2
EOT</
{{out}}
<pre>Secret message is ROSETTA CODE
Line 1,264 ⟶ 1,466:
{{libheader|Phix/mpfr}}
{{trans|C}}
<!--<
<span style="color: #008080;">
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"65537"</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"5617843187844953170308463622230283376298685"</span><span style="color: #0000FF;">),</span>
Line 1,278 ⟶ 1,481:
<span style="color: #000000;">mpz_import</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pt</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">plaintext</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">plaintext</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #
<span style="color: #7060A8;">mpz_powm</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ct</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">pt</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">);</span>
Line 1,294 ⟶ 1,497:
<span style="color: #0000FF;">{</span><span style="color: #000000;">pt</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ct</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_free</span><span style="color: #0000FF;">({</span><span style="color: #000000;">pt</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ct</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">})</span>
<!--</
<small>(mpz_import() and mpz_export() are not supported under pwa/p2js)</small>
{{out}}
<pre>
Line 1,304 ⟶ 1,508:
=={{header|PicoLisp}}==
PicoLisp comes with an RSA library:
<
# Generate long random number
Line 1,419 ⟶ 1,623:
# Decrypt
: (pack (decrypt Keys CryptText))
-> "The quick brown fox jumped over the lazy dog's back"</
=={{header|PowerShell}}==
{{trans|C#}}
<syntaxhighlight lang="powershell">
$n = [BigInt]::Parse("9516311845790656153499716760847001433441357")
$e = [BigInt]::new(65537)
Line 1,437 ⟶ 1,641:
$decoded = [Text.ASCIIEncoding]::ASCII.GetString($dc.ToByteArray())
"As ASCII: $decoded"
</syntaxhighlight>
{{out}}
Line 1,448 ⟶ 1,652:
=={{header|Python}}==
<
n = 9516311845790656153499716760847001433441357 # p*q = modulus
Line 1,474 ⟶ 1,678:
print('message ', binascii.unhexlify(hex(decrypted_text)[2:]).decode()) # [2:] slicing, to strip the 0x part
</syntaxhighlight>
{{output}}
<pre>
Line 1,493 ⟶ 1,697:
Cutting messages into blocks has not been done.
<
(require math/number-theory)
(define-logger rsa)
Line 1,664 ⟶ 1,868:
EOS
plain-A-to-B signed-A-to-B unsigned-A-to-B crypt-signed-A-to-B decrypt-signed-A-to-B
decrypt-verified-B A-pvt-keys B-pvt-keys))</
{{out}}
Line 1,724 ⟶ 1,928:
=={{header|Raku}}==
(formerly Perl 6)
No blocking here. Algorithm doesn't really work if either red or black text begins with 'A'.
<syntaxhighlight lang="raku" line>class RSA-message {
has ($.n, $.e, $.d); # the 3 elements that define an RSA key
my @alphabet = |('A' .. 'Z'), ' ';
my $rad = +@alphabet;
my %code = @alphabet Z=> 0 .. *;
subset Text of Str where /^^ @alphabet+ $$/;
method encode(Text $t) {
[+] %code{$t.flip.comb} Z× (1, $rad, $rad×$rad … *);
}
method decode(Int $n is copy) {
gather loop {
$n div= $rad;
}
].join.flip;
}
}
constant $n = 9516311845790656153499716760847001433441357;
constant $e = 65537;
constant $d = 5617843187844953170308463622230283376298685;
my $fmt = "%48s %s\n";
my $message = 'ROSETTA CODE';
printf $fmt, 'Secret message is', $message;
my $rsa = RSA-message.new: n => $n, e => $e, d => $d;
printf $fmt, 'Secret message in integer form is',
my $numeric-message = $rsa.encode: $message;
printf $fmt, 'After exponentiation with public exponent we get',
my $numeric-cipher = expmod $numeric-message, $e, $n;
printf $fmt, 'This turns into the string',
my $text-cipher = $rsa.decode: $numeric-cipher;
printf $fmt, 'If we re-encode it in integer form we get',
my $numeric-cipher2 = $rsa.encode: $text-cipher;
printf $fmt, 'After exponentiation with SECRET exponent we get',
my $numeric-message2 = expmod $numeric-cipher2, $d, $n;
printf $fmt, 'This turns into the string',
my $message2 = $rsa.decode: $numeric-message2;
</syntaxhighlight>
{{out}}
<pre> Secret message is ROSETTA CODE
Secret message
After exponentiation with public exponent we get 8326171774113983822045243488956318758396426
This turns into the string ZULYDCEZOWTFXFRRNLIMGNUPHVCJSX
If we re-encode it in integer form we get 8326171774113983822045243488956318758396426
After exponentiation with SECRET exponent we get 97525102075211938
This turns into the string ROSETTA CODE</pre>
=={{header|Ruby}}==
<
#!/usr/bin/ruby
Line 1,838 ⟶ 2,047:
final = blocks_to_text(decoded)
print "Decrypted Message: "; puts final
</syntaxhighlight>
{{out}}
<pre>
Line 1,849 ⟶ 2,058:
=={{header|Rust}}==
<
extern crate num;
Line 1,904 ⟶ 2,113:
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,916 ⟶ 2,125:
=={{header|Scala}}==
The code below demonstrates RSA encryption and decryption in Scala. Text to integer encryption using ASCII code.
<syntaxhighlight lang="scala">
object RSA_saket{
val d = BigInt("5617843187844953170308463622230283376298685")
Line 1,949 ⟶ 2,158:
}
}
</syntaxhighlight>
{{out}}
Line 1,962 ⟶ 2,171:
=={{header|Seed7}}==
<
include "bigint.s7i";
include "bytedata.s7i";
Line 1,991 ⟶ 2,200:
writeln("Decoded number as text: " <& decodedText);
end if;
end func;</
{{out}}
Line 2,004 ⟶ 2,213:
=={{header|Sidef}}==
{{trans|Raku}}
<
const e = 65537
const d = 5617843187844953170308463622230283376298685
Line 2,048 ⟶ 2,257:
var secret_message2 = Message::decode(numeric_message2)
say "This turns into the string #{secret_message2}"</
{{out}}
<pre>
Line 2,062 ⟶ 2,271:
=={{header|Tcl}}==
This code is careful to avoid the assumption that the input string is in a single-byte encoding, instead forcing the encryption to be performed on the UTF-8 form of the text. <!-- NB: Doesn't print the intermediate encoded value; see talk page for discussion why. -->
<
# This is a straight-forward square-and-multiply implementation that relies on
Line 2,109 ⟶ 2,318:
set dec [rsa_decrypt $enc $privateKey]
puts "$input -> $enc -> $dec"
}</
Output:
<pre>
Line 2,119 ⟶ 2,328:
{{trans|C#}}
{{libheader|System.Numerics}}
<
Imports System.Numerics
Imports System.Text
Line 2,139 ⟶ 2,348:
Console.WriteLine("As ASCII: " & decoded)
End Sub
End Module</
{{out}}
<pre> Encoded: 6219A470D8B319A31C8E13F612B31337098F
Decoded: 2161747465736F52202C6F6C6C6548
As ASCII: Hello, Rosetta!</pre>
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="ecmascript">/*import math.big
fn main() {
//var bb, ptn, etn, dtn big.Int
pt := "Rosetta Code"
println("Plain text: $pt")
// a key set big enough to hold 16 bytes of plain text in
// a single block (to simplify the example) and also big enough
// to demonstrate efficiency of modular exponentiation.
n := big.integer_from_string("9516311845790656153499716760847001433441357")?
e := big.integer_from_string("65537")?
d := big.integer_from_string("5617843187844953170308463622230283376298685")?
mut ptn := big.zero_int
// convert plain text to a number
for b in pt.bytes() {
bb := big.integer_from_i64(i64(b))
ptn = ptn.lshift(8).bitwise_or(bb)
}
if ptn >= n {
println("Plain text message too long")
return
}
println("Plain text as a number:$ptn")
// encode a single number
etn := ptn.big_mod_pow(e,n)
println("Encoded: $etn")
// decode a single number
mut dtn := etn.big_mod_pow(d,n)
println("Decoded: $dtn")
// convert number to text
mut db := [16]u8{}
mut dx := 16
bff := big.integer_from_int(0xff)
for dtn.bit_len() > 0 {
dx--
bb := dtn.bitwise_and(bff)
db[dx] = u8(i64(bb.int()))
dtn = dtn.rshift(8)
println('${db[0..].bytestr()} ${dtn.bit_len()}')
}
println("Decoded number as text: ${db[dx..].bytestr()}")
}*/
import math.big
fn main() {
//var bb, ptn, etn, dtn big.Int
pt := "Hello World"
println("Plain text: $pt")
// a key set big enough to hold 16 bytes of plain text in
// a single block (to simplify the example) and also big enough
// to demonstrate efficiency of modular exponentiation.
n := big.integer_from_string("9516311845790656153499716760847001433441357")?
e := big.integer_from_string("65537")?
d := big.integer_from_string("5617843187844953170308463622230283376298685")?
mut ptn := big.zero_int
// convert plain text to a number
for b in pt.bytes() {
bb := big.integer_from_i64(i64(b))
ptn = ptn.lshift(8).bitwise_or(bb)
}
if ptn >= n {
println("Plain text message too long")
return
}
println("Plain text as a number:$ptn")
// encode a single number
etn := ptn.big_mod_pow(e,n)
println("Encoded: $etn")
// decode a single number
mut dtn := etn.big_mod_pow(d,n)
println("Decoded: $dtn")
// convert number to text
mut db := [16]u8{}
mut dx := 16
bff := big.integer_from_int(0xff)
for dtn.bit_len() > 0 {
dx--
bb := dtn.bitwise_and(bff)
db[dx] = u8(i64(bb.int()))
dtn = dtn.rshift(8)
}
println("Decoded number as text: ${db[dx..].bytestr()}")
}</syntaxhighlight>
{{out}}
<pre>
Plain text: Hello World
Plain text as a number:87521618088882533792115812
Encoded: 8455179966388263657372423602482472996174613
Decoded: 87521618088882533792115812
Decoded number as text: Hello World
</pre>
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-big}}
<
var pt = "Rosetta Code"
Line 2,185 ⟶ 2,498:
var s = ""
for (i in dx..15) s = s + String.fromByte(db[i])
System.print("Decoded number as text : %(s)")</
{{out}}
Line 2,200 ⟶ 2,513:
{{libheader|GMP}}
No blocking.
<
n:=BN("9516311845790656153499716760847001433441357");
Line 2,215 ⟶ 2,528:
pt =ct.powm(d,n); println("Decoded: ",pt);
txt:=pt.toData().text; // convert big int to bytes, treat as string
println("As String: ",txt);</
{{out}}
<pre>
|