├── .gitignore ├── AES └── MITM.py ├── Diffie Hellman ├── DiscreteLogarithmSolver.py ├── Pollards_Kangaroo.sage └── README.md ├── LICENSE ├── Pairings ├── RogueKeyAttack.sage └── RogueKeyAttack.sage.py ├── README.md └── RSA ├── FranklinReiter.sage ├── FranklinReiterSage.py ├── README.md ├── RSATool.py ├── bleichenbacher.py ├── hastads.sage ├── hastadsSage.py ├── partialKnownMessage.sage ├── partialKnownMessageSage.py ├── testKeys ├── key-0.pem ├── key-1.pem ├── key-2.pem ├── key-3.pem ├── key-4.pem ├── key-5.pem └── key-6.pem ├── testScript.py ├── testScript.sage ├── testScriptSage.py └── wienerAttack.py /.gitignore: -------------------------------------------------------------------------------- 1 | **.pyc 2 | **.exp 3 | *.sqlite 4 | **.pyo 5 | **.pyd 6 | **.log 7 | firstRun.conf 8 | __pycache__/ 9 | **/__pycache__ 10 | -------------------------------------------------------------------------------- /AES/MITM.py: -------------------------------------------------------------------------------- 1 | """ 2 | AES Meet in the middle attack for when a plaintext is encrypted twice, with two different keys. 3 | You must know something about the key format, for example the sample keygen is written 4 | with all but the last 24 bits being 0. Create a new key generator method according to your case. 5 | """ 6 | 7 | from Crypto.Cipher import AES 8 | 9 | def solve(plaintext,ciphertext,KeyGen): 10 | encrypted = {} 11 | for key in KeyGen(): 12 | AEScipher = newAES(key) 13 | encrypted[AEScipher.encrypt(plaintext)] = key 14 | for key in KeyGen(): 15 | AEScipher = newAES(key) 16 | decrypted = AEScipher.decrypt(ciphertext) 17 | if(decrypted in encrypted): 18 | # We got a match! 19 | Key1 = encrypted[decrypted] 20 | Key2 = key 21 | return (Key1,Key2) 22 | 23 | def newAES(key): 24 | return AES.new(key, mode=AES.MODE_ECB) 25 | 26 | def sample_KeyGen(): 27 | baseString = bytes([0])*29 28 | for a in range(256): 29 | StringA = baseString + bytes([a]) 30 | for b in range(256): 31 | StringB = StringA + bytes([b]) 32 | for c in range(256): 33 | yield StringB + bytes([c]) 34 | 35 | def testAESMITM(): 36 | # Use 2013 Boston Key Party values 37 | import base64 38 | message1 = base64.b64decode("QUVTLTI1NiBFQ0IgbW9kZSB0d2ljZSwgdHdvIGtleXM=") 39 | encrypted = base64.b64decode("THbpB4bE82Rq35khemTQ10ntxZ8sf7s2WK8ErwcdDEc=") 40 | (Key1,Key2) = solve(message1,encrypted,sample_KeyGen) 41 | AES1 = newAES(Key1) 42 | AES2 = newAES(Key2) 43 | message2 = base64.b64decode("RWFjaCBrZXkgemVybyB1bnRpbCBsYXN0IDI0IGJpdHM=") 44 | encrypted = base64.b64decode("01YZbSrta2N+1pOeQppmPETzoT/Yqb816yGlyceuEOE=") 45 | assert AES1.encrypt(message2) == AES2.decrypt(encrypted) 46 | print("Test passed") 47 | ciphertext = base64.b64decode("s5hd0ThTkv1U44r9aRyUhaX5qJe561MZ16071nlvM9U=") 48 | print("That years BKP flag: ") 49 | print(AES1.decrypt(AES2.decrypt(ciphertext))) 50 | 51 | testAESMITM() 52 | -------------------------------------------------------------------------------- /Diffie Hellman/DiscreteLogarithmSolver.py: -------------------------------------------------------------------------------- 1 | class DiscreteLogarithmSolver: 2 | def babyStepGiantStep(self, g,b,p,m="m"): 3 | """ 4 | Baby Step Giant Step algorithm from https://en.wikipedia.org/wiki/Baby-step_giant-step 5 | Input: A cyclic group G of order n, having a generator g and an element β. 6 | order n = p, as is standard for DH 7 | Output: A value x satisfying g^x = β mod p 8 | 9 | This is essentially a space time trade-off attack. The amount of space needed can be quite large for not that large p. 10 | ( > 8 gb) hence the input() statement. 11 | """ 12 | if(m=="m"): 13 | m = self.floorSqrt(p) + 1 14 | if(m > 50000000): 15 | cont = input("m is large (%s), this may eat up all your available RAM. Type 'Y' to continue\n" % m).lower() 16 | if(cont != 'y' and cont != 'yes'): 17 | return -2 18 | gInverse = self.modinv(pow(g,m,p),p) 19 | hashtable = {} 20 | # The current power, using this instead of doing a 21 | # more expensive modpow every time 22 | cur = 1 23 | hashtable[1] = 0 24 | for j in range(1,m): 25 | cur = (cur*g)%p 26 | hashtable[cur] = j 27 | #print('finished beggining') 28 | gamma = b 29 | for i in range(m): 30 | if(gamma in hashtable): 31 | solution = i*m + hashtable[gamma] 32 | #open('solution','w+').write(str(solution)) 33 | return solution 34 | else: 35 | gamma = (gamma * gInverse) %p 36 | if(gamma==b): 37 | return -1 38 | #return "Looped at %s :( " % i 39 | return -1 40 | 41 | #----------------SHARED ALGORITHMS SECTION-----------------------# 42 | def extended_gcd(self,aa, bb): 43 | """Extended Euclidean Algorithm, 44 | from https://rosettacode.org/wiki/Modular_inverse#Python 45 | """ 46 | lastremainder, remainder = abs(aa), abs(bb) 47 | x, lastx, y, lasty = 0, 1, 1, 0 48 | while remainder: 49 | lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) 50 | x, lastx = lastx - quotient*x, x 51 | y, lasty = lasty - quotient*y, y 52 | return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) 53 | 54 | def modinv(self,a, m): 55 | """Modular Multiplicative Inverse, 56 | from https://rosettacode.org/wiki/Modular_inverse#Python 57 | """ 58 | g, x, y = self.extended_gcd(a, m) 59 | if g != 1: 60 | raise ValueError 61 | return x % m 62 | 63 | def floorSqrt(self,n): 64 | x = n 65 | y = (x + 1) // 2 66 | while y < x: 67 | x = y 68 | y = (x + n // x) // 2 69 | return x 70 | -------------------------------------------------------------------------------- /Diffie Hellman/Pollards_Kangaroo.sage: -------------------------------------------------------------------------------- 1 | #For use when trying to solve the DLP, and you have an upperbound for the exponent. 2 | # Running time is O(sqrt(upperbound-lowerbound)) 3 | # So for example, with the following g and p, and with it being in range (1,2**46) 4 | # This is for modular field, but can be adapted for any finite field. 5 | p = 174807157365465092731323561678522236549173502913317875393564963123330281052524687450754910240009920154525635325209526987433833785499384204819179549544106498491589834195860008906875039418684191252537604123129659746721614402346449135195832955793815709136053198207712511838753919608894095907732099313139446299843 6 | g = 41899070570517490692126143234857256603477072005476801644745865627893958675820606802876173648371028044404957307185876963051595214534530501331532626624926034521316281025445575243636197258111995884364277423716373007329751928366973332463469104730271236078593527144954324116802080620822212777139186990364810367977 7 | A = 60599224471338675280892530751916349778515159413752423808328059701102187627870714718035966693602191072973114841123646111608872779841184094624255525186079109811898831481367089940015561846391171130215542875940992971840860585330764274682844976540740482087538338803018712681621346835893113300860496747212230173641 8 | k = GF(p) 9 | AInField = k(A) 10 | gInField = k(g) 11 | discrete_log_lambda(AInField,gInField,(1,2**46)) 12 | # returns 33657892424673 given enough time! 13 | -------------------------------------------------------------------------------- /Diffie Hellman/README.md: -------------------------------------------------------------------------------- 1 | # Diffie Hellman 2 | 3 | Really most Diffie Hellman attacks are based upon solving the Discrete Logarithm Problem. 4 | There are only a few methods for solving the Discrete Logarithm Problem, and most are inbuilt into Sage. 5 | So I will just put examples of different attacks for those problems. 6 | 7 | ## Pollards Kangaroo Algorithm ( AKA Pollard's Lambda Algorithm) 8 | This is an algorithm which is good if you have bounds on the exponent. 9 | It runs in time O(sqrt(upperbound-lowerbound)) 10 | This algorithm works in any finite cyclic group 11 | 12 | ## Pohlig-Hellman 13 | This is a way of reducing a Discrete Log Problem into simpler sub-problems. If the modulus for what we are working with is composite (thus it has multiple prime factors), we can use the fact that any relationship which is true Modulo N, is also true modulo a factor of N. 14 | 15 | So what we do is we split the problem into then solving the DLP mod each prime factor of N. (In the case of repeated prime factors, mod primefactor^{its corresponding power}) 16 | We then CRT our solutions. 17 | 18 | Since we have general purpose O(Sqrt(N)) algorithms for solving a discrete log, this reduces the complexity of solving the discrete log to O(sqrt(Largest prime factor of N)) 19 | It is because of this that the modulii for discrete log problems are safe primes. 20 | (Since the order of a finite field is what is used, and the order of a finite field modulo prime p is p-1, you want it to have the largest prime factor it can, hence being a safe prime.) 21 | 22 | This also works for all finite cyclic groups, such as Elliptic Curves. 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Pairings/RogueKeyAttack.sage: -------------------------------------------------------------------------------- 1 | # The Rogue Public Key attack takes a given public key, and produces a second public key, 2 | # such that the aggregate BLS signature of any message with the two public keys can be forged by 3 | # the attacker, who knows nothing about the secret key for the first public key. 4 | 5 | 6 | # GenFakeKeys Returns a point on C2 (the public key), and a number B which corresponds to the blinding done on the original pubkey 7 | # B with the original public key, 8 | def GenFakeKeys(pubkey1): 9 | # Assumes pubkey is on C2 10 | pubkey2 = pubkey1 * -1 11 | b = randint(0, order) 12 | blindingFactor = g2 * b 13 | pubkey2 = pubkey2 + blindingFactor 14 | assert pubkey2 + pubkey1 == blindingFactor 15 | return pubkey2, b 16 | 17 | # GenFakeSignature Creates a fake signature, using the blinfing factor (b), and the message hashed onto G1 18 | def GenFakeSignature(b, hashedMsg): 19 | aggsig = b * hashedMsg 20 | return aggsig 21 | 22 | # This currently tests nothing. I'm trying to figure out how to undo the sextic 23 | # twist on G2, in order to be able to use Sage's inbuilt Tate Pairing. 24 | # I have tested this function with the bls12 implementation used in 25 | # https://github.com/Project-Arda/bgls 's develop branch however, and it works correctly 26 | def TestRoguePublicKey(): 27 | numTests = 2 28 | for _ in range(numTests): 29 | x = randint(0, order) 30 | h = g1 * randint(0, order) 31 | pk1 = g2*x 32 | pk2, b = GenFakeKeys(pk1) 33 | sig = GenFakeSignature(b, h) 34 | # Needs to test that 35 | # e(sig, g2) = e(h, pk1 + pk2) 36 | # The results of this function have been tested to function correctly with 37 | # https://github.com/Project-Arda/bgls 's develop branch however 38 | 39 | # BLS12-381 Curve parameters. Replace with your own curve parameters. 40 | # Curve 1 is the curve which the signatures are on. 41 | # Curve 2 is the curve which the public keys are on. 42 | q = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab 43 | F1 = GF(q) 44 | F2 = GF(q^2,"u",modulus=x^2 + 1) 45 | C1 = EllipticCurve(F1,[0,4]) 46 | g1 = C1(3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507,1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569) 47 | # This method of getting the order is unique to bls12. 48 | x = -0xd201000000010000 49 | x = x % q 50 | cofactor1 = Integer(pow(x - 1, 2, q) / 3) 51 | order = C1.order() // cofactor1 52 | 53 | C2 = EllipticCurve(F2,[0,4*F2("1+u")]) 54 | g2 = C2(F2("3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758*u + 352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160"), 55 | F2("927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582*u + 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905")) 56 | -------------------------------------------------------------------------------- /Pairings/RogueKeyAttack.sage.py: -------------------------------------------------------------------------------- 1 | 2 | # This file was *autogenerated* from the file RogueKeyAttack.sage 3 | from sage.all_cmdline import * # import sage library 4 | 5 | _sage_const_3 = Integer(3); _sage_const_2 = Integer(2); _sage_const_1 = Integer(1); _sage_const_0 = Integer(0); _sage_const_1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 = Integer(1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569); _sage_const_4 = Integer(4); _sage_const_3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 = Integer(3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507); _sage_const_0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab = Integer(0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab); _sage_const_0xd201000000010000 = Integer(0xd201000000010000)# Returns a point on C2 (the public key), and a number B which corresponds to the blinding done on the original pubkey 6 | # B with the original public key, 7 | def GenFakeKeys(pubkey1): 8 | # Assumes pubkey is on C2 9 | pubkey2 = pubkey1 * -_sage_const_1 10 | b = randint(_sage_const_0 , order) 11 | blindingFactor = g2 * b 12 | pubkey2 = pubkey2 + blindingFactor 13 | assert pubkey2 + pubkey1 == blindingFactor 14 | return pubkey2, b 15 | 16 | # Creates a fake signature, using the blinfing factor (b), and the message hashed onto G1 17 | def GenFakeSignature(b, hashedMsg): 18 | aggsig = b * hashedMsg 19 | return aggsig 20 | 21 | # This currently tests nothing. I'm trying to figure out how to undo the sextic 22 | # twist on G2, in order to be able to use Sage's inbuilt Tate Pairing. 23 | # I have tested this function with the bls12 implementation used in 24 | # https://github.com/Project-Arda/bgls 's develop branch however. 25 | def TestRoguePublicKey(): 26 | numTests = _sage_const_2 27 | for _ in range(numTests): 28 | x = randint(_sage_const_0 , order) 29 | h = g1 * randint(_sage_const_0 , order) 30 | pk1 = g2*x 31 | pk2, b = GenFakeKeys(pk1) 32 | sig = GenFakeSignature(b, h) 33 | print("h") 34 | print(h) 35 | print("sig") 36 | print(sig) 37 | print("agg key") 38 | print(pk1 + pk2) 39 | # Needs to test that 40 | # e(sig, g2) = e(h, pk1 + pk2) 41 | 42 | # BLS12-381 Curve parameters. Replace with your own curve parameters. 43 | # Curve 1 is the curve which the signatures are on. 44 | # Curve 2 is the curve which the public keys are on. 45 | q = _sage_const_0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab 46 | F1 = GF(q) 47 | F2 = GF(q**_sage_const_2 ,"u",modulus=x**_sage_const_2 + _sage_const_1 ) 48 | C1 = EllipticCurve(F1,[_sage_const_0 ,_sage_const_4 ]) 49 | g1 = C1(_sage_const_3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 ,_sage_const_1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 ) 50 | # This method of getting the order is unique to bls12. 51 | x = -_sage_const_0xd201000000010000 52 | x = x % q 53 | cofactor1 = Integer(pow(x - _sage_const_1 , _sage_const_2 , q) / _sage_const_3 ) 54 | order = C1.order() // cofactor1 55 | 56 | C2 = EllipticCurve(F2,[_sage_const_0 ,_sage_const_4 *F2("1+u")]) 57 | g2 = C2(F2("3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758*u + 352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160"), 58 | F2("927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582*u + 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905")) 59 | 60 | TestRoguePublicKey() 61 | 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | CTF Crypto 2 | ======= 3 | This contains the code I use to perform various Cryptography Attacks in CTFs. 4 | This only contains attacks on common cryptography systems, not custom cryptosystems / hashing functions made by the CTF creators. If you have any suggestions for attacks to implement, raise a github issue. 5 | 6 | The RSA tool is designed for python3, though it likely can be modified for python2 by removing timeouts. 7 | The files with Sage in the name are designed for sage. the `.sage` extension is the human readable version, the `Sage.py` version is the preparsed version which you can import into sage. 8 | *Please note this project is not abandoned. I am currently helping create a CTF, so there are certain things I can't commit to this repository until after the CTF is complete.* 9 | 10 | ## RSA Tool 11 | 12 | Note that this is Linux only, due to my usage of "signal" for timeouts. 13 | 14 | ### Factorization Methods contained: 15 | 16 | * Check FactorDB 17 | * GCD for Multiple keys 18 | * Sieved Fermat Factorization 19 | * Wiener Attack 20 | * Pollards P-1 (Not a good implementation) 21 | * Pollards Rho (Fairly Broken) 22 | 23 | ### RSA specific methods 24 | * Partial Key Recovery for n/2 bits of the private key 25 | * TODO Partial Key Recovery for n/4 bits of the private key 26 | * Chinese Remainder Theorem full private key recovery 27 | * Decoding despite invalid Public Exponent 28 | 29 | ### Low Public Exponent 30 | * Hastad's Broadcast Attack 31 | * Hastad's Broadcast Attack with Linear Padding 32 | * Common Modulus, Common public Exponent 33 | * Python RSA bleichenbacher-06 signature forgery 34 | * Known message format/prefix 35 | * Coppersmith Shortpad Attack 36 | 37 | ## Diffie Hellman 38 | 39 | * Baby Step Giant Step Algorithm 40 | * Pollards Kangaroo/Lambda Algorithm 41 | 42 | ## Pairings 43 | 44 | * Rogue Public Key for BLS signatures 45 | -------------------------------------------------------------------------------- /RSA/FranklinReiter.sage: -------------------------------------------------------------------------------- 1 | # Franklin-Reiter attack against RSA. 2 | # If two messages differ only by a known fixed difference between the two messages 3 | # and are RSA encrypted under the same RSA modulus N 4 | # then it is possible to recover both of them. 5 | 6 | # Inputs are modulus, known difference, ciphertext 1, ciphertext2. 7 | # Ciphertext 1 corresponds to smaller of the two plaintexts. (The one without the fixed difference added to it) 8 | def franklinReiter(n,e,r,c1,c2): 9 | R. = Zmod(n)[] 10 | f1 = X^e - c1 11 | f2 = (X + r)^e - c2 12 | # coefficient 0 = -m, which is what we wanted! 13 | return Integer(n-(compositeModulusGCD(f1,f2)).coefficients()[0]) 14 | 15 | # GCD is not implemented for rings over composite modulus in Sage 16 | # so we do our own implementation. Its the exact same as standard GCD, but with 17 | # the polynomials monic representation 18 | def compositeModulusGCD(a, b): 19 | if(b == 0): 20 | return a.monic() 21 | else: 22 | return compositeModulusGCD(b, a % b) 23 | 24 | def CoppersmithShortPadAttack(e,n,C1,C2,eps=1/30): 25 | """ 26 | Coppersmith's Shortpad attack! 27 | Figured out from: https://en.wikipedia.org/wiki/Coppersmith's_attack#Coppersmith.E2.80.99s_short-pad_attack 28 | """ 29 | import binascii 30 | P. = PolynomialRing(ZZ) 31 | ZmodN = Zmod(n) 32 | g1 = x^e - C1 33 | g2 = (x+y)^e - C2 34 | res = g1.resultant(g2) 35 | P. = PolynomialRing(ZmodN) 36 | # Convert Multivariate Polynomial Ring to Univariate Polynomial Ring 37 | rres = 0 38 | for i in range(len(res.coefficients())): 39 | rres += res.coefficients()[i]*(y^(res.exponents()[i][1])) 40 | 41 | diff = rres.small_roots(epsilon=eps) 42 | recoveredM1 = franklinReiter(n,e,diff[0],C1,C2) 43 | print(recoveredM1) 44 | print("Message is the following hex, but potentially missing some zeroes in the binary from the right end") 45 | print(hex(recoveredM1)) 46 | print("Message is one of:") 47 | for i in range(8): 48 | msg = hex(Integer(recoveredM1*pow(2,i))) 49 | if(len(msg)%2 == 1): 50 | msg = '0' + msg 51 | if(msg[:2]=='0x'): 52 | msg = msg[:2] 53 | print(binascii.unhexlify(msg)) 54 | 55 | def testCoppersmithShortPadAttack(eps=1/25): 56 | from Crypto.PublicKey import RSA 57 | import random 58 | import math 59 | import binascii 60 | M = "flag{This_Msg_Is_2_1337}" 61 | M = int(binascii.hexlify(M),16) 62 | e = 3 63 | nBitSize = 8192 64 | key = RSA.generate(nBitSize) 65 | #Give a bit of room, otherwhise the epsilon has to be tiny, and small roots will take forever 66 | m = int(math.floor(nBitSize/(e*e))) - 400 67 | assert (m < nBitSize - len(bin(M)[2:])) 68 | r1 = random.randint(1,pow(2,m)) 69 | r2 = random.randint(r1,pow(2,m)) 70 | M1 = pow(2,m)*M + r1 71 | M2 = pow(2,m)*M + r2 72 | C1 = Integer(pow(M1,e,key.n)) 73 | C2 = Integer(pow(M2,e,key.n)) 74 | CoppersmithShortPadAttack(e,key.n,C1,C2,eps) 75 | 76 | def testFranklinReiter(): 77 | p = random_prime(2^512) 78 | q = random_prime(2^512) 79 | n = p * q # 1024-bit modulus 80 | e = 11 81 | 82 | m = randint(0, n) # some message we want to recover 83 | r = randint(0, n) # random padding 84 | 85 | c1 = pow(m + 0, e, n) 86 | c2 = pow(m + r, e, n) 87 | print(m) 88 | recoveredM = franklinReiter(n,e,r,c1,c2) 89 | print(recoveredM) 90 | assert recoveredM==m 91 | print("They are equal!") 92 | return True 93 | -------------------------------------------------------------------------------- /RSA/FranklinReiterSage.py: -------------------------------------------------------------------------------- 1 | 2 | # This file was *autogenerated* from the file FranklinReiter.sage 3 | from sage.all_cmdline import * # import sage library 4 | 5 | _sage_const_3 = Integer(3); _sage_const_2 = Integer(2); _sage_const_1 = Integer(1); _sage_const_0 = Integer(0); _sage_const_11 = Integer(11); _sage_const_8 = Integer(8); _sage_const_512 = Integer(512); _sage_const_8192 = Integer(8192); _sage_const_16 = Integer(16); _sage_const_30 = Integer(30); _sage_const_400 = Integer(400); _sage_const_25 = Integer(25)# Franklin-Reiter attack against RSA. 6 | # If two messages differ only by a known fixed difference between the two messages 7 | # and are RSA encrypted under the same RSA modulus N 8 | # then it is possible to recover both of them. 9 | 10 | # Inputs are modulus, known difference, ciphertext 1, ciphertext2. 11 | # Ciphertext 1 corresponds to smaller of the two plaintexts. (The one without the fixed difference added to it) 12 | def franklinReiter(n,e,r,c1,c2): 13 | R = Zmod(n)['X']; (X,) = R._first_ngens(1) 14 | f1 = X**e - c1 15 | f2 = (X + r)**e - c2 16 | # coefficient 0 = -m, which is what we wanted! 17 | return Integer(n-(compositeModulusGCD(f1,f2)).coefficients()[_sage_const_0 ]) 18 | 19 | # GCD is not implemented for rings over composite modulus in Sage 20 | # so we do our own implementation. Its the exact same as standard GCD, but with 21 | # the polynomials monic representation 22 | def compositeModulusGCD(a, b): 23 | if(b == _sage_const_0 ): 24 | return a.monic() 25 | else: 26 | return compositeModulusGCD(b, a % b) 27 | 28 | def CoppersmithShortPadAttack(e,n,C1,C2,eps=_sage_const_1 /_sage_const_30 ): 29 | """ 30 | Coppersmith's Shortpad attack! 31 | Figured out from: https://en.wikipedia.org/wiki/Coppersmith's_attack#Coppersmith.E2.80.99s_short-pad_attack 32 | """ 33 | import binascii 34 | P = PolynomialRing(ZZ, names=('x', 'y',)); (x, y,) = P._first_ngens(2) 35 | ZmodN = Zmod(n) 36 | g1 = x**e - C1 37 | g2 = (x+y)**e - C2 38 | res = g1.resultant(g2) 39 | P = PolynomialRing(ZmodN, names=('y',)); (y,) = P._first_ngens(1) 40 | print("----------------------------------------------------------------------") 41 | print("This requires a bit of manual work b/c idk how to convert a" + 42 | " Multivariate PolynomialRing to a Univraiate PolynomialRing mod N through code in sage") 43 | print("So you need to just copy the following polynomial, and paste it back") 44 | print("----------------------------------------------------------------------") 45 | raw_input("Press enter to get the polynomial") 46 | print(str(res).replace('^','**')) 47 | rres = input() 48 | 49 | diff = rres.small_roots(epsilon=eps) 50 | recoveredM1 = franklinReiter(n,e,diff[_sage_const_0 ],C1,C2) 51 | print(recoveredM1) 52 | print("Message is the following hex, but potentially missing some zeroes in the binary from the right end") 53 | print(hex(recoveredM1)) 54 | print("Message is one of:") 55 | for i in range(_sage_const_8 ): 56 | msg = hex(Integer(recoveredM1*pow(_sage_const_2 ,i))) 57 | if(len(msg)%_sage_const_2 == _sage_const_1 ): 58 | msg = '0' + msg 59 | if(msg[:_sage_const_2 ]=='0x'): 60 | msg = msg[:_sage_const_2 ] 61 | print(binascii.unhexlify(msg)) 62 | 63 | def testCoppersmithShortPadAttack(eps=_sage_const_1 /_sage_const_25 ): 64 | from Crypto.PublicKey import RSA 65 | import random 66 | import math 67 | import binascii 68 | M = "flag{This_Msg_Is_2_1337}" 69 | M = int(binascii.hexlify(M),_sage_const_16 ) 70 | e = _sage_const_3 71 | nBitSize = _sage_const_8192 72 | key = RSA.generate(nBitSize) 73 | #Give a bit of room, otherwhise the epsilon has to be tiny, and small roots will take forever 74 | m = int(math.floor(nBitSize/(e*e))) - _sage_const_400 75 | assert (m < nBitSize - len(bin(M)[_sage_const_2 :])) 76 | r1 = random.randint(_sage_const_1 ,pow(_sage_const_2 ,m)) 77 | r2 = random.randint(r1,pow(_sage_const_2 ,m)) 78 | M1 = pow(_sage_const_2 ,m)*M + r1 79 | M2 = pow(_sage_const_2 ,m)*M + r2 80 | C1 = Integer(pow(M1,e,key.n)) 81 | C2 = Integer(pow(M2,e,key.n)) 82 | CoppersmithShortPadAttack(e,key.n,C1,C2,eps) 83 | 84 | def testFranklinReiter(): 85 | p = random_prime(_sage_const_2 **_sage_const_512 ) 86 | q = random_prime(_sage_const_2 **_sage_const_512 ) 87 | n = p * q # 1024-bit modulus 88 | e = _sage_const_11 89 | 90 | m = randint(_sage_const_0 , n) # some message we want to recover 91 | r = randint(_sage_const_0 , n) # random padding 92 | 93 | c1 = pow(m + _sage_const_0 , e, n) 94 | c2 = pow(m + r, e, n) 95 | print(m) 96 | recoveredM = franklinReiter(n,e,r,c1,c2) 97 | print(recoveredM) 98 | assert recoveredM==m 99 | print("They are equal!") 100 | return True 101 | 102 | -------------------------------------------------------------------------------- /RSA/README.md: -------------------------------------------------------------------------------- 1 | RSA Tool 2 | ======= 3 | This contains code to factor large RSA modulii, and perform other related RSA attacks. 4 | I have used methods in here for every RSA problem I have encountered in CTFs. 5 | 6 | ### Factorization Methods contained: 7 | 8 | * Check FactorDB 9 | * GCD for Multiple keys 10 | * Sieved Fermat Factorization 11 | * Wiener Attack 12 | * Pollards P-1 (Not a good implementation) 13 | * Pollards Rho (Fairly Broken) 14 | 15 | 16 | ### RSA specific methods 17 | * Partial Key Recovery for n/2 bits of the private key 18 | * TODO Partial Key Recovery for n/4 bits of the private key 19 | * Chinese Remainder Theorem full private key recovery 20 | * Decoding despite invalid Public Exponent 21 | 22 | ### Low Public Exponent 23 | * Hastad's Broadcast Attack 24 | * Hastad's Broadcast Attack with Linear Padding 25 | * Common Modulus, Common public Exponent 26 | * Python RSA bleichenbacher-06 signature forgery 27 | * Known message format/prefix 28 | * Coppersmith Shortpad Attack 29 | -------------------------------------------------------------------------------- /RSA/RSATool.py: -------------------------------------------------------------------------------- 1 | from fractions import gcd 2 | from Crypto.PublicKey import RSA 3 | import requests 4 | import re 5 | import signal 6 | import wienerAttack 7 | import datetime 8 | # Note this file is Linux only because of usage of signal. 9 | 10 | # TODO Add Sieve improvement to Fermat Attack 11 | # https://en.wikipedia.org/wiki/Fermat's_factorization_method 12 | class RSATool: 13 | """ 14 | RSA Factorization Utility written by Valar_Dragon for use in CTF's. 15 | It is meant for factorizing large modulii 16 | Currently it checks Factor DB, performs the Wiener Attack, fermat attack, and GCD between multiple keys. 17 | """ 18 | def __init__(self): 19 | #Eventually put logging here@ 20 | #this is the number to be added to x^2 in pollards rho. 21 | self.pollardRhoConstant1 = 1 22 | #this is the number to be multiplied to x^2 in pollards rho. 23 | self.pollardRhoConstant2 = 1 24 | self.keyNotFound = "key not found" 25 | 26 | 27 | def factorModulus(self,pubKey="pubkey",e="e",n="n",outFileName=""): 28 | if(type(pubKey)==type("pubkey")): 29 | self.e = e 30 | self.modulus = n 31 | else: 32 | self.e = pubKey.e 33 | self.modulus = pubKey.n 34 | self.outFileName = outFileName 35 | self.p = -1 36 | self.q = -1 37 | 38 | print("[*] Checking Factor DB...") 39 | self.checkFactorDB() 40 | if(self.p != -1 and self.q != -1): 41 | print("[*] Factors are: %s and %s" % (self.p,self.q)) 42 | return self.generatePrivKey() 43 | print("[x] Factor DB did not have the modulus") 44 | 45 | print("[*] Trying Wiener Attack...") 46 | if(len(str(self.e))*3 > len(str(self.modulus))): 47 | print("[*] Wiener Attack is likely to be succesful, increasing its timeout to 8 minutes") 48 | self.wienerAttack(wienerTimeout=8*60) 49 | else: 50 | self.wienerAttack() 51 | if(self.p != -1 and self.q != -1): 52 | print("[*] Wiener Attack Successful!!") 53 | print("[*] Factors are: %s and %s" % (self.p,self.q)) 54 | return self.generatePrivKey() 55 | print("[x] Wiener Attack Failed") 56 | 57 | print("[*] Trying Sieved Fermat Attack...") 58 | self.sieveFermatAttack() 59 | if(self.p != -1 and self.q != -1): 60 | print("[*] Sieved Fermat Attack Successful!!") 61 | print("[*] Factors are: %s and %s" % (self.p,self.q)) 62 | return self.generatePrivKey() 63 | 64 | print("[*] Trying Small Primes Factorization...") 65 | self.smallPrimes() 66 | if(self.p != -1 and self.q != -1): 67 | print("[*] Small Primes Factorization Successful!!") 68 | print("[*] Factors are: %s and %s" % (self.p,self.q)) 69 | return self.generatePrivKey() 70 | print("[x] Small Primes Factorization Failed") 71 | 72 | print("[*] Trying Pollards P-1 Attack...") 73 | self.pollardPminus1() 74 | if(self.p != -1 and self.q != -1): 75 | print("[*] Pollards P-1 Factorization Successful!!") 76 | print("[*] Factors are: %s and %s" % (self.p,self.q)) 77 | return self.generatePrivKey() 78 | 79 | return self.keyNotFound 80 | 81 | def factorModulii(self,pubkeys,outFileNameFormat="privkey-%s.pem"): 82 | success = [-1]*len(pubkeys) 83 | privkeys = [-1] * len(pubkeys) 84 | print("[*] Trying multi-key attacks") 85 | print("[*] Searching for common factors (GCD Attack)") 86 | for i in range(len(pubkeys)): 87 | for j in range(i): 88 | if(success[i]==True and True==success[j]): 89 | continue 90 | greatestCommonDivisor = gcd(pubkeys[i].n,pubkeys[j].n) 91 | if(greatestCommonDivisor != 1): 92 | print("[*] Common Factor Found between key-%s and key-%s!!!" 93 | % (i,j)) 94 | print("[*] Generating respective privatekeys") 95 | for k in [i,j]: 96 | success[k]=True 97 | privkeys[k] = (self.generatePrivKey(modulus=pubkeys[k].n, 98 | pubexp=pubkeys[k].e,p=greatestCommonDivisor, 99 | q=pubkeys[k].n//greatestCommonDivisor, 100 | outFileName=outFileNameFormat%k)) 101 | for i in range(len(pubkeys)): 102 | if(success[i]==True): 103 | print("Key #%s already factored!"%i) 104 | continue 105 | print("Factoring key #%s"%i) 106 | privkey = self.factorModulus(pubkeys[i],outFileName=outFileNameFormat%i) 107 | if(type(privkey) == type(self.keyNotFound)): 108 | success[i]==False 109 | else: 110 | privkeys[i] = (privkey) 111 | success[i]==True 112 | return privkeys 113 | 114 | 115 | #----------------BEGIN FACTOR DB SECTION------------------# 116 | 117 | def checkFactorDB(self, n="n"): 118 | """See if the modulus is already factored on factordb.com, 119 | and if so get the factors""" 120 | if(n=="n"): n = self.modulus 121 | # Factordb gives id's of numbers, which act as links for full number 122 | # follow the id's and get the actual numbers 123 | r = requests.get('http://www.factordb.com/index.php?query=%i' % self.modulus) 124 | regex = re.compile("index\.php\?id\=([0-9]+)", re.IGNORECASE) 125 | ids = regex.findall(r.text) 126 | # These give you ID's to the actual number 127 | p_id = ids[1] 128 | q_id = ids[2] 129 | # follow ID's 130 | regex = re.compile("value=\"([0-9]+)\"", re.IGNORECASE) 131 | r_1 = requests.get('http://www.factordb.com/index.php?id=%s' % p_id) 132 | r_2 = requests.get('http://www.factordb.com/index.php?id=%s' % q_id) 133 | # Get numbers 134 | self.p = int(regex.findall(r_1.text)[0]) 135 | self.q = int(regex.findall(r_2.text)[0]) 136 | if(self.p == self.q == self.modulus): 137 | self.p = -1 138 | self.q = -1 139 | 140 | 141 | 142 | #------------------END FACTOR DB SECTION------------------# 143 | #---------------BEGIN WIENER ATTACK SECTION---------------# 144 | #This comes from https://github.com/sourcekris/RsaCtfTool/blob/master/wiener_attack.py 145 | def wienerAttack(self,n="n",e="e",wienerTimeout=3*60): 146 | if(n=="n"): n = self.modulus 147 | if(e=="e"): e = self.e 148 | try: 149 | with timeout(seconds=wienerTimeout): 150 | wiener = wienerAttack.WienerAttack(n, e) 151 | if wiener.p is not None and wiener.q is not None: 152 | self.p = wiener.p 153 | self.q = wiener.q 154 | except TimeoutError: 155 | print("[x] Wiener Attack went over %s seconds "% wienerTimeout) 156 | 157 | 158 | #----------------END WIENER ATTACK SECTION----------------# 159 | #-----------BEGIN Fermat Factorization SECTION------------# 160 | 161 | # Maybe make this take a bigger lastDig? 162 | def isLastDigitPossibleSquare(self,x): 163 | if(x < 0): 164 | return False 165 | lastDig = x & 0xF 166 | if(lastDig > 9): 167 | return False 168 | if(lastDig < 2): 169 | return True 170 | if(lastDig == 4 or lastDig == 5 or lastDig == 9): 171 | return True 172 | return False 173 | 174 | # https://en.wikipedia.org/wiki/Fermat's_factorization_method 175 | # Fermat factorization method written by me, inspired from wikipedia :D 176 | # Limit is the number of a's to try. 177 | def fermatAttack(self,n="n",limit=100,fermatTimeout=3*60): 178 | if(n=="n"): n = self.modulus 179 | try: 180 | with timeout(seconds=fermatTimeout): 181 | a = self.floorSqrt(n)+1 182 | b2 = a*a - n 183 | for i in range(limit): 184 | if(self.isLastDigitPossibleSquare(b2)): 185 | b = self.floorSqrt(b2) 186 | if(b**2 == a*a-n): 187 | #We found the factors! 188 | self.p = a+b 189 | self.q = a-b 190 | return 191 | a = a+1 192 | b2 = a*a-n 193 | if(i==limit-1): 194 | print("[x] Fermat Iteration Limit Exceeded") 195 | except TimeoutError: 196 | print("[x] Fermat Timeout Exceeded") 197 | 198 | def genSquaresModSieve(self,sieve): 199 | squaresModSieve = {} 200 | #Range not starting from 0, because we have already checked that 201 | # N % sieve != 0 202 | # Use property that (a-x)^2 mod a = x^2 mod a 203 | if(sieve%2 == 0): 204 | sieve2 = sieve // 2 205 | for num in range(1,sieve2+1): 206 | mod = pow(num,2,sieve) 207 | if mod not in squaresModSieve: 208 | squaresModSieve[mod] = [num] 209 | else: 210 | squaresModSieve[mod].append(num) 211 | if(num != sieve2): 212 | squaresModSieve[mod].append(sieve-num) 213 | return squaresModSieve 214 | else: 215 | # There is a duplication issue using the above halving of the sieve. 216 | # and I don't want to add a delay by doing a search for duplicate values 217 | for num in range(1,sieve): 218 | mod = pow(num,2,sieve) 219 | if mod not in squaresModSieve: 220 | squaresModSieve[mod] = [num] 221 | else: 222 | squaresModSieve[mod].append(num) 223 | return squaresModSieve 224 | 225 | # Create an array of possible a values for this N and sieveModulus 226 | # What we're doing is using that only a few numbers can be squares mod Sieve, 227 | # you use the idea that a^2 mod x, can only be a few different values. 228 | # b^2 = a^2 - N, so taking everything mod x, b^2 must also be one of those few different values 229 | # So the candidateA, are values of a, which when squared and subtracted by N, are still a number 230 | # that COULD potentially be a square mod x. This lowers our brute space in the Fermat Attack! 231 | def getCandidateA(self,sieveModulus,N="RSA modulus",secondIter=False): 232 | nModSieve = N % sieveModulus 233 | squaresModSieve = self.genSquaresModSieve(sieveModulus) 234 | candidateA = [] 235 | 236 | # potential a values: 237 | for mod in squaresModSieve: 238 | if(((mod - nModSieve) % sieveModulus) in squaresModSieve): 239 | for x in squaresModSieve[mod]: 240 | candidateA.append(x) 241 | 242 | # any number thats a solution mod x, must also be a solution mod 2x 243 | # and vice versa. Depending on N and the sieve used, it can save many modulii 244 | # from being checked. Un comment print statement to see effect. 245 | if(not secondIter): 246 | if(sieveModulus % 2 == 0): 247 | candidateA2 = self.getCandidateA(sieveModulus*2, N=N, secondIter = True) 248 | candidateAFinal = [] 249 | for i in candidateA: 250 | if(i in candidateA2): 251 | candidateAFinal.append(i) 252 | # print("%s numbers per modular ring are saved" % (len(candidateA) - len(candidateAFinal))) 253 | return candidateAFinal 254 | return candidateA 255 | 256 | 257 | # https://en.wikipedia.org/wiki/Fermat's_factorization_method#Sieve_improvement 258 | # This code is based upon the sieve improvement presented there. 259 | # Limit is the number of a's to try. 260 | def sieveFermatAttack(self,N="RSA modulus",sieveModulus=4500,limit=1000,fermatTimeout=3*60): 261 | if(N=="RSA modulus"): N = self.modulus 262 | try: 263 | with timeout(seconds=fermatTimeout): 264 | 265 | # ASSUME THAT N is not divisible by anything in sieveModulus 266 | # confirm via small primes first. 267 | #This lets me remove 0 from genSquaresModSieve, thus boosting times 268 | # GCD = gcd(sieveModulus,N) 269 | # if(GCD != 1): 270 | # self.p = GCD 271 | # self.q = N // GCD 272 | # return 273 | 274 | candidateA = self.getCandidateA(sieveModulus,N) 275 | # print(candidateA) 276 | # Redefine limit accordingly. 277 | limit = limit // len(candidateA) 278 | print("[*] %s %% faster than standard Fermat Factorization" % (100-100*len(candidateA)/sieveModulus)) 279 | a = self.floorSqrt(N)+1 280 | a = a - (a%sieveModulus) 281 | b2 = a*a - N 282 | 283 | 284 | for i in range(limit): 285 | for aModSieve in candidateA: 286 | aPlusMod = a + aModSieve 287 | b2 = aPlusMod*aPlusMod-N 288 | if(b2 < 0): 289 | continue 290 | if(self.isLastDigitPossibleSquare(b2)): 291 | b = self.floorSqrt(b2) 292 | if(pow(b,2) == b2): 293 | #We found the factors! 294 | self.p = aPlusMod+b 295 | self.q = aPlusMod-b 296 | return 297 | a = a+sieveModulus 298 | if(i==limit-1): 299 | print("[x] Sieved Fermat Iteration Limit Exceeded") 300 | 301 | except TimeoutError: 302 | print("[x] Sieved Fermat Timeout Exceeded") 303 | 304 | # Brute forces which SieveModulus has the least amount of candidates per sieveMod 305 | # I reccomend using startVal > 10, lower than that, I don't really trust the result 306 | 307 | def bruteBestSieveModulus(self,startVal,endVal,N="RSA modulus"): 308 | if(N=="RSA modulus"): N = self.modulus 309 | # index 0 = % speed up, index 1 = what the SieveMod is 310 | bestSpeedUp = [-1,-1] 311 | for sieveModulus in range(startVal,endVal): 312 | candidateA = self.getCandidateA(sieveModulus,N) 313 | speedUp = 1-len(candidateA)/sieveModulus 314 | if(speedUp > bestSpeedUp[0]): 315 | bestSpeedUp = [speedUp,sieveModulus] 316 | return bestSpeedUp[1] 317 | 318 | #------------END Fermat Factorization SECTION-------------# 319 | #----------------BEGIN SMALL PRIME SECTION----------------# 320 | def smallPrimes(self,n="n",upperlimit=1000000): 321 | if(n=="n"): n = self.modulus 322 | from sympy import sieve 323 | for i in sieve.primerange(1,upperlimit): 324 | if(n % i == 0): 325 | self.p = i 326 | self.q = n // i 327 | return 328 | 329 | #-----------------END SMALL PRIME SECTION-----------------# 330 | #----------------BEGIN POLLARDS P-1 SECTION---------------# 331 | 332 | #Pollard P minus 1 factoring, using the algorithm as described by 333 | # https://math.berkeley.edu/~sagrawal/su14_math55/notes_pollard.pdf 334 | # Then I further modified it by using the standard "B" as the limit, and only 335 | # taking a to the power of a prime. Then from looking at wikipedia and such, 336 | # I took the gcd out of the loop, and put it at the end. 337 | # TODO Update this to official wikipedia definition, once I find an explanation of 338 | # Wikipedia definition. (I.e. Why it works) 339 | def pollardPminus1(self,N="modulus",a=7,B=2**16,pMinus1Timeout=3*60): 340 | if(N=="modulus"): N = self.modulus 341 | from sympy import sieve 342 | try: 343 | with timeout(seconds=pMinus1Timeout): 344 | brokeEarly = False 345 | for x in sieve.primerange(1, B): 346 | tmp = 1 347 | while tmp < B: 348 | a = pow(a, x, N) 349 | tmp *= x 350 | d = gcd(a-1,N) 351 | if(d==N): 352 | #try next a value 353 | print('[x] Unlucky choice of a, try restarting Pollards P-1 with a different a') 354 | brokeEarly = True 355 | return 356 | elif(d>1): 357 | #Success! 358 | self.p = d 359 | self.q = N//d 360 | return 361 | if(brokeEarly == False): 362 | print("[x] Pollards P-1 did not find the factors with B=%s"% B) 363 | except TimeoutError: 364 | print("[x] Pollard P-1 Timeout Exceeded") 365 | 366 | 367 | #-----------------END POLLADS P-1 SECTION-----------------# 368 | #---------------BEGIN POLLARDS RHO SECTION----------------# 369 | def pollardf(self,x): 370 | return (self.pollardRhoConstant2*x*x + self.pollardRhoConstant1) % self.modulus 371 | 372 | def pollardsRho(self,n="modulus",rhoTimeout=5*60): 373 | if(n=="modulus"): n = self.modulus 374 | """ 375 | Pollard's Rho method for factoring numbers. 376 | Explanation I based this off of: 377 | https://www.csh.rit.edu/~pat/math/quickies/rho/#algorithm 378 | This is apparently not the standard definition, and doesn't work well. 379 | """ 380 | xValues = [1] 381 | i = 2 382 | 383 | with timeout(seconds=rhoTimeout): 384 | while(True): 385 | if(i % 2 == 0): 386 | #if(i%100000==0): 387 | #print("on iteration %s " % i ) 388 | #Calculate GCD(n, x_k - x_(k/2)), to conserve memory I'm popping x_k/2 389 | x_k = self.pollardf(i) 390 | xValues.append(x_k) 391 | x_k2 = xValues.pop(0) 392 | #if x_k2 >= x_k, their difference is negative and thus we can't do the GCD 393 | if(x_k2 < x_k): 394 | commonDivisor = gcd(n,x_k - x_k2) 395 | if(commonDivisor > 1): 396 | print("[*] Pollards Rho completed in %s iterations!" % i) 397 | #print("Factors: " + str(commonDivisor) + ", " + str(n / commonDivisor)) 398 | assert commonDivisor * (n // commonDivisor) == n 399 | 400 | return (commonDivisor, n // commonDivisor) 401 | else: 402 | #Just append new x value 403 | xValues.append(self.pollardf(i)) 404 | i+=1 405 | 406 | #-----------------END POLLADS RHO SECTION-----------------# 407 | #---------------BEGIN COMMON MODULUS ATTACK---------------#\ 408 | def commonModulusPubExpSamePlainText(self,e1,e2,c1,c2,n="n"): 409 | """ 410 | Solves for message if you have two ciphertexts of the same message 411 | encrypted with different public exponents and same modulus. 412 | Source: https://crypto.stackexchange.com/questions/16283/how-to-use-common-modulus-attack 413 | """ 414 | if(n=="n"): n = self.modulus 415 | GCD, s1, s2 = self.extended_gcd(e1, e2) 416 | assert GCD == 1 417 | assert s1*e1 + s2*e2 == 1 418 | message = 1 419 | if(s1 < 0): 420 | inv = self.modinv(c1,n) 421 | message = message*pow(inv,-1*s1,n) % n 422 | message = message*pow(c2,s2,n) %n 423 | elif(s2 < 0): 424 | inv = self.modinv(c2,n) 425 | message = message*pow(inv,-1*s2,n) % n 426 | message = message*pow(c1,s1,n) %n 427 | else: 428 | message = pow(c1,s1,n)*pow(c2,s2,n) % n 429 | return message 430 | #----------------END COMMON MODULUS ATTACK----------------# 431 | #----------BEGIN INVALID PUBLIC EXPONENT SECTION----------# 432 | 433 | def invalidPubExponent(self,c,p="p",q="q",e="e"): 434 | """Recovers some bytes of ciphertext if n is factored, but e was invalid. 435 | (Like e=100) The vast majority of bytes are however lost, as we are taking the 436 | GCD(e, totient(N))th root of the Ciphertext. Therefore only the most significant 437 | bits of the ciphertext may be recovered. 438 | Returns plaintext, since a key can't be formed from a non-integer exponent""" 439 | # Explanation of why this works: There exists no modinv if GCD(e,Totient(N)) != 1 440 | # but let x be e/GCD 441 | # then there is a modular inverse of x to totient n 442 | # c = m^(GCDx) mod n 443 | # c^(x^-1) = m^GCD mod n, where x^-1 denotes modinv(x,totientN) 444 | # Now if we take the GCD-th root 445 | # c^(x^-1)^(1/GCD) = m mod n, except that roots aren't an operation defined on modular rings 446 | # They are defined on finite fields in some circumstances, but this is not a finite field. 447 | # Therefore we have only recovered a few of the most significant bits of c. 448 | if(p=="p"): p = self.p 449 | if(p=="q"): q = self.q 450 | totientN = (p-1)*(q-1) 451 | n = p*q 452 | if(e=="e"): e = self.e 453 | GCD = gcd(e,totientN) 454 | if(GCD == 1): 455 | return "[X] This method only applies for invalid Public Exponents." 456 | d = self.modinv(e//GCD,totientN) 457 | c = pow(c,d,n) 458 | import sympy 459 | plaintext = sympy.root(c,GCD) 460 | return plaintext 461 | 462 | #-----------END INVALID PUBLIC EXPONENT SECTION-----------# 463 | #-----------BEGIN PARTIAL KEY RECOVERY SECTION------------# 464 | # TODO Implement Coppersmith, and get a quarter d partial key recovery attack 465 | 466 | def halfdPartialKeyRecoveryAttack(self,d0,d0BitSize,nBitSize="nBitSize",n="n",e="e", outFileName="None"): 467 | """ 468 | Recovers full private key given more than half of the private key. Links: 469 | http://www.ijser.org/researchpaper/Attack_on_RSA_Cryptosystem.pdf 470 | http://honors.cs.umd.edu/reports/lowexprsa.pdf 471 | """ 472 | if(n=="n"): n = self.modulus 473 | if(nBitSize == "nBitSize"): 474 | import sympy as sp 475 | nBitSize = int(sp.floor(sp.log(n)/sp.log(2)) + 1) 476 | if(e=="e"): e = self.e 477 | test = pow(3, e, n) 478 | test2 = pow(5, e, n) 479 | if(d0BitSize < nBitSize//2): 480 | return "Not enough bits of d0" 481 | # The idea is that ed - k(N-p-q+1)=1 by definitions (1) 482 | # d < totient(N) since its modInv(e,Totient(n)), so k can't be bigger than e 483 | # Therefore k is on range(1,e) 484 | # But we don't have totient(N), we have N, so its only an approximation 485 | # Proofs are in the links, but if you switch totientN with just N in the above, 486 | # and set d' = (k*N + 1)/e , 487 | # the maximum error in d' is 3*sqrt(nBitSize) bits 488 | # Thats less than d/2, so we can just replace the least significant bits with d0 489 | # and get plaintext 490 | for k in range(1,e): 491 | # This is guaranteed to be accurate to nBitSize^(1/3), 492 | # so we replace last bits with d 493 | d = ((k * n + 1) // e) 494 | # Chop of last d0 bits of d, and put d0 there. 495 | d >>= d0BitSize 496 | d <<= d0BitSize 497 | d |= d0 498 | # This condition must be true from modulo def. (1) And avoids computing many modpows 499 | if((e * d) % k == 1): 500 | # Were testing that d is valid by decoding two test messages 501 | if pow(test, d, n) == 3: 502 | if pow(test2, d, n) == 5: 503 | # From (1) 504 | totientN = (e*d - 1) // k 505 | #totient(N) = (p-1)(q-1) = n - p - q + 1 506 | # p^2 - p^2 - N + N = 0 507 | # p^2 - p^2 - pq + N = 0 508 | # p^2 + (-p -q)p + N = 0 509 | # p^2 + (totient(N) -n -1) + N = 0 510 | # Solving this quadratic for variable p: 511 | b = totientN - n - 1 512 | discriminant = b*b - 4*n 513 | #make sure discriminant is perfect square 514 | root = self.floorSqrt(discriminant) 515 | if(root*root != discriminant): 516 | continue 517 | p = (-b + root) // 2 518 | q = n // p 519 | self.p = p 520 | self.q = q 521 | #print("[*] Factors are: %s and %s" % (self.p,self.q)) 522 | return self.generatePrivKey(modulus=n,pubexp=e,outFileName=outFileName) 523 | 524 | 525 | def dpPartialKeyRecoveryAttack(self,dp,n="n",e="e", outFileName="None"): 526 | """ 527 | Recovers full private key given d_p for CRT version of RSA. Links: 528 | https://www.iacr.org/archive/crypto2003/27290027/27290027.pdf 529 | """ 530 | if(n=="n"): n = self.modulus 531 | if(e=="e"): e = self.e 532 | 533 | for k in range(1,e): 534 | if((e * dp) % k == 1): 535 | p = (e * dp - 1 + k) // k 536 | if(n%p==0): 537 | q = n // p 538 | self.p = p 539 | self.q = q 540 | 541 | return self.generatePrivKey(modulus=n,pubexp=e,outFileName=outFileName) 542 | #--------------END PARTIAL KEY RECOVERY SECTION---------------# 543 | #---------------BEGIN SHARED ALGORITHM SECTION----------------# 544 | 545 | #moduliiValueDictionary is a dictionary with key = modulus, value = array of possible values 546 | def chineseRemainderTheorem(self,moduliiValueDictionary): 547 | # Now we have to iterate through every combination of elements in each array 548 | # We can be slightly inefficient, and just keep CRT'ing 2 arrays at a time 549 | # one array being new array, other array being prevIteration 550 | 551 | # CRT first two arrays 552 | keys = list(moduliiValueDictionary.keys()) 553 | curCRTCandidateA = [] 554 | M = keys[0]*keys[1] 555 | 556 | # M // sieveModulus[0] = sieveModulus[1] 557 | 558 | b0 = self.modinv(keys[1],keys[0]) 559 | b1 = self.modinv(keys[0],keys[1]) 560 | 561 | for element0 in moduliiValueDictionary[keys[0]]: 562 | ab0 = element0*b0* keys[1] 563 | for element1 in moduliiValueDictionary[keys[1]]: 564 | ab1 = element1*b1 * keys[0] 565 | curCRTCandidateA.append((ab0 + ab1) % M) 566 | 567 | del moduliiValueDictionary[keys[0]] 568 | del keys[0] 569 | del moduliiValueDictionary[keys[0]] 570 | del keys[0] 571 | oldCRTCandidateA = curCRTCandidateA 572 | 573 | while(len(keys) > 0): 574 | oldCRTModulus = M 575 | curCRTCandidateA = [] 576 | M = M * keys[0] 577 | 578 | b0 = self.modinv(keys[0] ,oldCRTModulus) 579 | b1 = self.modinv(oldCRTModulus,keys[0]) 580 | 581 | for element0 in oldCRTCandidateA: 582 | ab0 = element0*b0*keys[0] 583 | for element1 in moduliiValueDictionary[keys[0]]: 584 | ab1 = element1*b1*oldCRTModulus 585 | curCRTCandidateA.append((ab0 + ab1) % M) 586 | 587 | del keys[0] 588 | 589 | return curCRTCandidateA,M 590 | 591 | def floorSqrt(self,n): 592 | x = n 593 | y = (x + 1) // 2 594 | while y < x: 595 | x = y 596 | y = (x + n // x) // 2 597 | return x 598 | 599 | def extended_gcd(self,aa, bb): 600 | """Extended Euclidean Algorithm, 601 | from https://rosettacode.org/wiki/Modular_inverse#Python 602 | """ 603 | lastremainder, remainder = abs(aa), abs(bb) 604 | x, lastx, y, lasty = 0, 1, 1, 0 605 | while remainder: 606 | lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) 607 | x, lastx = lastx - quotient*x, x 608 | y, lasty = lasty - quotient*y, y 609 | return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) 610 | 611 | def modinv(self,a, m): 612 | """Modular Multiplicative Inverse, 613 | from https://rosettacode.org/wiki/Modular_inverse#Python 614 | """ 615 | g, x, y = self.extended_gcd(a, m) 616 | if g != 1: 617 | raise ValueError 618 | return x % m 619 | 620 | def generatePrivKey(self, modulus="modulus",pubexp="e",p="p",q="q",outFileName="None"): 621 | if(modulus=="modulus"): modulus = self.modulus 622 | if(p=="p"): p = self.p 623 | if(pubexp=="e"): pubexp = self.e 624 | if(q=="q"): q = self.q 625 | if(outFileName==""): outFileName = self.outFileName 626 | if(outFileName==""): outFileName = "RSA_PrivKey_%s" % str(datetime.datetime.now()) 627 | totn = (p-1)*(q-1) 628 | privexp = self.modinv(pubexp,totn) 629 | assert p*q == modulus 630 | #Wieners attack returns "Integers" that throw type errors for not being "ints" 631 | #casting fixes this. This is likely due to use of sympy 632 | privKey = RSA.construct((modulus,pubexp,int(privexp),int(p),int(q))) 633 | #Write to File 634 | if(outFileName != "None"): 635 | open(outFileName,'bw+').write(privKey.exportKey()) 636 | print("Wrote private key to file %s " % outFileName) 637 | return privKey 638 | 639 | def generatePubKey(self, modulus="modulus",pubexp="e",outFileName="None"): 640 | if(modulus=="modulus"): modulus = self.modulus 641 | if(pubexp=="e"): pubexp = self.e 642 | if(outFileName==""): outFileName = self.outFileName 643 | if(outFileName==""): outFileName = "RSA_PubKey_%s" % str(datetime.datetime.now()) 644 | 645 | pubKey = RSA.construct((modulus,pubexp)) 646 | #Write to File 647 | if(outFileName != "None"): 648 | open(outFileName,'bw+').write(privKey.exportKey()) 649 | print("Wrote public key to file %s " % outFileName) 650 | return pubKey 651 | #----------------END SHARED ALGORITHM SECTION -----------------# 652 | 653 | class timeout: 654 | def __init__(self, seconds=1, error_message='[*] Timeout'): 655 | self.seconds = seconds 656 | self.error_message = error_message 657 | def handle_timeout(self, signum, frame): 658 | raise TimeoutError(self.error_message) 659 | def __enter__(self): 660 | signal.signal(signal.SIGALRM, self.handle_timeout) 661 | signal.alarm(self.seconds) 662 | def __exit__(self, type, value, traceback): 663 | signal.alarm(0) 664 | -------------------------------------------------------------------------------- /RSA/bleichenbacher.py: -------------------------------------------------------------------------------- 1 | import binascii 2 | import math 3 | import random 4 | 5 | 6 | def python_rsa_bleichenbacher(hashtype,msgHashed,modulusSize,e=3): 7 | """ 8 | This can forge RSA signatures for low exponents for the python RSA module, for any modulus 9 | The CVE was reported in http://www.openwall.com/lists/oss-security/2016/01/05/3 10 | So if the RSA module wasn't updated after that, you can forge the signature! 11 | https://blog.filippo.io/bleichenbacher-06-signature-forgery-in-python-rsa/ 12 | """ 13 | HASH_ASN1 = { 14 | 'MD5': b'\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10', 15 | 'SHA-1': b'\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14', 16 | 'SHA-256': b'\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20', 17 | 'SHA-384': b'\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30', 18 | 'SHA-512': b'\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40' 19 | } 20 | # we need to forge 00 01 XX XX XX ... XX XX 00 HASH_ASN1[hashtype] HASH 21 | # where the XX's make the whole thing same size as modulus 22 | 23 | # MAKE SUFFIX 24 | #print(msgHashed) 25 | #Its 10 0's because the first two 0's of the ASN.1 isn't getting printed with bin() 26 | targetSuffix = '0000000000' + bin(int(binascii.hexlify(HASH_ASN1[hashtype]),16))[2:] + bin(msgHashed)[2:] 27 | if(int(targetSuffix,2)%2 == 0): 28 | if(int(targetSuffix,2)%8 != 0): 29 | print("No solution for this hash!") 30 | return -1 31 | # print(targetSuffix) 32 | # print(hex(int(targetSuffix,2))) 33 | # s = our forgery 34 | # c = s^3 35 | # tgt = targetSuffix 36 | # key here is that nth bit, counting from LSB, only affects nth bit OR later in c 37 | 38 | # s starts out as bytes until first 1 in tgt 39 | s = targetSuffix[targetSuffix.rfind('1'):] 40 | c = sToC(s) 41 | 42 | initLenS = len(s) 43 | for index in range(initLenS,len(targetSuffix)): 44 | if(c[len(c)-index-1]==targetSuffix[len(targetSuffix)-index-1]): 45 | s = '0' + s 46 | else: 47 | s = '1' + s 48 | c = sToC(s) 49 | 50 | # SUFFIX MADE! 51 | 52 | assert(c[-len(targetSuffix):]==targetSuffix) 53 | if(len(c) > modulusSize): 54 | print("e is too big for this hash type. Try a smaller hash type.") 55 | return -2 56 | 57 | suffix ='00'+hex(int(s,2))[2:] 58 | 59 | # print("suffix is %s" % hex(int(s,2))) 60 | # print("suffix is %s" % hex(int(c,2))) 61 | 62 | valid = False 63 | import gmpy 64 | while(valid == False): 65 | valid = True 66 | # Generate prefix 67 | prefix = format(0,'08b') + format(1,'08b') 68 | prefix += ''.join([format(random.randint(1,256),'08b')]*((modulusSize-len(prefix))//8)) 69 | assert len(prefix) == modulusSize 70 | 71 | cRoot = gmpy.root(int(prefix,2),3) 72 | if(cRoot[1]==1): 73 | #Its a perfect cubed root! How unlikely :) 74 | cRoot = int(cRoot[0].digits()) 75 | else: 76 | cRoot = int(cRoot[0].digits()) 77 | 78 | prefix = hex(cRoot)[2:] 79 | final = prefix[:-len(suffix)] + suffix 80 | 81 | # print(final) 82 | # Message that is forged when cubed: 83 | # ('0'+hex(int(final,16)**3)[2:]) 84 | finalcubed = ('0'+hex(int(final,16)**3)[2:]) 85 | finalcubedbytes = chunks(finalcubed[:-len(suffix)],2) 86 | # print(finalcubed) 87 | 88 | for element in finalcubedbytes: 89 | if(element=='00'): 90 | valid = False 91 | print("NEXT ITERATION") 92 | return int(final,16) 93 | 94 | def sToC(s,e=3): 95 | s = int(s,2) 96 | if(s==1): 97 | return '00001' 98 | return bin(s**e)[2:] 99 | 100 | def chunks(l, n): 101 | n = max(1, n) 102 | return (l[i:i+n] for i in range(0, len(l), n)) 103 | 104 | def testFunction(): 105 | # msg = "right below" 106 | # Hash is hashed version of msg. 107 | print(hex(python_rsa_bleichenbacher('SHA-256',int('b24fbe5fba106419e028be32dd049736d797815f6a6f5370579437784c51eb9f',16),2048))) 108 | # Check against: nc challenge.uiuc.tf 11345 109 | # If it is still up 110 | -------------------------------------------------------------------------------- /RSA/hastads.sage: -------------------------------------------------------------------------------- 1 | def hastads(cArray,nArray,e=3): 2 | """ 3 | Performs Hastads attack on raw RSA with no padding. 4 | cArray = Ciphertext Array 5 | nArray = Modulus Array 6 | e = public exponent 7 | """ 8 | 9 | if(len(cArray)==len(nArray)==e): 10 | for i in range(e): 11 | cArray[i] = Integer(cArray[i]) 12 | nArray[i] = Integer(nArray[i]) 13 | M = crt(cArray,nArray) 14 | return(Integer(M).nth_root(e,truncate_mode=1)) 15 | else: 16 | print("CiphertextArray, ModulusArray, need to be of the same length, and the same size as the public exponent") 17 | 18 | 19 | def linearPaddingHastads(cArray,nArray,aArray,bArray,e=3,eps=1/8): 20 | """ 21 | Performs Hastads attack on raw RSA with no padding. 22 | This is for RSA encryptions of the form: cArray[i] = pow(aArray[i]*msg + bArray[i],e,nArray[i]) 23 | Where they are all encryptions of the same message. 24 | cArray = Ciphertext Array 25 | nArray = Modulus Array 26 | aArray = Array of 'slopes' for the linear padding 27 | bArray = Array of 'y-intercepts' for the linear padding 28 | e = public exponent 29 | """ 30 | if(len(cArray) == len(nArray) == len(aArray) == len(bArray) == e): 31 | for i in range(e): 32 | cArray[i] = Integer(cArray[i]) 33 | nArray[i] = Integer(nArray[i]) 34 | aArray[i] = Integer(aArray[i]) 35 | bArray[i] = Integer(bArray[i]) 36 | TArray = [-1]*e 37 | for i in range(e): 38 | arrayToCRT = [0]*e 39 | arrayToCRT[i] = 1 40 | TArray[i] = crt(arrayToCRT,nArray) 41 | P. = PolynomialRing(Zmod(prod(nArray))) 42 | gArray = [-1]*e 43 | for i in range(e): 44 | gArray[i] = TArray[i]*(pow(aArray[i]*x + bArray[i],e) - cArray[i]) 45 | g = sum(gArray) 46 | g = g.monic() 47 | # Use Sage's inbuilt coppersmith method 48 | roots = g.small_roots(epsilon=eps) 49 | if(len(roots)== 0): 50 | print("No Solutions found") 51 | return -1 52 | return roots[0] 53 | 54 | else: 55 | print("CiphertextArray, ModulusArray, and the linear padding arrays need to be of the same length," + 56 | "and the same size as the public exponent") 57 | 58 | def testLinearPadding(): 59 | from Crypto.PublicKey import RSA 60 | import random 61 | import binascii 62 | flag = b"flag{Th15_1337_Msg_is_a_secret}" 63 | flag = int(binascii.hexlify(flag),16) 64 | e = 3 65 | nArr = [-1]*e 66 | cArr = [-1]*e 67 | aArr = [-1]*e 68 | bArr = [-1]*e 69 | randUpperBound = pow(2,500) 70 | for i in range(e): 71 | key = RSA.generate(2048) 72 | nArr[i] = key.n 73 | aArr[i] = random.randint(1,randUpperBound) 74 | bArr[i] = random.randint(1,randUpperBound) 75 | cArr[i] = pow(flag*aArr[i]+bArr[i],e,key.n) 76 | msg = linearPaddingHastads(cArr,nArr,aArr,bArr,e=e,eps=1/8) 77 | if(msg==flag): 78 | print("Hastad's solver with linear padding is working! We got message: ") 79 | msg = hex(int(msg))[2:] 80 | if(msg[-1]=='L'): 81 | msg = msg[:-1] 82 | if(len(msg)%2 == 1): 83 | msg = '0' + msg 84 | print(msg) 85 | print(binascii.unhexlify(msg)) 86 | if(flag==binascii.unhexlify(msg)): 87 | return True 88 | -------------------------------------------------------------------------------- /RSA/hastadsSage.py: -------------------------------------------------------------------------------- 1 | 2 | # This file was *autogenerated* from the file hastads.sage 3 | from sage.all_cmdline import * # import sage library 4 | 5 | _sage_const_3 = Integer(3); _sage_const_2 = Integer(2); _sage_const_1 = Integer(1); _sage_const_0 = Integer(0); _sage_const_8 = Integer(8); _sage_const_500 = Integer(500); _sage_const_2048 = Integer(2048); _sage_const_16 = Integer(16) 6 | def hastads(cArray,nArray,e=_sage_const_3 ): 7 | """ 8 | Performs Hastads attack on raw RSA with no padding. 9 | cArray = Ciphertext Array 10 | nArray = Modulus Array 11 | e = public exponent 12 | """ 13 | 14 | if(len(cArray)==len(nArray)==e): 15 | for i in range(e): 16 | cArray[i] = Integer(cArray[i]) 17 | nArray[i] = Integer(nArray[i]) 18 | M = crt(cArray,nArray) 19 | return(Integer(M).nth_root(e,truncate_mode=_sage_const_1 )) 20 | else: 21 | print("CiphertextArray, ModulusArray, need to be of the same length, and the same size as the public exponent") 22 | 23 | 24 | def linearPaddingHastads(cArray,nArray,aArray,bArray,e=_sage_const_3 ,eps=_sage_const_1 /_sage_const_8 ): 25 | """ 26 | Performs Hastads attack on raw RSA with no padding. 27 | This is for RSA encryptions of the form: cArray[i] = pow(aArray[i]*msg + bArray[i],e,nArray[i]) 28 | Where they are all encryptions of the same message. 29 | cArray = Ciphertext Array 30 | nArray = Modulus Array 31 | aArray = Array of 'slopes' for the linear padding 32 | bArray = Array of 'y-intercepts' for the linear padding 33 | e = public exponent 34 | """ 35 | if(len(cArray) == len(nArray) == len(aArray) == len(bArray) == e): 36 | for i in range(e): 37 | cArray[i] = Integer(cArray[i]) 38 | nArray[i] = Integer(nArray[i]) 39 | aArray[i] = Integer(aArray[i]) 40 | bArray[i] = Integer(bArray[i]) 41 | TArray = [-_sage_const_1 ]*e 42 | for i in range(e): 43 | arrayToCRT = [_sage_const_0 ]*e 44 | arrayToCRT[i] = 1 45 | TArray[i] = crt(arrayToCRT,nArray) 46 | P = PolynomialRing(Zmod(prod(nArray)), names=('x',)); (x,) = P._first_ngens(1) 47 | gArray = [-_sage_const_1 ]*e 48 | for i in range(e): 49 | gArray[i] = TArray[i]*(pow(aArray[i]*x + bArray[i],e) - cArray[i]) 50 | g = sum(gArray) 51 | g = g.monic() 52 | # Use Sage's inbuilt coppersmith method 53 | roots = g.small_roots(epsilon=eps) 54 | if(len(roots)== _sage_const_0 ): 55 | print("No Solutions found") 56 | return -_sage_const_1 57 | return roots[_sage_const_0 ] 58 | 59 | else: 60 | print("CiphertextArray, ModulusArray, and the linear padding arrays need to be of the same length," + 61 | "and the same size as the public exponent") 62 | 63 | def testLinearPadding(): 64 | from Crypto.PublicKey import RSA 65 | import random 66 | import binascii 67 | flag = b"flag{Th15_1337_Msg_is_a_secret}" 68 | flag = int(binascii.hexlify(flag),_sage_const_16 ) 69 | e = _sage_const_3 70 | nArr = [-_sage_const_1 ]*e 71 | cArr = [-_sage_const_1 ]*e 72 | aArr = [-_sage_const_1 ]*e 73 | bArr = [-_sage_const_1 ]*e 74 | randUpperBound = pow(_sage_const_2 ,_sage_const_500 ) 75 | for i in range(e): 76 | key = RSA.generate(_sage_const_2048 ) 77 | nArr[i] = key.n 78 | aArr[i] = random.randint(_sage_const_1 ,randUpperBound) 79 | bArr[i] = random.randint(_sage_const_1 ,randUpperBound) 80 | cArr[i] = pow(flag*aArr[i]+bArr[i],e,key.n) 81 | msg = linearPaddingHastads(cArr,nArr,aArr,bArr,e=e,eps=_sage_const_1 /_sage_const_8 ) 82 | if(msg==flag): 83 | print("Hastad's solver with linear padding is working! We got message: ") 84 | msg = hex(int(msg))[_sage_const_2 :] 85 | if(msg[-_sage_const_1 ]=='L'): 86 | msg = msg[:-_sage_const_1 ] 87 | if(len(msg)%_sage_const_2 == _sage_const_1 ): 88 | msg = '0' + msg 89 | print(msg) 90 | print(binascii.unhexlify(msg)) 91 | if(binascii.unhexlify(msg)==flag): 92 | return True 93 | -------------------------------------------------------------------------------- /RSA/partialKnownMessage.sage: -------------------------------------------------------------------------------- 1 | def knownMessageFormatUnkownAtEnd(prefix,e,n,c,eps=1/8): 2 | # Solves for message if you know the prefix of the message, such that message = prefix+x 3 | # It requires that x < N 4 | ZmodN = Zmod(n) 5 | C = ZmodN(c) 6 | prefix = ZmodN(prefix) 7 | P. = PolynomialRing(ZmodN) 8 | pol = (prefix+x)^e - C 9 | diff = pol.small_roots(epsilon=eps) 10 | if(len(diff)==0): 11 | print("No solutions found") 12 | return -1 13 | return m+diff[0] 14 | 15 | def knownMessageFormat(message,e,c,n,unknownEndBitIndex,eps=1/15): 16 | """ 17 | unknownEndBitIndex is measured from the LSB being bit #0 18 | if unknownEndBitIndex is 0, it is knownMessageFormatUnkownAtEnd, but with epsilon solving capabilities. 19 | """ 20 | #TODO EPSILON SOLVING CAPABILITIES 21 | ZmodN = Zmod(n) 22 | c = ZmodN(c) 23 | e = ZmodN(e) 24 | message = ZmodN(message) 25 | P. = PolynomialRing(ZmodN) 26 | pol = ((message + ZmodN((pow(2,unknownEndBitIndex)))*x)^e) - c 27 | pol = pol.monic() 28 | 29 | xval = pol.small_roots(epsilon=eps) 30 | if(len(xval)==0): 31 | print("No solutions found") 32 | return -1 33 | xval = xval[0] 34 | xval = xval*(2**unknownEndBitIndex) 35 | return Integer(message+xval) 36 | 37 | def testKnownMessageFormat(): 38 | msg = "this challenge was supposed to be babyrsa but i screwed up and now i have to redo the challenge.\nhopefully this challenge proves to be more worthy of 250 points compared to the 200 points i gave out for babyrsa :D :D :D\nyour super secret flag is: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\nyou know what i'm going to add an extra line here just to make your life miserable so deal with it" 39 | msg = msg.replace('X','\x00') 40 | import binascii 41 | message = int(binascii.hexlify(msg),16) 42 | e = 5 43 | c = 321344338551168130701947757669249162791535374419225256466002854387287697945811581844875867845545337575193797350159207497966826027124926618458827324785590115214765980153475875175895244152171945352397663605222668892070894285036685408001675776259216704639659684767335997326195127379070104670798191048101430782486785148455557975065509824478935393935463232461294974471055239751453456270779997852527271795223623224696998441762750417393944955667837832299195592347653873362173157136283926817115042942127695355760288879165245940595259284499711202547364332122472169897570069773912201877037737474884548477516093671861643329899650704311880900221217905929830674467383904928054908475945599046498840246878554674443087280023564313470872269644230953001876937807402083390603760508851259383686896871724061532464374712413952574633098739843484563001012414107193262431117290853995664646176812763789444386869148000606985026530596652927567162641583951775993815884965569050328445927871220492529331846189285588168127051152438658813934744257031316581112434690871286836998078235766836485498780504037745116357109237384369621143931229920342036890494878183569174869563857473355851368119174926388706612127773670862261189669510108216517652686402185979222505401328291 44 | n = 805467500635696403604126524373650578882729068725582344971555936471728279008969317394226798274039587275908735628164913963756789131471531490012281262137708844664619411648776174742900969650281132608104486439462068493207388096754400356209191212924158917441463852311090597438686723680422989566039830705971272945580630621308622704812919416445637277433384864510484266136345300166188170847768250622904194100556098235897898548354386415341541887443486684297114240486341073977172459860420916964212739802004276614553755113124726331629822694410052832980560107812738167277181748569891715410067156205497753620739994002924247168259596220654379789860120944816884358006621854492232604827642867109476922149510767118658715534476782931763110787389666428593557178061972898056782926023179701767472969849999844288795597293792471883445525249025377326859655523448211020675915933552601140243332965620235850177872856558184848182439374292376522160931072677877590262080551636962148104050583711183119856867201924407132152091888936970437318064654447142605921825771487108398034919404885812834444299826080204996660391375038388918601615609593999711720104533648851576138805705999947802739408729788376315233147532770988216608571607302006681600662261521288802804512781133 45 | unknownEndBitIndex = Integer(8*(len(msg)-msg.rfind('\x00')-1)) 46 | return (binascii.unhexlify(hex(knownMessageFormat(message,e,c,n,unknownEndBitIndex)))) 47 | # testKnownMessageFormat() 48 | -------------------------------------------------------------------------------- /RSA/partialKnownMessageSage.py: -------------------------------------------------------------------------------- 1 | 2 | # This file was *autogenerated* from the file partialKnownMessage.sage 3 | from sage.all_cmdline import * # import sage library 4 | 5 | _sage_const_2 = Integer(2); _sage_const_1 = Integer(1); _sage_const_0 = Integer(0); _sage_const_5 = Integer(5); _sage_const_321344338551168130701947757669249162791535374419225256466002854387287697945811581844875867845545337575193797350159207497966826027124926618458827324785590115214765980153475875175895244152171945352397663605222668892070894285036685408001675776259216704639659684767335997326195127379070104670798191048101430782486785148455557975065509824478935393935463232461294974471055239751453456270779997852527271795223623224696998441762750417393944955667837832299195592347653873362173157136283926817115042942127695355760288879165245940595259284499711202547364332122472169897570069773912201877037737474884548477516093671861643329899650704311880900221217905929830674467383904928054908475945599046498840246878554674443087280023564313470872269644230953001876937807402083390603760508851259383686896871724061532464374712413952574633098739843484563001012414107193262431117290853995664646176812763789444386869148000606985026530596652927567162641583951775993815884965569050328445927871220492529331846189285588168127051152438658813934744257031316581112434690871286836998078235766836485498780504037745116357109237384369621143931229920342036890494878183569174869563857473355851368119174926388706612127773670862261189669510108216517652686402185979222505401328291 = Integer(321344338551168130701947757669249162791535374419225256466002854387287697945811581844875867845545337575193797350159207497966826027124926618458827324785590115214765980153475875175895244152171945352397663605222668892070894285036685408001675776259216704639659684767335997326195127379070104670798191048101430782486785148455557975065509824478935393935463232461294974471055239751453456270779997852527271795223623224696998441762750417393944955667837832299195592347653873362173157136283926817115042942127695355760288879165245940595259284499711202547364332122472169897570069773912201877037737474884548477516093671861643329899650704311880900221217905929830674467383904928054908475945599046498840246878554674443087280023564313470872269644230953001876937807402083390603760508851259383686896871724061532464374712413952574633098739843484563001012414107193262431117290853995664646176812763789444386869148000606985026530596652927567162641583951775993815884965569050328445927871220492529331846189285588168127051152438658813934744257031316581112434690871286836998078235766836485498780504037745116357109237384369621143931229920342036890494878183569174869563857473355851368119174926388706612127773670862261189669510108216517652686402185979222505401328291); _sage_const_8 = Integer(8); _sage_const_805467500635696403604126524373650578882729068725582344971555936471728279008969317394226798274039587275908735628164913963756789131471531490012281262137708844664619411648776174742900969650281132608104486439462068493207388096754400356209191212924158917441463852311090597438686723680422989566039830705971272945580630621308622704812919416445637277433384864510484266136345300166188170847768250622904194100556098235897898548354386415341541887443486684297114240486341073977172459860420916964212739802004276614553755113124726331629822694410052832980560107812738167277181748569891715410067156205497753620739994002924247168259596220654379789860120944816884358006621854492232604827642867109476922149510767118658715534476782931763110787389666428593557178061972898056782926023179701767472969849999844288795597293792471883445525249025377326859655523448211020675915933552601140243332965620235850177872856558184848182439374292376522160931072677877590262080551636962148104050583711183119856867201924407132152091888936970437318064654447142605921825771487108398034919404885812834444299826080204996660391375038388918601615609593999711720104533648851576138805705999947802739408729788376315233147532770988216608571607302006681600662261521288802804512781133 = Integer(805467500635696403604126524373650578882729068725582344971555936471728279008969317394226798274039587275908735628164913963756789131471531490012281262137708844664619411648776174742900969650281132608104486439462068493207388096754400356209191212924158917441463852311090597438686723680422989566039830705971272945580630621308622704812919416445637277433384864510484266136345300166188170847768250622904194100556098235897898548354386415341541887443486684297114240486341073977172459860420916964212739802004276614553755113124726331629822694410052832980560107812738167277181748569891715410067156205497753620739994002924247168259596220654379789860120944816884358006621854492232604827642867109476922149510767118658715534476782931763110787389666428593557178061972898056782926023179701767472969849999844288795597293792471883445525249025377326859655523448211020675915933552601140243332965620235850177872856558184848182439374292376522160931072677877590262080551636962148104050583711183119856867201924407132152091888936970437318064654447142605921825771487108398034919404885812834444299826080204996660391375038388918601615609593999711720104533648851576138805705999947802739408729788376315233147532770988216608571607302006681600662261521288802804512781133); _sage_const_16 = Integer(16); _sage_const_15 = Integer(15) 6 | def knownMessageFormatUnkownAtEnd(prefix,e,n,c,eps=_sage_const_1 /_sage_const_8 ): 7 | # Solves for message if you know the prefix of the message, such that message = prefix+x 8 | # It requires that x < N^(1/e - epsilon) 9 | ZmodN = Zmod(n) 10 | C = ZmodN(c) 11 | prefix = ZmodN(prefix) 12 | P = PolynomialRing(ZmodN, names=('x',)); (x,) = P._first_ngens(1) 13 | pol = (prefix+x)**e - C 14 | diff = pol.small_roots(epsilon=eps) 15 | if(len(diff)==_sage_const_0 ): 16 | print("No solutions found") 17 | return -_sage_const_1 18 | return m+diff[_sage_const_0 ] 19 | 20 | def knownMessageFormat(message,e,c,n,unknownEndBitIndex=0,eps=_sage_const_1 /_sage_const_15 ): 21 | """ 22 | unknownEndBitIndex is measured from the LSB being bit #0 23 | if unknownEndBitIndex is 0, it is knownMessageFormatUnkownAtEnd, but with epsilon solving capabilities. 24 | Likewise unknownStartBitIndex is measured from LSB also. 25 | Solves for message if you know the format of the message, such that message = format+x 26 | It requires that x < N^(1/e - epsilon) 27 | Thus this only works for low exponents. 28 | """ 29 | ZmodN = Zmod(n) 30 | c = ZmodN(c) 31 | e = ZmodN(e) 32 | message = ZmodN(message) 33 | P = PolynomialRing(ZmodN, names=('x',)); (x,) = P._first_ngens(1) 34 | pol = ((message + ZmodN((pow(_sage_const_2 ,unknownEndBitIndex)))*x)**e) - c 35 | pol = pol.monic() 36 | 37 | xval = pol.small_roots(epsilon=eps) 38 | if(len(xval)==_sage_const_0 ): 39 | print("No solutions found") 40 | return -_sage_const_1 41 | xval = xval[_sage_const_0 ] 42 | xval = xval*(_sage_const_2 **unknownEndBitIndex) 43 | return Integer(message+xval) 44 | 45 | def testKnownMessageFormat(): 46 | msg = "this challenge was supposed to be babyrsa but i screwed up and now i have to redo the challenge.\nhopefully this challenge proves to be more worthy of 250 points compared to the 200 points i gave out for babyrsa :D :D :D\nyour super secret flag is: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\nyou know what i'm going to add an extra line here just to make your life miserable so deal with it" 47 | msg = msg.replace('X','\x00') 48 | import binascii 49 | message = int(binascii.hexlify(msg),_sage_const_16 ) 50 | e = _sage_const_5 51 | c = _sage_const_321344338551168130701947757669249162791535374419225256466002854387287697945811581844875867845545337575193797350159207497966826027124926618458827324785590115214765980153475875175895244152171945352397663605222668892070894285036685408001675776259216704639659684767335997326195127379070104670798191048101430782486785148455557975065509824478935393935463232461294974471055239751453456270779997852527271795223623224696998441762750417393944955667837832299195592347653873362173157136283926817115042942127695355760288879165245940595259284499711202547364332122472169897570069773912201877037737474884548477516093671861643329899650704311880900221217905929830674467383904928054908475945599046498840246878554674443087280023564313470872269644230953001876937807402083390603760508851259383686896871724061532464374712413952574633098739843484563001012414107193262431117290853995664646176812763789444386869148000606985026530596652927567162641583951775993815884965569050328445927871220492529331846189285588168127051152438658813934744257031316581112434690871286836998078235766836485498780504037745116357109237384369621143931229920342036890494878183569174869563857473355851368119174926388706612127773670862261189669510108216517652686402185979222505401328291 52 | n = _sage_const_805467500635696403604126524373650578882729068725582344971555936471728279008969317394226798274039587275908735628164913963756789131471531490012281262137708844664619411648776174742900969650281132608104486439462068493207388096754400356209191212924158917441463852311090597438686723680422989566039830705971272945580630621308622704812919416445637277433384864510484266136345300166188170847768250622904194100556098235897898548354386415341541887443486684297114240486341073977172459860420916964212739802004276614553755113124726331629822694410052832980560107812738167277181748569891715410067156205497753620739994002924247168259596220654379789860120944816884358006621854492232604827642867109476922149510767118658715534476782931763110787389666428593557178061972898056782926023179701767472969849999844288795597293792471883445525249025377326859655523448211020675915933552601140243332965620235850177872856558184848182439374292376522160931072677877590262080551636962148104050583711183119856867201924407132152091888936970437318064654447142605921825771487108398034919404885812834444299826080204996660391375038388918601615609593999711720104533648851576138805705999947802739408729788376315233147532770988216608571607302006681600662261521288802804512781133 53 | unknownEndBitIndex = Integer(_sage_const_8 *(len(msg)-msg.rfind('\x00')-_sage_const_1 )) 54 | return (binascii.unhexlify(hex(knownMessageFormat(message,e,c,n,unknownEndBitIndex)))) 55 | # testKnownMessageFormat() 56 | -------------------------------------------------------------------------------- /RSA/testKeys/key-0.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA168ysJPW4iS7ljqae8hz 3 | sud8as52Pn1sbdfR0RGChS9oS1A91y52lP3sRmivv2+QxK9GYqvuHDozxQ7FxSqM 4 | CpqvTQ8xYeu07nYioi/x+2e5MCPUlDEwb/wBQBkbEHexFMyohNtMzdjR97sTHvMh 5 | tJBwA1SBYZIdKTpCYxiXCLoHVUUqZqbckWGIsmMBBTb9I56+2o2HembdhMtDH1pi 6 | q5CLZrTmTT5Xv7ozjhOwN3wDA9Y4YHVYZHhaHI9LX7R8b8Tyqf2FMHMjBzPGi3VL 7 | K0gBBwJzMwObsdhJExN+bfpHPpLUskr1fnMKSjT24BpBb5SoNVzPRpVM0m0lA7zq 8 | IJA+zXegHyaEzx18cSS0Xe+r1sK0fybcFCgSyDVzxBKBPwFoBOLBLzHKQz3t1HY0 9 | u+Pkk112KrblnnLqCTL/dfGIB6ixei9ogXY88wKLnhWlEUwGgX+wduBfTUH6Urnb 10 | eVmf9AehhWtOtHOPHO00CkQHBynCpWrXO2EkO2yplqINUFSN/LEddQaJrpNHEzH+ 11 | aMIpImh/FsSDCNOtdOjJv/jBdEwGdNIDpWwJnXvujvlNktm07D0ekZegrEkldUX8 12 | CeHtc51qEK3aCC5bGPfqqD54bumthYYHDqZdtPm1q7k5TaMvt01oyNSmTvXEoSzC 13 | nWEiZOc9JZo/1ojFVnVYvqkCAwEAAQ== 14 | -----END PUBLIC KEY----- 15 | -------------------------------------------------------------------------------- /RSA/testKeys/key-1.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxP9IaxTNnDe5VvCP8Zyi 3 | +D26hlCcuEDNalqV8TUgCbGNHVa0oP7A6VopypbK76pd7/cdausK2J7qrZCM7pNY 4 | K9cbLNfa9wmlS5jRY7UI0/0fCpcJ+2nkmdG4q8UK86TLrnfAcERJM2E6RSlU+RrN 5 | r0YdajZANZIFYfeIXTDr3IK+NWDmQohkuXFeFzTQE+I9+4wdpmL1zm2jcSQC+NpE 6 | XQykm5ux5Hq+7vWKY4XKP5650kAItuaOHefC8S/qFPdynCSNjbfZuF5ieatosFF/ 7 | c52XRboC+Kq8M4GcMmEWwyc5a1cWxolUla6NPPYKO2oRVXMpOD9tX0FNngXofhPV 8 | 18v4eZTIbxQZqPyWlQDjbYVw++G8E9+L/jiIIJsL1oS5Jlv39OBc9nDY8ojh2CdA 9 | 6YEvmqaKmbXlaUILOMwVOHh+rSU99TNB48JpfOdhUrAu1DfM4ZOG4qE2CL+3sjM2 10 | NW8DLFUPH7xPjuAClMvssD7ORd/F9cEV1zrcmIuilxBMgTUbtzwqwB06z8WoFMSU 11 | e1dYsBkyIhAsFUHzmNLXscLP3VOhcqqJmID1Ootcfmo55uQIFB35muL2vvwAsC4q 12 | xMOvEivlCX8yMcW05ge8oqeMHxBAqjxDUd5LMXLjiCwRbl9YbeM87pyRGHWsGW77 13 | g1XUzd/lR5sZ+kJqJeDqGJECAwEAAQ== 14 | -----END PUBLIC KEY----- 15 | -------------------------------------------------------------------------------- /RSA/testKeys/key-2.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAhphlSMArLWsEYadKCaXu 3 | TvoHiC1cYQvbFNG6METv/VVw5MUJ0RasqZKjQs9S7QRj221GSKMBO6ghnDpysZmH 4 | liU90R7MU2CH5uW9IHwTh6+d9r+HWrMZVW3MC61qkPAXRZdg7n0nT+YEbnWZOF92 5 | B9Ke0jVHdpXjNl/GufUnAYPpxMLBGKpnbB2cvgaGRQfkMQ2FuMrP+fWj7tSHtx0t 6 | dbAJQ9ftqar1srtpJxYl3iRp1qfE9QxO6sVLFgV5PMD3/pFnRS/1/vNkfJ7siGZz 7 | BzLAXcpMVvOTyi5h59dkQoIrnaVtlvZ7up9glfdh0PKj3mLqjG/HrC+ntydoSUf3 8 | ZAcRtwD0CheZ0CZe7+lJUrUOXhCxW+wUzBZkcUxsH/HBZFT0qRLsGXYNgMR1n/MT 9 | DaQ7E+eWfVzqUmQCzytWZlPAzV19CZU1dmHAMIy9EarrgyypCT3DmB0ftrYv2YqI 10 | Po1MFUhSHD4vC+92xyINgJPCvbGuAX8uSNDe/kLOVxOVWuKUvsK12puBz5ux2Mpe 11 | Xcyb+TDtt6P20tNQ0qpHjgEHDbwVHW+fbbpHPsABQy3k4s7UYRlV8pSz1IYx3VHr 12 | fFCpf1Flcx1ZcSnTM19MmUI02JCVM1xwXwdaG6CKD1zzg9Zc1CRSSkikFc4spaNL 13 | Qofk76yyQ+aLnJCjZ5vvJ1cCAwEAAQ== 14 | -----END PUBLIC KEY----- 15 | -------------------------------------------------------------------------------- /RSA/testKeys/key-3.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIIEITANBgkqhkiG9w0BAQEFAAOCBA4AMIIECQKCAgEAmUpeLCMDtAlD2bdEtXCe 3 | 5gH7XErDAM+kSnYIEHp00GrASWOj+CAfp4ATNe3T8yMJBCWSS3T2rDnur/e0pryq 4 | JBUz/V9XUFs4hmjyTY1lMwdFzFFe4bPJYBazmcNe7+8GErr/gnYQiBF7B+JfkmP5 5 | FJgQIzGRZdIJxHhLw3qS7X/stHAxez/eU0PN2aoTeUt0gxiSz26hAC16P3YPG7Pt 6 | +/YnOxU2ESdCTxcSiS4MbMdZs8aQ2oxhhKkL5khrjyXHRVVMCqpEV2RYmlF3A4pn 7 | zXPmb+Gw1Vngu74+W41K7vcv+odMwWEQu8E1w+mSjF/K5zeBX0n7Ajxk7aYq0u19 8 | DTIklhfcUS3FQABsDwWbL9rrOwrhwrlhXbfIO5CeIicZRRc24fB8ORnDll/Z0AO9 9 | iBPsHpzVQPr39w9y/o8PVEssq1GooGKGWuT0agUwt+EaJk1xfzzxO2AY0J3hoMKO 10 | ogzuKmcR2l0RX9ccCW0RXBPwteQNlGlsZxBcL3Ca5dL+CshYR7PJAXrOfbLrANQQ 11 | 2dLadoV3aoCZRy0BeRxXgQ0WCr1snkICdjIOsRuAoLL1ci4g6diCKh0UPJemPvgX 12 | M+UvJj46f3e2kAv5XaIVVE31HmHsxGjwN6KznM8VPZhLMqmkznV7uzh5jOCwgPUD 13 | zho5bUfhTMQb8Y407b2RN+sCggIAOA0B7bbsx15RBW72DeyAeowXNW6mZE7PYsK4 14 | V2P3n6ZfG1TU/yg/uwsLPm+lcYbFK+og4JY2jBlBQc3tdZeLvhTScJ0gFFYB0N1r 15 | fi3w3e1CpRTSmMaBgiibgkGqCa/r5/PQoYemVFuJoGzuUofoJXJk4EvQloPZtLOw 16 | Ty6oZ4LT43nlAU/2FiAseK2bCAG2fu7qrztDBVpvCWyb+xGfG1fHjG5AUKzzyWd/ 17 | kyV6K6q5/7wPVi/GTUaNY52wkM22JhASaPvChsXJhFq6+2wG/AYlkEzPMoN/sv1d 18 | Fg34Ngsz/i+lX7Q/1LoLpp3eRPcvngZQmmNuyEVoV1l7mlUwtDtsLxEDjJ/OcdXe 19 | vXtjx/sdr3yEN5CTsfnY9eHUq16W5IfErEzRYpdnpVng/pVpmXXTspafvEjmwFKb 20 | QuRQUaxc6Zi4p3clEtwyxIkCqZbD+9MVlnvmpANVYwiPO77nncMk/Qg7LlKfLRFL 21 | rl5t6lPd4+UYCBpKE+aWtQ7YpRusVlNTqYprhB+teY6XAVBimVakgWsdeWj2XO/n 22 | Gxkgc0Es3WnAwiIZpJxYkeY2ZirjQpypwqOimoklFnSzfAdvZiRLQfsijIJWiWfA 23 | lA5FT0l09o0YY/c5jd1iMfrox/9vg/rzG0cuda4mztWYGRsPYn3CdZ4qmoYKPjsD 24 | yvaKrL8= 25 | -----END PUBLIC KEY----- 26 | -------------------------------------------------------------------------------- /RSA/testKeys/key-4.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAqd/7zfgI5KUSC4dtS+B3 3 | zvIbbvO7zNrne2r8mI6gaMrVLG59F5cEk5TKrucB6Raz0ZLG/I+KssigvNx1z7HE 4 | NqkUwSgEa4ia618ciYUoVsrReaCVikrrh7p3jqYhh60ZMdW9z4XVc2H9KUGgduqb 5 | NlIRAod1XmY+Z5iStP8FGQQrCzqFqpn2I6EDfVA7JFzzIFw8WyQTmzq/CIH7wbD3 6 | 4DREFJ9pQn/XjNvHW2NKUWDpsqrb/Zz9YVCrCs5y3R2V4diEFTy+ndYkWHRaD+lQ 7 | FOifJjqXMP8iBbEI45hbudqaG2i0rh1SzsKzpTIOAjkunouALRkN5uT3U4jD+v2y 8 | uliQTs6qYTw9Z9ge3jgaDxWigivRpaGFTfOK6n0y5s+MONjWqNrzhL78XuBsm+Gk 9 | siFraQso36rr2dR7PZb93ZYRTcbfmx6yE0MJjvnmVA+6wMGaY82vbkUorkHSEuUN 10 | q3L/RSmwQuwi3Y1hFm0pVIVZ7X3kaTkXgURLruKPPsvteRaacTTaeF1HZTOs4v/j 11 | ruW5UBVJqAYa1Qs1LQFzXftMp9TQv3Wcnby7G6R5OjAjj5Wa0DO1aRkgs+L8eT/h 12 | VO6fbrxdZHRLUYpB4mgD0R8f2m0iOQTCYFS0xoXjZA2g4fTaZEW1V1esfk4YyTgW 13 | jB2MZPMesR5KqgnQyU/KmXMCAwEAAQ== 14 | -----END PUBLIC KEY----- 15 | -------------------------------------------------------------------------------- /RSA/testKeys/key-5.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAiO+DdXDEFh9e99bmXer7 3 | mEDP+uXzN317LE+o7pkob9qG0d13rsmn2XUTKMDQ20SB+KEItNhEJi6h+4vwKqRN 4 | ug+cArrxhrrDfgIxTEgneAOwiMKSEHaxVcSILPTCOXeWlZ7fIq9qL/dpykZo83Du 5 | oQSsAG3z/q1p4bfAC41OoLjpn5BMe2b61M6gMQkbZqITc8DMZNIVHYJ08SjRg6fz 6 | 1peWXxWQ8/JlYln9qb5BdRCUnashY8X0UNZiqJn8qjE0StDezVWPo+n5JHoj/kUc 7 | j4RqytGTYOZnIJCfQFBk9Xa2ySWggdSGX3vIYdURAcM9aVZWsz0WTjiUgjTbHNwP 8 | v4YIr/ZPZ9268+Pq2ILYq2mRbda5Is7GLz1TVnsOZE+ZCt0ksi0wIReNpHNVvfFx 9 | TOFC+Y0D2ve1JdDGrr9C8vXpNSWEulA/F3G/Wy7X93Ajw8guiu/HnTwi0Xez9uPV 10 | 45n1hrQEHLpeTNZuMP6WZt+fxiFvK6HQ/wAvodbxynh6MTCmpcqSn6c3yPzYbHU3 11 | Cbwj9U7d1sH8bRIZMukA9L4kIAMpQyus86qOb8noeiJkV9/iR0X8fJaTkPmS+Znq 12 | SSDPzMTEfAa5rrq6tMkfFNj/heJ1dvCgJ8pwCTwYXACLJ+gkMSFVHkcF/UbDVhSF 13 | q/L7qg/CioeHH+Lj9a+jBScCAwEAAQ== 14 | -----END PUBLIC KEY----- 15 | -------------------------------------------------------------------------------- /RSA/testKeys/key-6.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAvA1N2e1ExEwhc6vTsCVA 3 | GzZoFtkT97QnG3Grze0hqw0EwvxXejE7eUJ1hF27iegVHPS9OCXpJAyI65OoJMqo 4 | sLVjlg/8sS+8r82dOPvfh7E0OV0OoxYYa+ryRwpTWh2jUpwAXLkGLw1D64579M15 5 | Qlpsq2WhXJBXE6vO2/SnFcRkZb7Lup7WD9d7+C8DXYo5TFbxOJiDSyd8Z0kmGpyV 6 | siV0wfd4FVA0VYjPL/HSLq6xE3ruTUH24oh1mESk646MvfrqF3bTxF51UcmSQxfQ 7 | 7+NqaGr7OsihKrgJo97uJ9f2nya3C5fNHtUUJuSJ6ASIHcroAvunUcP4O2mDz8tM 8 | MMlmypLnvwiHSyhI4JjwIfGDroOb4wGR47zSzjgyXjmRxuczvwDPP2Cq7yt+vQVU 9 | +wyYCm9i21mXTn885Gr7JOQ+EH7I0cwOdy+Zf/DFpgL6i80Mu/eMwtGoSQOjzACz 10 | l4WMAsKPfAcH5m1twN4s50fZncQDi92STPPFNLzsbc89TwJH4wh185r3qw/aafyh 11 | LXEExRv21mr/LRIzj/v1HiQ63geN5swZMPhyw62R2PgiZo5W01LAFW5RMDPqIMDx 12 | Y9VYtpEZc0aE+Yz3id9y+MU00AilNcna/r6HdBQK3AxT7rAhhS7Cgre93OWMn/uH 13 | p7TyC5G/0E7YTqZWa8OX8dkCAwEAAQ== 14 | -----END PUBLIC KEY----- 15 | -------------------------------------------------------------------------------- /RSA/testScript.py: -------------------------------------------------------------------------------- 1 | from Crypto.PublicKey import RSA 2 | import RSATool 3 | import os 4 | 5 | keys =[] 6 | 7 | def loadBostonKeyPartyPEMs(): 8 | for i in range(7): 9 | key = RSA.importKey(open('testKeys/key-%s.pem' % i).read()) 10 | keys.append(key) 11 | 12 | def main(): 13 | loadBostonKeyPartyPEMs() 14 | 15 | print("[#] Checking factorModulii with Boston Key Party keys") 16 | # CHECK FOR ERRORS: 17 | # key-0, key-6 is GCD 18 | # key-1 is Fermat Attack 19 | # key-2 is Factordb 20 | # key-3 is Wiener Attack 21 | # key-4 is KEY NOT FOUND 22 | # key-5 is P-1 attack 23 | tool.factorModulii(keys,'/tmp/privkey-%s.pem') 24 | print("[*] Boston Key Party Checks completed") 25 | 26 | print("[#] Checking Sieved Fermat Attack") 27 | checkSievedFermatAttack() 28 | print("[#] Checking broken pub exp attack") 29 | checkBrokenPublicExponent() 30 | print("[#] Checking Half D Partial Key Recovery") 31 | checkHalfdPartialKeyRecoveryAttack() 32 | print("[#] Checking d_p partial key recovery") 33 | checkdpPartialKeyRecoveryAttack() 34 | print("[#] Checking Common Modulus, Different Public Exponent Attack") 35 | checkSameModulusDifferentPubExp() 36 | 37 | def checkSievedFermatAttack(): 38 | # primes taken from https://en.wikipedia.org/wiki/Prime_gap 39 | # Any primes would work, just these were easily accesible and spaced far apart 40 | p = int("1,294,268,491".replace(',','')) 41 | q = int("2,300,942,549".replace(',','')) 42 | tool.sieveFermatAttack(p*q,limit=100000000) 43 | if(tool.q == q or tool.q == p): 44 | print("[*] Sieved Fermat Factorization Check Passed") 45 | else: 46 | print("[x] q = %s" % tool.q) 47 | print("[x] p = %s" % tool.p) 48 | print("[x] Sieved Fermat Factorization Check FAILED") 49 | 50 | def checkBrokenPublicExponent(): 51 | #Using EasyCTF RSA 4 values 52 | p= 13013195056445077675245767987987229724588379930923318266833492046660374216223334270611792324721132438307229159984813414250922197169316235737830919431103659 53 | q= 12930920340230371085700418586571062330546634389230084495106445639925420450591673769061692508272948388121114376587634872733055494744188467315949429674451947 54 | e= 100 55 | C= 2536072596735405513004321180336671392201446145691544525658443473848104743281278364580324721238865873217702884067306856569406059869172045956521348858084998514527555980415205217073019437355422966248344183944699168548887273804385919216488597207667402462509907219285121314528666853710860436030055903562805252516 56 | 57 | RSASolver = RSATool.RSATool() 58 | RSASolver.invalidPubExponent(C,p,q,e) 59 | plaintext = str(bytearray.fromhex(hex(RSASolver.invalidPubExponent(C,p,q,e))[2:])) 60 | 61 | if('easyctf' in plaintext.lower()): 62 | print("[*] Broken Public Exponent Check Passed") 63 | else: 64 | print("[X] Broken Public Exponent Check FAILED") 65 | 66 | def checkHalfdPartialKeyRecoveryAttack(): 67 | # Using EasyCTF PremiumRSA Values 68 | n = int('0x6c451672f63e8ece9c3bde03f4483ed3d0e286c908a55b78e2d235021d95f4ba403e6cbaf14d15928867bb14ac855d7fbdc6ebbf99f151ab49832e70fdd19e8d29dfc4c4ca7329564a1d4182c1b02ef040d7e347e13db768203319357abe07b1ecaf5d099d3326d2639e0a5991ded8cb46b825709e0942e67f770520c26306e5f44c8ca72313106ff0dd9a90294edaa7e0097997ff2425c266e1d52c6935799a8cf7ebf12f88edd1dc683ffd252facf7fb3e9bca0467ebbb1dbe731e7ff9b245a78ca50e8f810202eef4e44ea0c01443584baf727b13aa2ba8978445345981a264fb15709f7b71b9611e0ef3f0b69c6a3ba9f12ea703bf742b3aa3fc1522d8d20466223bdfe5c2cc726d66a1416bcb26cab2976a915e6646143500e012896f355dea77e10a7ec36aacd547f66bf543a7d7841acbcd4f54ec267ad185984ef74a995ad7c141fa34f46956bb3d66db54c5f8f84252800d968cb1bd47b30030f3c54c8d45b2ed9e1809ae7aad3367a7d3b11c80539282b3deaa8e23bda567e09b87f33a60666e9247cc38c0d09666346d54e18fcd58e987fcfc1796ad4bc0cb498d5e100d640abdbdfcb45039464fe023679ad70fce916a5adffcb58520a22bbf1870cfe5fcbf651a30ace03a716b2a283bfaa076330abd502e1460f2182e64b565c3c1b3a77312fe98e77dd1b8eca1f80fe11d6f2675f9ea90cc533abd507dc285',0) 69 | e = int('0x10001',0) 70 | d0 = int('0xa5cb79ef8059485d8ee47a9da0ed128ea83febf509c009aafcada53d35b28a7b020f7308078257aae306052f2086fa89ad9c810a4fd9afe498825bdc16b3050e6e26c2ebcc49de22ab34c09e53a699f29252adc01c1a3c036f192105154d94858bbaf42bf1dfadc0cdf7338c5c9e9fdf9c508bdc9d260df831b781e5ce33b874999ebb0f07d72bbe6d0971a2164b660e1d3df4cb265e8edbc63ec56c2b05ce2eb32cf9808931a3968f1045c38ea022bfd750c3925073d1c5befec2268efe0bd047f2411f081aee2b71c443c5fd26fed6a75c9e31b89dfd93180215eaa51117bcf4be54f140fc39322c5deb32ae1ec164f4ae451a1391d7b612645c06cdf83541',0) 71 | c = int('0x36e7437512d71ca2a412fa411f7d376feaf02db7a6c301284ed9dc7dcffa8a658c24d199aa14d008ed72a88e36e2c5520caf95c88e5deb0d311d4fe2641732455bde7bc1c64a7274bcbe3825cd59b66727354fbbd01ab4ea39dbddd765395fa9c653556987f2f7efbdf86e741573338699e7fb7ad8405eeb02bc8fbca39a55870255328fcd44998bb5339805298575c0aef9bcfe791e8330bac92cd11620ad837ac2f7e9fcc4bf61da3c09cb8455e6d46890d5beb0b1af0bf989c10c6d83604de862bbb82fc697c2513488a9e3321d2590e9f5c0eb4a1882aa26c455da6e45f1fff42e233208ebd494365e89fb8e1ae89ea5b2f800e07b9e6b362bf4caaec11e81a8fc04377a7820f1392057f44bcbac03e9846b29989106e0dcf98559af1d5221aea01dd0d64667eb6615f7cce13e004249f2a0ccf065044450c1bd6661a986a53c983bf810d961f5c0a551fa66a08cf6cabf4e08291f1a08c7ee73c3b7c51a6d1620c9005530b8c1ce883eae095b1949eb4df159a35c7ce654cfc18527f08c8483d3630803bd688040a4b4bae86766f5535421bb8ec9c6e071b280f9e0db26c1cc90b56dba1cd09adeb520a996d6fd6ce135edb9e496986770cff49abc68473edc51ce0c79db915aae4ce1bb6fd42adb62b6b350cb84d37c52f30fe1e4943babf868bed50fa912ca431500ecb18643bb3df560450f673769818fdc48cdcdf6',0) 72 | bitLenD0 = 2048 73 | 74 | privkey = tool.halfdPartialKeyRecoveryAttack(d0,2048,n=n,e=e) 75 | c = pow(c,tool.modinv(e, (tool.p-1)*(tool.q-1)) ,n) 76 | plaintext = str(bytearray.fromhex(hex(c)[2:])) 77 | if('easyctf' in plaintext.lower()): 78 | print("[*] Half D Partial Key Recovery Check Passed") 79 | else: 80 | print("[X] Half D Partial Key Recovery Check FAILED") 81 | 82 | def checkSameModulusDifferentPubExp(): 83 | n = 833929583326835661493412421421662334710101847251478730732141353414827268108037510962529108456417073055556084152064297022357597449531697186108107117859195056928214895471459318573608151418964034964984867719532223146075807387934141330521748837197938956194347619538946483679260989736316020197725907183265791327386423769106495481318669361956865035871161895075261785645079802263842746572189561104373559922766419282816535392616146974645050083778891169886988692336045288728531377610182411690456891969179370179800783814565270217378150097369499544065595857519228220649098897913490514002554851163704900152203185649251074924165791134196440278209720829456199310354118738683991857330290586217732920652996263113335590597564878311516547127241065734076446464717118639221604877123046024278717844928169662197952638149868037658306153218634332570768923620937370153917962338547598020701710448055951029770847548900433672859909577007321124626850784967355695546710601996652826387942803174541171682129290332326308134030363894446885678944647443990146534124177804565577435112159346409741998338246431532425335878875056521201105991481353990730019704883140241877901874769813208089330143726859679405180356547887663780892266276887772858880708447393520689502162042531 84 | e1 = 65537 85 | e2 = 65539 86 | msg = 85189518985198159851985981589493930202952058280 87 | c1 = pow(msg,e1,n) 88 | c2 = pow(msg,e2,n) 89 | if(tool.commonModulusPubExpSamePlainText(e1,e2,c1,c2,n)==msg): 90 | print("[*] Common Modulus Check Passed") 91 | else: 92 | print("[X] Common Modulus Check FAILED") 93 | 94 | def checkdpPartialKeyRecoveryAttack(): 95 | dp = 10169576291048744120030378521334130877372575619400406464442859732399651284965479823750811638854185900836535026290910663113961810650660236370395359445734425 96 | n = 211767290324398254371868231687152625271180645754760945403088952020394972457469805823582174761387551992017650132806887143281743839388543576204324782920306260516024555364515883886110655807724459040458316068890447499547881914042520229001396317762404169572753359966034696955079260396682467936073461651616640916909 97 | e = 65537 98 | c = 42601238135749247354464266278794915846396919141313024662374579479712190675096500801203662531952565488623964806890491567595603873371264777262418933107257283084704170577649264745811855833366655322107229755242767948773320530979935167331115009578064779877494691384747024161661024803331738931358534779829183671004 99 | privkey = tool.dpPartialKeyRecoveryAttack(dp,n=n,e=e) 100 | m = pow(c,tool.modinv(e,(privkey.p-1)*(privkey.q-1)),n) 101 | m = hex(m)[2:] 102 | import binascii 103 | if(len(m)%2 == 1): 104 | m = '0'+m 105 | if(b'flag' in binascii.unhexlify(m)): 106 | print("[*] full d_p private key recovery Check Passed") 107 | else: 108 | print("[X] full d_p private key recovery Check FAILED") 109 | 110 | tool = RSATool.RSATool() 111 | main() 112 | -------------------------------------------------------------------------------- /RSA/testScript.sage: -------------------------------------------------------------------------------- 1 | 2 | import FranklinReiterSage 3 | import hastadsSage 4 | import partialKnownMessageSage 5 | 6 | def main(): 7 | 8 | print("[#] BEGIN CHECKING SAGE FILES") 9 | print("[#] Franklin Reiter Check") 10 | if(FranklinReiterSage.testFranklinReiter()): 11 | print("[*] Franklin Reiter Check Passed") 12 | else: 13 | print("[X] Franklin Reiter Check FAILED") 14 | print("[#] Partial Known Message(Coppersmith) Check") 15 | if("bu7_0N_4_w3Dn3sdAy_iN_a_c4f3_i_waTcH3dD_17_6eg1n_aga1n" in partialKnownMessageSage.testKnownMessageFormat()): 16 | print("[*] Partial Known Message(Coppersmith) Check Passed") 17 | else: 18 | print("[X] Partial Known Message(Coppersmith) Check FAILED") 19 | print("[#] Linear Padding Hastads Check") 20 | if(hastadsSage.testLinearPadding()): 21 | print("[*] Linear Padding Hastads Check Passed") 22 | else: 23 | print("[X] Linear Padding Hastads Check FAILED") 24 | 25 | print("[#] Coppersmith Shortpad Attack Check") 26 | print("This check passes if flag{This_Msg_Is_2_1337} is in the output") 27 | FranklinReiterSage.testCoppersmithShortPadAttack() 28 | 29 | main() 30 | -------------------------------------------------------------------------------- /RSA/testScriptSage.py: -------------------------------------------------------------------------------- 1 | 2 | # This file was *autogenerated* from the file testScript.sage 3 | from sage.all_cmdline import * # import sage library 4 | 5 | 6 | import FranklinReiterSage 7 | import hastadsSage 8 | import partialKnownMessageSage 9 | 10 | def main(): 11 | 12 | print("[#] BEGIN CHECKING SAGE FILES") 13 | print("[#] Franklin Reiter Check") 14 | if(FranklinReiterSage.testFranklinReiter()): 15 | print("[*] Franklin Reiter Check Passed") 16 | else: 17 | print("[X] Franklin Reiter Check FAILED") 18 | print("[#] Coppersmith Shortpad Attack Check") 19 | print("This check passes if flag{This_Msg_Is_2_1337} is in the output") 20 | FranklinReiterSage.testCoppersmithShortPadAttack() 21 | print("[#] Partial Known Message(Coppersmith) Check") 22 | if("bu7_0N_4_w3Dn3sdAy_iN_a_c4f3_i_waTcH3dD_17_6eg1n_aga1n" in partialKnownMessageSage.testKnownMessageFormat()): 23 | print("[*] Partial Known Message(Coppersmith) Check Passed") 24 | else: 25 | print("[X] Partial Known Message(Coppersmith) Check FAILED") 26 | print("[#] Linear Padding Hastads Check") 27 | if(hastadsSage.testLinearPadding()): 28 | print("[*] Linear Padding Hastads Check Passed") 29 | else: 30 | print("[X] Linear Padding Hastads Check FAILED") 31 | 32 | main() 33 | 34 | -------------------------------------------------------------------------------- /RSA/wienerAttack.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from sympy.solvers import solve 3 | from sympy import Symbol 4 | 5 | # This comes from https://github.com/sourcekris/RsaCtfTool/blob/master/wiener_attack.py 6 | # He made it, and I am incorporating it into my Factorizer. 7 | 8 | # A reimplementation of pablocelayes rsa-wiener-attack for this purpose 9 | # https://github.com/pablocelayes/rsa-wiener-attack/ 10 | 11 | class WienerAttack(object): 12 | def rational_to_contfrac (self, x, y): 13 | a = x//y 14 | if a * y == x: 15 | return [a] 16 | else: 17 | pquotients = self.rational_to_contfrac(y, x - a * y) 18 | pquotients.insert(0, a) 19 | return pquotients 20 | 21 | def convergents_from_contfrac(self, frac): 22 | convs = []; 23 | for i in range(len(frac)): 24 | convs.append(self.contfrac_to_rational(frac[0:i])) 25 | return convs 26 | 27 | def contfrac_to_rational (self, frac): 28 | if len(frac) == 0: 29 | return (0,1) 30 | elif len(frac) == 1: 31 | return (frac[0], 1) 32 | else: 33 | remainder = frac[1:len(frac)] 34 | (num, denom) = self.contfrac_to_rational(remainder) 35 | return (frac[0] * num + denom, num) 36 | 37 | def is_perfect_square(self, n): 38 | h = n & 0xF; 39 | if h > 9: 40 | return -1 41 | 42 | if ( h != 2 and h != 3 and h != 5 and h != 6 and h != 7 and h != 8 ): 43 | t = self.isqrt(n) 44 | if t*t == n: 45 | return t 46 | else: 47 | return -1 48 | 49 | return -1 50 | 51 | def isqrt(self, n): 52 | if n == 0: 53 | return 0 54 | a, b = divmod(n.bit_length(), 2) 55 | x = 2**(a+b) 56 | while True: 57 | y = (x + n//x)//2 58 | if y >= x: 59 | return x 60 | x = y 61 | 62 | 63 | def __init__(self, n, e): 64 | self.d = None 65 | self.p = None 66 | self.q = None 67 | sys.setrecursionlimit(100000) 68 | frac = self.rational_to_contfrac(e, n) 69 | convergents = self.convergents_from_contfrac(frac) 70 | 71 | for (k,d) in convergents: 72 | if k!=0 and (e*d-1)%k == 0: 73 | phi = (e*d-1)//k 74 | s = n - phi + 1 75 | discr = s*s - 4*n 76 | if(discr>=0): 77 | t = self.is_perfect_square(discr) 78 | if t!=-1 and (s+t)%2==0: 79 | self.d = d 80 | x = Symbol('x') 81 | roots = solve(x**2 - s*x + n, x) 82 | if len(roots) == 2: 83 | self.p = roots[0] 84 | self.q = roots[1] 85 | break 86 | --------------------------------------------------------------------------------