how to use RSA with Crypt.au3 ( or anything else )
-
Recently Browsing 0 members
No registered users viewing this page.
-
Similar Content
-
By TheXman
Encryption / Decryption / Hashing
Purpose
Cryptography API: Next Generation (CNG) is Microsoft's long-term replacement for their CryptoAPI. Microsoft's CNG is designed to be extensible at many levels and cryptography agnostic in behavior. Although the Crypt.au3 UDF lib that is installed with AutoIt3 still works perfectly, the advapi32.dll functions that it uses have been deprecated. In addition the Crypt.au3 UDF lib, as it is currently written, has a very limited ability to decrypt AES data that was not encrypted using Crypt.au3. That is because Crypt.au3 functions do not allow you to specify an actual key or initialization vector (IV). It only lets you specify data to be used to derive a key and uses a static IV. This UDF was created to offer a replacement for the deprecated functions used by Crypt.au3. According to Microsoft, deprecated functions may be removed in future release. It was also created to allow more flexibility in encryption/decryption and to expand the ability for users to implement cryptography in their scripts.
Description
This UDF implements some of Microsoft's Cryptography API: Next Generation (CNG) Win32 API functions. It implements functions to encrypt/decrypt text and files, generate hashes, derive keys using Password-Based Key Derivation Function 2 (PBKDF2), and has several cryptography-related helper functions. The UDF can implement any encryption/decryption algorithms and hashing algorithms that are supported by the installed cryptography providers on the PC in which it is running. Most, if not all, of the values that you would commonly use to specify that desired algorithms, key bit lengths, and other magic number type values, are already defined as constants or enums in the UDF file.
To flatten the learning curve, there is an example file that shows examples of all of the major functionality. This example file is not created to be an exhaustive set of how to implement each feature and parameter. It is designed to give you a template or guide to help you hit the ground running in terms of using the functions. I have tried to fully document the headers of all of the functions as well as the code within the functions themselves. As of v1.4.0, there is also a Help file that includes all of the functions, with examples.
Current UDF Functions
Algorithm-Specific Symmetric Encryption/Decryption Functions _CryptoNG_AES_CBC_EncryptData _CryptoNG_AES_CBC_DecryptData
_CryptoNG_AES_CBC_EncryptFile _CryptoNG_AES_CBC_DecryptFile
_CryptoNG_AES_ECB_EncryptData _CryptoNG_AES_ECB_DecryptData
_CryptoNG_AES_GCM_EncryptData _CryptoNG_AES_GCM_DecryptData
_CryptoNG_3DES_CBC_EncryptData _CryptoNG_3DES_CBC_DecryptData
_CryptoNG_3DES_CBC_EncryptFile _CryptoNG_3DES_CBC_DecryptFile
Generic Symmetric Encryption/Decryption Functions _CryptoNG_EncryptData _CryptoNG_DecryptData
_CryptoNG_EncryptFile _CryptoNG_DecryptFile
Hashing Functions _CryptoNG_HashData _CryptoNG_HashFile
_CryptoNG_PBKDF2
Asymmetric (Public/Private Key) Encryption/Decryption Functions _CryptoNG_RSA_CreateKeyPair
_CryptoNG_RSA_EncryptData _CryptoNG_RSA_DecryptData
Misc / Helper Functions _CryptoNG_CryptBinaryToString _CryptoNG_CryptStringToBinary
_CryptoNG_GenerateRandom
_CryptoNG_EnumAlgorithms _CryptoNG_EnumRegisteredProviders _CryptoNG_EnumKeyStorageProviders
_CryptoNG_LastErrorMessage
_CryptoNG_Version
Related Links
Cryptography API: Next Generation - Main Page
Cryptography API: Next Generation - Reference
Cryptography API: Next Generation - Primitives
Cryptography API: Next Generation - Cryptographic Algorithm Providers
-
By Beege
I found this article and enjoyed it so much I had play with some code since the numbers are small enough.
https://thatsmaths.com/2016/08/11/a-toy-example-of-rsa-encryption/
Standard Encryption's vs RSA Encryption (Public Key Encryption) Fundamental Differences
If you read that and couldn't immediately clarify the difference then let me blow your mind because its simple:
STANDARD ENCRYPTION'S:
ORIGINAL_DATA + Password(or KEY) = Encrypted DATA
Then to decrypt ->
Encrypted DATA + (SAME Password(or SAME KEY)) = ORIGINAL_DATA
RSA:
ORIGINAL_DATA + Password(or PUBLIC_KEY) = Encrypted DATA
Then to decrypt ->
Encrypted DATA + (DIFFERENT Password(or PRIVATE_KEY)) = ORIGINAL_DATA
Are we all caught up? Did the colors help? I think they did
That's crazy right? Don't answer. It is. And crazier its used EVERY TIME we make a secure connection to a server over the internet. But here's the craziest part to me that I recently got clarity on from the toy example and that is the simplicity of this very very very very important algorithm that has yet to be cracked (fingers crossed):
Mod($vData ^ $key, $n)
So ya. That's it. That's the magic algorithm. 3 values. Oh and $n is also a shared known value that will be in the certificate with the public key that your browser reads when it makes a connection:
That's just mind blowing to me so couldn't resist getting something going in AUT. After playing with this code, I got a much better understanding of how its not just that algorithm that makes this whole thing possible. The numbers that we pick to form the public key and n are just as important and also how important it is to be random!
Let me know if you have any problems. Enjoy!
#include <array.au3> _Toy_RSA_Example() ;https://thatsmaths.com/2016/08/11/a-toy-example-of-rsa-encryption/ Func _Toy_RSA_Example() Local $p, $q, $n, $nT, $e, $d Local $aPublicKeys, $aCrypt, $sDecrypt, $sMsg ;Pick two random primes (they will be between 1000-10000) $p = _GetRandomPrime() $q = _GetRandomPrime() $sMsg = 'p= %i \t\t| Prime 1 - [NOT SHARED!]\nq= %i \t\t| Prime 2 - [NOT SHARED!]\n' ;Calculate lowest common multiple $nT = _LCM($p - 1, $q - 1) $sMsg &= 'nT= %i \t| _LCM(p - 1,q - 1) - [NOT SHARED!]\n' ;Calculate n. This is a shared number $n = $p * $q $sMsg &= 'n= %i \t| p * q - [Shared]\n' ;Get a small random list of possible public keys to pick from. Only searching for 100ms $aPublicKeys = _GetPublicKeys($nT) _ArrayDisplay($aPublicKeys, "Possible Public Keys Found") ;Pick a random public (encryption) key from array $e = $aPublicKeys[Random(1, $aPublicKeys[0], 1)] $sMsg &= 'e= %i \t| Public (Encryption) Key - [Shared]\n' ;Generate our private (decryption) key $d = _GetPrivateKey($e, $nT) $sMsg &= 'd= %i \t| Private (Decryption) Key - [NOT SHARED!]\n' ;format our msg (rsa details) to encrypt $sMsg = StringFormat($sMsg, $p, $q, $nT, $n, $e, $d) ;encrypt message $aCrypt = _RSA($sMsg, $e, $n) _ArrayDisplay($aCrypt, 'Encrypted RSA messsage') ;Decrypt array back $sDecrypt = _RSA($aCrypt, $d, $n) MsgBox(0, 'Decrypted RSA messsage', $sDecrypt) EndFunc ;==>_Toy_RSA_Example ;Function will perfrom Mod($v ^ $key, $n) on each char/element. ;Excepts Arrays or Strings. If input is array a string is returned and vice versa. Func _RSA($vDat, $key, $n) Local $bIsStr = IsString($vDat) If $bIsStr Then $vDat = StringToASCIIArray($vDat) For $i = 0 To UBound($vDat) - 1 $vDat[$i] = _Modular($vDat[$i], $key, $n) Next Return $bIsStr ? $vDat : StringFromASCIIArray($vDat) EndFunc ;==>_RSA ;algorithm is from the book "Discrete Mathematics and Its Applications 5th Edition" by Kenneth H. Rosen. Func _Modular($iBase, $iExp, $iMod) ; Mod($v ^ $key, $n) Local $iPower = Mod($iBase, $iMod) Local $x = 1 For $i = 0 To (4 * 8) - 1 If BitAND(0x00000001, BitShift($iExp, $i)) Then $x = Mod(($x * $iPower), $iMod) EndIf $iPower = Mod(($iPower * $iPower), $iMod) Next Return $x EndFunc ;==>_Modular ;Generate a "random" list of possible valid public keys to choose from based on $nT Func _GetPublicKeys($nT, $iMs = 100) Do Local $aKeys[10000] = [0], $iTime = TimerInit() Local $i = (Mod(@SEC, 2) ? Int($nT / 2) : Int($nT / 4)) ; randomize where we start Do If _IsPrime($i) And _IsCoPrime($i, $nT) Then $aKeys[0] += 1 $aKeys[$aKeys[0]] = $i EndIf $i += (Mod(@MSEC, 2) ? 1 : 100) ; randomize step size Until ($i >= ($nT - 1)) Or (TimerDiff($iTime) > $iMs) ReDim $aKeys[$aKeys[0] + 1] Until $aKeys[0] > 5 ; Ive seen 200+ returned sometimes and 0 on others. Make sure we have at least a few choices Return $aKeys EndFunc ;==>_GetPublicKeys ;https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/ - _ModInverse(a,m) Func _GetPrivateKey($a, $m) If ($m = 1) Then Return 0 ; Local $t, $q, $y = 0, $x = 1, $m0 = $m While ($a > 1) $q = Int($a / $m) ;q is quotient $t = $m ; $m = Mod($a, $m) ;m is remainder now, process same as Euclid's algo $a = $t ; $t = $y ; $y = $x - $q * $y ;Update y and x $x = $t ; WEnd Return $x < 0 ? $x + $m0 : $x EndFunc ;==>_GetPrivateKey ;Pick the next nearest prime from a random number (or number you cho0se) Func _GetRandomPrime($iStart = Default) Local $iPrime = ($iStart = Default ? Random(1000, 10000, 1) : $iStart) Do $iPrime += 1 Until _IsPrime($iPrime) Return $iPrime EndFunc ;==>_GetRandomPrime #Region Math Functions Func _IsPrime($n) For $i = 2 To (Int($n ^ 0.5) + 1) If Mod($n, $i) = 0 Then Return False Next Return True EndFunc ;==>_IsPrime Func _IsCoPrime($a, $b) Return _GCD($a, $b) = 1 EndFunc ;==>_IsCoPrime Func _GCD($iX, $iY) Local $iM While 1 $iM = Mod($iX, $iY) If $iM = 0 Then Return $iY $iX = $iY $iY = $iM WEnd EndFunc ;==>_GCD Func _LCM($iX, $iY) Return ($iX * $iY) / _GCD($iX, $iY) EndFunc ;==>_LCM #EndRegion Math Functions
You should get a message box displaying the decrypted message with details of the values used:
rsa.au3
-
By BigDaddyO
I've been working with the Windows Credentials store to store credentials for lots of RDP connections. I'm also using this code in other scripts to store and retrieve "legacy" credentials for my scripts that have a Save Password checkbox.
All goes well, until someone requests a button to display a list of all saved credentials. I found the CredEnumerate call and it looks like it's working but the Target and UserName field that I want is stored inside an array of pointers and I can't figure out how to get data from inside that. I found a post from 2009 that talks about this, but there was never a solution.
Below are my functions put into an example script. the _Credentials_Enumerate() is where i'm having problems. Anybody have some ideas?
Thanks,
Mike
;Credentials Manager #include <array.au3> #include <WinAPI.au3> ;Needed for the _WinAPI_GetLastError() ;------------------------------------------------------------------------ ;----- Add items into the Credentials Store ---------------------------- ;------------------------------------------------------------------------ ;~ _Cred_Add("MyCredStored", "ItsMe", "Secret1", "", 1) ;Add a Local Credentials so we can test the retrieval of a password ;~ $aAddCred = _Cred_Add("MyServer", "Domain\adminAccount", "MyS3cr3+P@ssw0rd") ;Add domain Credentials that can only be used with RDP and other such items ;~ _ArrayDisplay($aAddCred, "AddCred") ;------------------------------------------------------------------------ ;------------------------------------------------------------------------ ;----- Retrieve Credentials from the Credentials Store ----------------- ;------------------------------------------------------------------------ ;~ $aCreds = _Cred_Get("MyServer", 2) ;Retrieve Domain Cred's, won't have password in it ;~ _ArrayDisplay($aCreds, "Credentials") $aCreds = _Credentials_Enumerate() ;Get a list of all credentials currently stored on the system **(DOES NOT WORK)** ;------------------------------------------------------------------------ ;------------------------------------------------------------------------ ;----- Delete a Credential from the Credentials Store ------------------ ;------------------------------------------------------------------------ ;~ _Cred_Delete("MyServer") ;Delete the specified item from the Credential Store ;~ For $d = 1 to UBound($aCreds) - 1 ;~ _Cred_Delete($aCreds[$d][0]) ;Loop to delete all items found. **(DOES NOT WORK)** ;~ Next ;------------------------------------------------------------------------ ;================================================================================================ ;===== Add a Credential into the Credentials Store ============================================= ;================================================================================================ Func _Cred_Add($sTarget, $sUser, $sPassword, $sComm = "", $iType = 2) ;Type: 2=Domain, 1=Local Local $structTarget = DllStructCreate("wchar[100]") ; Create a structure to hold the Target object name DllStructSetData($structTarget, 1, $sTarget) ; Insert the target name into that Structure Local $structUser = DllStructCreate("wchar[100]") ; Create a structure to hold the UserName to use DllStructSetData($structUser, 1, $sUser) ; Insert the user name into the structure Local $structPwd = DllStructCreate("wchar[100]") ; Create a structure to hole the password to use DllStructSetData($structPwd, 1, $sPassword) ; Insert the password into the structure Local $structComment = DllStructCreate("wchar[100]") ; I don't see where this is used, but was in all the examples DllStructSetData($structComment, 1, $sComm) Local $structCREDENTIAL= "" & _ "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" Local $NewCred = DllStructCreate($structCREDENTIAL) If @error Then MsgBox(0, "NewCred", "Error in DllStructCreate " & @error); Exit EndIf DllStructSetData($NewCred,"Flags",0) DllStructSetData($NewCred,"Type",$iType) ;2 = Domain, 1 = Generic DllStructSetData($NewCred,"TargetName",DllStructGetPtr($structTarget)) DllStructSetData($NewCred,"Persist",3) DllStructSetData($NewCred,"AttributeCount",0) DllStructSetData($NewCred,"UserName",DllStructGetPtr($structUser)) DllStructSetData($NewCred,"CredentialBlob",DllStructGetPtr($structPwd)) DllStructSetData($NewCred,"CredintialBlobSize",StringLen($sPassword)*2) DllStructSetData($NewCred,"Comment",DllStructGetPtr($structComment)) Local $hAdvapi32 = DllOpen("Advapi32.dll") If $hAdvapi32 = -1 Then Msgbox(0, "Error", "Failed to connect to the Credentials Store") Exit Endif $Ret = DllCall($hAdvapi32, 'bool', 'CredWriteW', 'ptr', DllStructGetPtr($NewCred), 'dword', 0) $NewCred = 0 If IsArray($Ret) Then Return $Ret Else Return SetError(1) EndIf EndFunc ;_Cred_Add ;================================================================================================ ;===== Retrieve the Credentials for the specified item ========================================= ;================================================================================================ Func _Cred_Get($sTarget, $iType = 1) ;Type: 2=Domain, 1=Local. CAN'T RETURN DOMAIN PASSWORDS!!! Local $FuncRet[3] Local $structTarget = DllStructCreate("wchar[100]") DllStructSetData($structTarget,1,$sTarget) Local $hAdvapi32 = DllOpen("Advapi32.dll") If $hAdvapi32 = -1 Then Msgbox(0, "Error", "Failed to connect to the Credentials Store") Exit Endif Local $Ret = DllCall($hAdvapi32, 'bool', 'CredReadW', 'ptr', DllStructGetPtr($structTarget), 'dword', $iType, 'dword', 0, 'ptr*', 0) if $ret[0]=0 then Return SetError(1,0,$FuncRet) Local $structCREDENTIAL= "" & _ "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "Ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" Local $tdata=DllStructCreate($structCREDENTIAL, $Ret[4]) Local $userName = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Username')) Local $User = DllStructGetData($userName, 1) Local $CredentialBlobSize = DllStructGetData($tdata, 'CredintialBlobSize') Local $credentialBlob = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'CredentialBlob')) Local $Password = StringLeft(DllStructGetData($credentialBlob, 1), $CredentialBlobSize/2) Local $Comment = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Comment')) Local $Comm = DllStructGetData($Comment, 1) Dim $FuncRet[] = [$User, $Password, $Comm] Return $FuncRet EndFunc ;_Cred_Get ;================================================================================================ ;===== Delete a specified item from the Credentials Store ====================================== ;================================================================================================ Func _Cred_Delete($sTarget, $iType = 2) ;Type: 2=Domain, 1=Local Local $structTarget = DllStructCreate("wchar[100]") ;Create a structure to hold the object name we want to delete DllStructSetData($structTarget, 1, $sTarget) ;Insert the Object Name into the Structure Local $hAdvapi32 = DllOpen("Advapi32.dll") If $hAdvapi32 = -1 Then Msgbox(0, "Error", "Failed to connect to the Credentials Store") Exit Endif ;Now send all the info into the DLL to delete the item $Ret = DllCall($hAdvapi32, 'bool', 'CredDeleteW', 'ptr', DllStructGetPtr($structTarget), 'dword', $iType, 'dword', 0) ;$iType 2 = Domain, 1 = Local EndFunc ;_Cred_Delete ;================================================================================================ ;===== Return a 2D array with the Target, UserName, Password for every item ==================== ;===== in the Credentials Store ==================== ;================================================================================================ Func _Credentials_Enumerate() ;https://msdn.microsoft.com/en-us/library/windows/desktop/aa374794(v=vs.85).aspx ;https://www.autoitscript.com/forum/topic/99705-credenumerate-function-call/?do=findComment&comment=715159 Local $aResult Local $structCREDENTIAL = "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "Ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" $aResult = DllCall('advapi32.dll', 'int', 'CredEnumerateW', _ ;Call the Unicode version of CredEnumerate 'wstr', Null, _ ;Don't use any filter since I want everything returned 'uint', 1, _ ;1 = CRED_ENUMERATE_ALL_CREDENTIALS 'uint*', '', _ ;Return the Count of all stored credentials 'ptr*', '') ;Returns a pointer to an Array of pointers? If @error Or ($aResult[0] = 0) Then ConsoleWrite('Error: ' & @error & @TAB & 'Extended: ' & @extended & @CRLF) ConsoleWrite(_WinAPI_GetLastError() & @CRLF) ;1168 = Nothing matches the filter, 1312 = no credential set for this user, 1004 = Flag/Filter options are wrong Return SetError(1) EndIf ConsoleWrite("DllCall Returned = " & $aResult[0] & @CRLF & "Credential Count = " & $aResult[3] & @CRLF & "Pointer to Creds Array = " & $aResult[4] & @CRLF) For $c = 2 to $aResult[3] ;Create enough struct for each item in each credential found $structCREDENTIAL &= "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "Ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" Next Local $tdata = DllStructCreate($structCREDENTIAL, $aResult[4]) ;Insert all the data from the array of pointers into this struct Local $FullTarget = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'TargetName')) ;Create and Get the array storing TargetName Local $userName = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Username')) ;Create and Get the array storing Username Local $CredentialBlobSize = DllStructGetData($tdata, 'CredintialBlobSize') ;Get the password blob Local $credentialBlob = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'CredentialBlob')) ;Create and get the password text Local $Comment = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Comment')) ;Don't see a need for comments ;Retrieve the data For $c = 1 to $aResult[3] Local $Target = DllStructGetData($FullTarget, $c) ;Retrieve the Target Name from the item # Local $User = DllStructGetData($userName, $c) ;Retrieve the User Name from the item # Local $Password = StringLeft(DllStructGetData($credentialBlob, $c), $CredentialBlobSize/2) ;Retrieve the password, Only works for 1, legacy. domain creds will not return passwords Local $Comm = DllStructGetData($Comment, $c) ;Don't need comments but getting it since it's in all the examples ConsoleWrite("Loop = " & $c & ": Target = " & $Target & ": UserName = " & $User & ": Comment = " & $Comm & @CRLF) Next If $aResult[3] > 0 Then $aCreds = DllCall('advapi32.dll', 'none', 'CredFree', 'ptr', $aResult[4]) ;This is just used to release the pointer. Call when done EndIf EndFunc ;_Credentials_Enumerate
-
By Osys2010
My RSA script, 128 bit and lower fast (for UDF attachment)
Using :
"RSATool2v17.exe" open and input (E) key and Keysize (Bits) "128", Generate "P, Q, D". Copy "P, Q, D" to my code
; Script Start - Add your code below here #include <String.au3> #include "BigNum.au3" Global $P, $Q, $SelectBase = 64 $base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ;base64 ;Sexagesimal $base60_2 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx" ;sexagesimal $base32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" ;base32 $base24 = "0123456789ABCDEFGHJKLMNP" ;base24 $base16 = "0123456789ABCDEF" ;hex ;Duodecimal system or dozenal $base12 = "0123456789AB" ;duodecimal $base10 = "0123456789" ;base10 $base8 = "01234567" ;oct $base2 = "01" ;binary $P = _BigNum_Add($P, "18429553113751821539") $Q = _BigNum_Add($Q, "14963134653035728619") $n = _BigNum_Mul($P, $Q) $PHI = _BigNum_Mul(_BigNum_Sub($P, 1), _BigNum_Sub($Q, 1)) $e = _NumToDec("10001100011000110001", $base16) $D = "263455903565562556840568120179103558669" ConsoleWrite(@CRLF) ConsoleWrite("P: " & NumberBase($P) & @CRLF) ConsoleWrite("Q: " & NumberBase($Q) & @CRLF) ConsoleWrite("N: " & NumberBase($n) & @CRLF) ConsoleWrite("PHI: " & NumberBase($PHI) & @CRLF & @CRLF) ConsoleWrite("D: " & NumberBase($D) & @CRLF) ConsoleWrite("E: " & NumberBase($e) & @CRLF & @CRLF) $Message = _NumToDec(_StringToHex("TEST MESSAGE"), $base16) If StringLen($Message) > StringLen($n) Then Exit (1) $c = _BigNum_PowerMod($Message, $e, $n) $D = _BigNum_PowerMod($c, $D, $n) ConsoleWrite("C: " & NumberBase($c) & @CRLF) ConsoleWrite("D: " & _HexToString(_DecToNum($D, $base16)) & @CRLF) ConsoleWrite(@CRLF) ;==================================================================================== ;~ Func modpow($a, $b, $c) ;~ $res = 1 ;~ While $b > 0 ;~ ;/* Need long multiplication else this will overflow... */ ;~ If Mod(StringRight($b, 1), 2) Then ;If BitAND($b,1) Then ;~ $res = _BigNum_Mod(_BigNum_Mul($res, $a), $c) ;~ EndIf ;~ $b = BitShift($b, 1) ;~ $a = _BigNum_Mod(_BigNum_Mul($a, $a), $c) ; /* Same deal here */ ;~ WEnd ;~ Return $res ;~ EndFunc ;==>modpow Func NumberBase($num, $base = $SelectBase) If $base = 10 Then Return _DecToNum($num, $base10) ElseIf $base = 16 Then Return _DecToNum($num, $base16) ElseIf $base = 60 Then Return _DecToNum($num, $base60_2) ElseIf $base = 64 Then Return _DecToNum($num, $base64) EndIf Return $num EndFunc ;==>NumberBase Func _DecToNum($iDec, $Symbol) Local $Out, $ost $Symbol = StringSplit($Symbol, '') If @error Or $Symbol[0] < 2 Then Return SetError(1, 0, $iDec) Do $ost = _BigNum_Mod($iDec, $Symbol[0]) $iDec = _BigNum_Div(_BigNum_Sub($iDec, $ost), $Symbol[0]) $Out = $Symbol[$ost + 1] & $Out Until Not Number($iDec) Return SetError(0, $Symbol[0], $Out) EndFunc ;==>_DecToNum Func _NumToDec($num, $sSymbol, $casesense = 1) Local $i, $iPos, $Len, $n, $Out $Len = StringLen($sSymbol) If $Len < 2 Then Return SetError(1, 0, $num) $n = StringSplit($num, '') For $i = 1 To $n[0] $iPos = StringInStr($sSymbol, $n[$i], $casesense) If Not $iPos Then Return SetError(2, 0, $num) $Out = _BigNum_Add(_BigNum_Mul($iPos - 1, _BigNum_Pow($Len, $n[0] - $i)), $Out) Next Return SetError(0, $Len, $Out) EndFunc ;==>_NumToDec ; #FUNCTION# ;==================================================================================== ; ; Name...........: _BigNum_PowerMod ; Description ...: Modular Exponentiation Mod($n^$e, $k) ; Syntax.........: _BigNum_Pow($n, $e, $k) ; Parameters ....: $n - Positive StringNumber: Digits"0"..."9" ; $e - Positive StringNumber: Exponent ; $k - Positive StringNumber: Modulus ; Return values .: Success - Result Mod($n^$e, $k) ; Failure - -1, sets @error to 1 if $n is not a positive valid StringNumber ; -1, sets @error to 2 if $e is not a positive valid StringNumber ; -1, sets @error to 3 if $k is not a positive valid StringNumber ; Author ........: jchd ; Date ..........: 17.12.13 ; Remarks .......: Fractional exponents not allowed - use BigNum_n_root instead. ; ;=============================================================================================== Func _BigNum_PowerMod($n, $e, $k) If Not __BigNum_IsValid_3($n, $e, $k) Then Return SetError(1, 0, -1) Local $res = "1" While $e <> "0" If Mod(StringRight($e, 1), 2) Then $res = _BigNum_Mod(_BigNum_Mul($res, $n), $k) $e = _BigNum_Sub($e, "1") EndIf $n = _BigNum_Mod(_BigNum_Mul($n, $n), $k) $e = _BigNum_Div($e, "2") WEnd Return $res EndFunc ;==>_BigNum_PowerMod Func __BigNum_IsValid_3($sX, $sY, $sZ) If StringRegExp($sX, "[^0-9.-]") Or StringRegExp($sY, "[^0-9.-]") Or StringRegExp($sZ, "[^0-9.-]") Then Return False Return True EndFunc ;==>__BigNum_IsValid_3
RSA 2 (TEST NOW).zip
-
By giangnguyen
Anybody knows how I can apply Public-Private Key encryption? I found several threads but they are all outdated
Any ideas? I don't think it is included in advapi32 either, which is used by AutoIt atm
-
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now