Skip to content

Instantly share code, notes, and snippets.

@jesobreira
Created August 28, 2016 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesobreira/c73c9d114bad13a995ecef671e52f8ee to your computer and use it in GitHub Desktop.
Save jesobreira/c73c9d114bad13a995ecef671e52f8ee to your computer and use it in GitHub Desktop.
AutoIt RSA
#include <Array.au3>
#Region Math
; http://sabemosdetudo.com/ciencias/ask67749-O_que_sao_numeros_relativamente_primos.html
Func RelativelyPrime($x, $y)
Return gdc($x, $y) = 1
EndFunc
; http://stackoverflow.com/a/21480873
Func gdc($a, $b)
Local $gdc = 0
While $b <> 0
$gdc = $b
$b = Mod($a, $b)
$a = $gdc
WEnd
Return $gdc
EndFunc
; https://rosettacode.org/wiki/Least_common_multiple
Func lcm($m, $n)
Return Abs($m * $n)/gdc($m, $n)
EndFunc
#EndRegion
#Region UDF
; http://mathaware.org/mam/06/Kaliski.pdf
Func _RSA_GenKeyPair()
; Generate a pair of large, random primes p and q
$p = 5
$q = 11
; Compute the modulus n as n = pq.
$n = Abs($p*$q)
; Select an odd public exponent e between 3 and n-1 that is relatively prime to p-1 and q-1.
For $i = 3 To $n-1 Step +2
If RelativelyPrime($i, $p-1) And RelativelyPrime($i, $q-1) Then
$e = $i
ExitLoop
EndIf
Next
; Compute the private exponent d from e, p and q. (See appendix)
$L = lcm($p-1, $q-1)
msgbox(0, 'L', $L)
$d = Mod($e^-1, 20) ; buggy, should be 7, not 0.333, and it should be inverse mod, not mod
msgbox(0, 'd', $d)
; Output (n, e) as the public key and (n, d) as the private key.
Local $aReturn[3]
$aReturn[0] = $n
$aReturn[1] = $e
$aReturn[2] = $d
Return $aReturn
EndFunc
Func _RSA_Encrypt($m, $mKeypairOr_e, $i_n = Default)
If IsArray($mKeypairOr_e) Then
$e = $mKeypairOr_e[1]
$n = $mKeypairOr_e[0]
Else
$e = $mKeypairOr_e
$n = $i_n
EndIf
$c = Mod($m^$e, $n)
Return $c
EndFunc
Func _RSA_Decrypt($c, $mKeypairOr_d, $i_n = Default)
If IsArray($mKeypairOr_d) Then
$d = $mKeypairOr_d[2]
$n = $mKeypairOr_d[0]
Else
$d = $mKeypairOr_d
$n = $i_n
EndIf
$m = Mod($c^$d, $n)
EndFunc
#EndRegion
$keypair = _RSA_GenKeyPair()
_ArrayDisplay($keypair)
$m = 4
$encoded = _RSA_Encrypt($m, $keypair)
msgbox(0, '', $encoded)
$decoded = _RSA_Decrypt($encoded, $keypair)
msgbox(0, '', $decoded)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment