blob: 0fd67e73dffe02cca7905c7a5eec2cb9894fdd35 [file] [log] [blame]
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="rustdoc"><meta name="description" content="Source of the Rust file `/root/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.20/src/rsa/signing.rs`."><meta name="keywords" content="rust, rustlang, rust-lang"><title>signing.rs - source</title><link rel="preload" as="font" type="font/woff2" crossorigin href="../../../SourceSerif4-Regular.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../../../FiraSans-Regular.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../../../FiraSans-Medium.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../../../SourceCodePro-Regular.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../../../SourceSerif4-Bold.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../../../SourceCodePro-Semibold.ttf.woff2"><link rel="stylesheet" href="../../../normalize.css"><link rel="stylesheet" href="../../../rustdoc.css" id="mainThemeStyle"><link rel="stylesheet" href="../../../ayu.css" disabled><link rel="stylesheet" href="../../../dark.css" disabled><link rel="stylesheet" href="../../../light.css" id="themeStyle"><script id="default-settings" ></script><script src="../../../storage.js"></script><script defer src="../../../source-script.js"></script><script defer src="../../../source-files.js"></script><script defer src="../../../main.js"></script><noscript><link rel="stylesheet" href="../../../noscript.css"></noscript><link rel="alternate icon" type="image/png" href="../../../favicon-16x16.png"><link rel="alternate icon" type="image/png" href="../../../favicon-32x32.png"><link rel="icon" type="image/svg+xml" href="../../../favicon.svg"></head><body class="rustdoc source"><!--[if lte IE 11]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><nav class="sidebar"><a class="sidebar-logo" href="../../../ring/index.html"><div class="logo-container"><img class="rust-logo" src="../../../rust-logo.svg" alt="logo"></div></a></nav><main><div class="width-limiter"><nav class="sub"><a class="sub-logo-container" href="../../../ring/index.html"><img class="rust-logo" src="../../../rust-logo.svg" alt="logo"></a><form class="search-form"><div class="search-container"><span></span><input class="search-input" name="search" autocomplete="off" spellcheck="false" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"><div id="help-button" title="help" tabindex="-1"><a href="../../../help.html">?</a></div><div id="settings-menu" tabindex="-1"><a href="../../../settings.html" title="settings"><img width="22" height="22" alt="Change settings" src="../../../wheel.svg"></a></div></div></form></nav><section id="main-content" class="content"><div class="example-wrap"><pre class="src-line-numbers"><span id="1">1</span>
<span id="2">2</span>
<span id="3">3</span>
<span id="4">4</span>
<span id="5">5</span>
<span id="6">6</span>
<span id="7">7</span>
<span id="8">8</span>
<span id="9">9</span>
<span id="10">10</span>
<span id="11">11</span>
<span id="12">12</span>
<span id="13">13</span>
<span id="14">14</span>
<span id="15">15</span>
<span id="16">16</span>
<span id="17">17</span>
<span id="18">18</span>
<span id="19">19</span>
<span id="20">20</span>
<span id="21">21</span>
<span id="22">22</span>
<span id="23">23</span>
<span id="24">24</span>
<span id="25">25</span>
<span id="26">26</span>
<span id="27">27</span>
<span id="28">28</span>
<span id="29">29</span>
<span id="30">30</span>
<span id="31">31</span>
<span id="32">32</span>
<span id="33">33</span>
<span id="34">34</span>
<span id="35">35</span>
<span id="36">36</span>
<span id="37">37</span>
<span id="38">38</span>
<span id="39">39</span>
<span id="40">40</span>
<span id="41">41</span>
<span id="42">42</span>
<span id="43">43</span>
<span id="44">44</span>
<span id="45">45</span>
<span id="46">46</span>
<span id="47">47</span>
<span id="48">48</span>
<span id="49">49</span>
<span id="50">50</span>
<span id="51">51</span>
<span id="52">52</span>
<span id="53">53</span>
<span id="54">54</span>
<span id="55">55</span>
<span id="56">56</span>
<span id="57">57</span>
<span id="58">58</span>
<span id="59">59</span>
<span id="60">60</span>
<span id="61">61</span>
<span id="62">62</span>
<span id="63">63</span>
<span id="64">64</span>
<span id="65">65</span>
<span id="66">66</span>
<span id="67">67</span>
<span id="68">68</span>
<span id="69">69</span>
<span id="70">70</span>
<span id="71">71</span>
<span id="72">72</span>
<span id="73">73</span>
<span id="74">74</span>
<span id="75">75</span>
<span id="76">76</span>
<span id="77">77</span>
<span id="78">78</span>
<span id="79">79</span>
<span id="80">80</span>
<span id="81">81</span>
<span id="82">82</span>
<span id="83">83</span>
<span id="84">84</span>
<span id="85">85</span>
<span id="86">86</span>
<span id="87">87</span>
<span id="88">88</span>
<span id="89">89</span>
<span id="90">90</span>
<span id="91">91</span>
<span id="92">92</span>
<span id="93">93</span>
<span id="94">94</span>
<span id="95">95</span>
<span id="96">96</span>
<span id="97">97</span>
<span id="98">98</span>
<span id="99">99</span>
<span id="100">100</span>
<span id="101">101</span>
<span id="102">102</span>
<span id="103">103</span>
<span id="104">104</span>
<span id="105">105</span>
<span id="106">106</span>
<span id="107">107</span>
<span id="108">108</span>
<span id="109">109</span>
<span id="110">110</span>
<span id="111">111</span>
<span id="112">112</span>
<span id="113">113</span>
<span id="114">114</span>
<span id="115">115</span>
<span id="116">116</span>
<span id="117">117</span>
<span id="118">118</span>
<span id="119">119</span>
<span id="120">120</span>
<span id="121">121</span>
<span id="122">122</span>
<span id="123">123</span>
<span id="124">124</span>
<span id="125">125</span>
<span id="126">126</span>
<span id="127">127</span>
<span id="128">128</span>
<span id="129">129</span>
<span id="130">130</span>
<span id="131">131</span>
<span id="132">132</span>
<span id="133">133</span>
<span id="134">134</span>
<span id="135">135</span>
<span id="136">136</span>
<span id="137">137</span>
<span id="138">138</span>
<span id="139">139</span>
<span id="140">140</span>
<span id="141">141</span>
<span id="142">142</span>
<span id="143">143</span>
<span id="144">144</span>
<span id="145">145</span>
<span id="146">146</span>
<span id="147">147</span>
<span id="148">148</span>
<span id="149">149</span>
<span id="150">150</span>
<span id="151">151</span>
<span id="152">152</span>
<span id="153">153</span>
<span id="154">154</span>
<span id="155">155</span>
<span id="156">156</span>
<span id="157">157</span>
<span id="158">158</span>
<span id="159">159</span>
<span id="160">160</span>
<span id="161">161</span>
<span id="162">162</span>
<span id="163">163</span>
<span id="164">164</span>
<span id="165">165</span>
<span id="166">166</span>
<span id="167">167</span>
<span id="168">168</span>
<span id="169">169</span>
<span id="170">170</span>
<span id="171">171</span>
<span id="172">172</span>
<span id="173">173</span>
<span id="174">174</span>
<span id="175">175</span>
<span id="176">176</span>
<span id="177">177</span>
<span id="178">178</span>
<span id="179">179</span>
<span id="180">180</span>
<span id="181">181</span>
<span id="182">182</span>
<span id="183">183</span>
<span id="184">184</span>
<span id="185">185</span>
<span id="186">186</span>
<span id="187">187</span>
<span id="188">188</span>
<span id="189">189</span>
<span id="190">190</span>
<span id="191">191</span>
<span id="192">192</span>
<span id="193">193</span>
<span id="194">194</span>
<span id="195">195</span>
<span id="196">196</span>
<span id="197">197</span>
<span id="198">198</span>
<span id="199">199</span>
<span id="200">200</span>
<span id="201">201</span>
<span id="202">202</span>
<span id="203">203</span>
<span id="204">204</span>
<span id="205">205</span>
<span id="206">206</span>
<span id="207">207</span>
<span id="208">208</span>
<span id="209">209</span>
<span id="210">210</span>
<span id="211">211</span>
<span id="212">212</span>
<span id="213">213</span>
<span id="214">214</span>
<span id="215">215</span>
<span id="216">216</span>
<span id="217">217</span>
<span id="218">218</span>
<span id="219">219</span>
<span id="220">220</span>
<span id="221">221</span>
<span id="222">222</span>
<span id="223">223</span>
<span id="224">224</span>
<span id="225">225</span>
<span id="226">226</span>
<span id="227">227</span>
<span id="228">228</span>
<span id="229">229</span>
<span id="230">230</span>
<span id="231">231</span>
<span id="232">232</span>
<span id="233">233</span>
<span id="234">234</span>
<span id="235">235</span>
<span id="236">236</span>
<span id="237">237</span>
<span id="238">238</span>
<span id="239">239</span>
<span id="240">240</span>
<span id="241">241</span>
<span id="242">242</span>
<span id="243">243</span>
<span id="244">244</span>
<span id="245">245</span>
<span id="246">246</span>
<span id="247">247</span>
<span id="248">248</span>
<span id="249">249</span>
<span id="250">250</span>
<span id="251">251</span>
<span id="252">252</span>
<span id="253">253</span>
<span id="254">254</span>
<span id="255">255</span>
<span id="256">256</span>
<span id="257">257</span>
<span id="258">258</span>
<span id="259">259</span>
<span id="260">260</span>
<span id="261">261</span>
<span id="262">262</span>
<span id="263">263</span>
<span id="264">264</span>
<span id="265">265</span>
<span id="266">266</span>
<span id="267">267</span>
<span id="268">268</span>
<span id="269">269</span>
<span id="270">270</span>
<span id="271">271</span>
<span id="272">272</span>
<span id="273">273</span>
<span id="274">274</span>
<span id="275">275</span>
<span id="276">276</span>
<span id="277">277</span>
<span id="278">278</span>
<span id="279">279</span>
<span id="280">280</span>
<span id="281">281</span>
<span id="282">282</span>
<span id="283">283</span>
<span id="284">284</span>
<span id="285">285</span>
<span id="286">286</span>
<span id="287">287</span>
<span id="288">288</span>
<span id="289">289</span>
<span id="290">290</span>
<span id="291">291</span>
<span id="292">292</span>
<span id="293">293</span>
<span id="294">294</span>
<span id="295">295</span>
<span id="296">296</span>
<span id="297">297</span>
<span id="298">298</span>
<span id="299">299</span>
<span id="300">300</span>
<span id="301">301</span>
<span id="302">302</span>
<span id="303">303</span>
<span id="304">304</span>
<span id="305">305</span>
<span id="306">306</span>
<span id="307">307</span>
<span id="308">308</span>
<span id="309">309</span>
<span id="310">310</span>
<span id="311">311</span>
<span id="312">312</span>
<span id="313">313</span>
<span id="314">314</span>
<span id="315">315</span>
<span id="316">316</span>
<span id="317">317</span>
<span id="318">318</span>
<span id="319">319</span>
<span id="320">320</span>
<span id="321">321</span>
<span id="322">322</span>
<span id="323">323</span>
<span id="324">324</span>
<span id="325">325</span>
<span id="326">326</span>
<span id="327">327</span>
<span id="328">328</span>
<span id="329">329</span>
<span id="330">330</span>
<span id="331">331</span>
<span id="332">332</span>
<span id="333">333</span>
<span id="334">334</span>
<span id="335">335</span>
<span id="336">336</span>
<span id="337">337</span>
<span id="338">338</span>
<span id="339">339</span>
<span id="340">340</span>
<span id="341">341</span>
<span id="342">342</span>
<span id="343">343</span>
<span id="344">344</span>
<span id="345">345</span>
<span id="346">346</span>
<span id="347">347</span>
<span id="348">348</span>
<span id="349">349</span>
<span id="350">350</span>
<span id="351">351</span>
<span id="352">352</span>
<span id="353">353</span>
<span id="354">354</span>
<span id="355">355</span>
<span id="356">356</span>
<span id="357">357</span>
<span id="358">358</span>
<span id="359">359</span>
<span id="360">360</span>
<span id="361">361</span>
<span id="362">362</span>
<span id="363">363</span>
<span id="364">364</span>
<span id="365">365</span>
<span id="366">366</span>
<span id="367">367</span>
<span id="368">368</span>
<span id="369">369</span>
<span id="370">370</span>
<span id="371">371</span>
<span id="372">372</span>
<span id="373">373</span>
<span id="374">374</span>
<span id="375">375</span>
<span id="376">376</span>
<span id="377">377</span>
<span id="378">378</span>
<span id="379">379</span>
<span id="380">380</span>
<span id="381">381</span>
<span id="382">382</span>
<span id="383">383</span>
<span id="384">384</span>
<span id="385">385</span>
<span id="386">386</span>
<span id="387">387</span>
<span id="388">388</span>
<span id="389">389</span>
<span id="390">390</span>
<span id="391">391</span>
<span id="392">392</span>
<span id="393">393</span>
<span id="394">394</span>
<span id="395">395</span>
<span id="396">396</span>
<span id="397">397</span>
<span id="398">398</span>
<span id="399">399</span>
<span id="400">400</span>
<span id="401">401</span>
<span id="402">402</span>
<span id="403">403</span>
<span id="404">404</span>
<span id="405">405</span>
<span id="406">406</span>
<span id="407">407</span>
<span id="408">408</span>
<span id="409">409</span>
<span id="410">410</span>
<span id="411">411</span>
<span id="412">412</span>
<span id="413">413</span>
<span id="414">414</span>
<span id="415">415</span>
<span id="416">416</span>
<span id="417">417</span>
<span id="418">418</span>
<span id="419">419</span>
<span id="420">420</span>
<span id="421">421</span>
<span id="422">422</span>
<span id="423">423</span>
<span id="424">424</span>
<span id="425">425</span>
<span id="426">426</span>
<span id="427">427</span>
<span id="428">428</span>
<span id="429">429</span>
<span id="430">430</span>
<span id="431">431</span>
<span id="432">432</span>
<span id="433">433</span>
<span id="434">434</span>
<span id="435">435</span>
<span id="436">436</span>
<span id="437">437</span>
<span id="438">438</span>
<span id="439">439</span>
<span id="440">440</span>
<span id="441">441</span>
<span id="442">442</span>
<span id="443">443</span>
<span id="444">444</span>
<span id="445">445</span>
<span id="446">446</span>
<span id="447">447</span>
<span id="448">448</span>
<span id="449">449</span>
<span id="450">450</span>
<span id="451">451</span>
<span id="452">452</span>
<span id="453">453</span>
<span id="454">454</span>
<span id="455">455</span>
<span id="456">456</span>
<span id="457">457</span>
<span id="458">458</span>
<span id="459">459</span>
<span id="460">460</span>
<span id="461">461</span>
<span id="462">462</span>
<span id="463">463</span>
<span id="464">464</span>
<span id="465">465</span>
<span id="466">466</span>
<span id="467">467</span>
<span id="468">468</span>
<span id="469">469</span>
<span id="470">470</span>
<span id="471">471</span>
<span id="472">472</span>
<span id="473">473</span>
<span id="474">474</span>
<span id="475">475</span>
<span id="476">476</span>
<span id="477">477</span>
<span id="478">478</span>
<span id="479">479</span>
<span id="480">480</span>
<span id="481">481</span>
<span id="482">482</span>
<span id="483">483</span>
<span id="484">484</span>
<span id="485">485</span>
<span id="486">486</span>
<span id="487">487</span>
<span id="488">488</span>
<span id="489">489</span>
<span id="490">490</span>
<span id="491">491</span>
<span id="492">492</span>
<span id="493">493</span>
<span id="494">494</span>
<span id="495">495</span>
<span id="496">496</span>
<span id="497">497</span>
<span id="498">498</span>
<span id="499">499</span>
<span id="500">500</span>
<span id="501">501</span>
<span id="502">502</span>
<span id="503">503</span>
<span id="504">504</span>
<span id="505">505</span>
<span id="506">506</span>
<span id="507">507</span>
<span id="508">508</span>
<span id="509">509</span>
<span id="510">510</span>
<span id="511">511</span>
<span id="512">512</span>
<span id="513">513</span>
<span id="514">514</span>
<span id="515">515</span>
<span id="516">516</span>
<span id="517">517</span>
<span id="518">518</span>
<span id="519">519</span>
<span id="520">520</span>
<span id="521">521</span>
<span id="522">522</span>
<span id="523">523</span>
<span id="524">524</span>
<span id="525">525</span>
<span id="526">526</span>
<span id="527">527</span>
<span id="528">528</span>
<span id="529">529</span>
<span id="530">530</span>
<span id="531">531</span>
<span id="532">532</span>
<span id="533">533</span>
<span id="534">534</span>
<span id="535">535</span>
<span id="536">536</span>
<span id="537">537</span>
<span id="538">538</span>
<span id="539">539</span>
<span id="540">540</span>
<span id="541">541</span>
<span id="542">542</span>
<span id="543">543</span>
<span id="544">544</span>
<span id="545">545</span>
<span id="546">546</span>
<span id="547">547</span>
<span id="548">548</span>
<span id="549">549</span>
<span id="550">550</span>
<span id="551">551</span>
<span id="552">552</span>
<span id="553">553</span>
<span id="554">554</span>
<span id="555">555</span>
<span id="556">556</span>
<span id="557">557</span>
<span id="558">558</span>
<span id="559">559</span>
<span id="560">560</span>
<span id="561">561</span>
<span id="562">562</span>
<span id="563">563</span>
<span id="564">564</span>
<span id="565">565</span>
<span id="566">566</span>
<span id="567">567</span>
<span id="568">568</span>
<span id="569">569</span>
<span id="570">570</span>
<span id="571">571</span>
<span id="572">572</span>
<span id="573">573</span>
<span id="574">574</span>
<span id="575">575</span>
<span id="576">576</span>
<span id="577">577</span>
<span id="578">578</span>
<span id="579">579</span>
<span id="580">580</span>
<span id="581">581</span>
<span id="582">582</span>
<span id="583">583</span>
<span id="584">584</span>
<span id="585">585</span>
<span id="586">586</span>
<span id="587">587</span>
<span id="588">588</span>
<span id="589">589</span>
<span id="590">590</span>
<span id="591">591</span>
<span id="592">592</span>
<span id="593">593</span>
<span id="594">594</span>
<span id="595">595</span>
<span id="596">596</span>
<span id="597">597</span>
<span id="598">598</span>
<span id="599">599</span>
<span id="600">600</span>
<span id="601">601</span>
<span id="602">602</span>
<span id="603">603</span>
<span id="604">604</span>
<span id="605">605</span>
<span id="606">606</span>
<span id="607">607</span>
<span id="608">608</span>
<span id="609">609</span>
<span id="610">610</span>
<span id="611">611</span>
<span id="612">612</span>
<span id="613">613</span>
<span id="614">614</span>
<span id="615">615</span>
<span id="616">616</span>
<span id="617">617</span>
<span id="618">618</span>
<span id="619">619</span>
<span id="620">620</span>
<span id="621">621</span>
<span id="622">622</span>
<span id="623">623</span>
<span id="624">624</span>
<span id="625">625</span>
<span id="626">626</span>
<span id="627">627</span>
<span id="628">628</span>
<span id="629">629</span>
<span id="630">630</span>
<span id="631">631</span>
<span id="632">632</span>
<span id="633">633</span>
<span id="634">634</span>
<span id="635">635</span>
<span id="636">636</span>
<span id="637">637</span>
<span id="638">638</span>
<span id="639">639</span>
<span id="640">640</span>
<span id="641">641</span>
<span id="642">642</span>
<span id="643">643</span>
<span id="644">644</span>
<span id="645">645</span>
</pre><pre class="rust"><code><span class="comment">// Copyright 2015-2016 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED &quot;AS IS&quot; AND THE AUTHORS DISCLAIM ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
</span><span class="kw">use super</span>::{
bigint::{<span class="self">self</span>, Prime},
verification, RsaEncoding, N,
};
<span class="doccomment">/// RSA PKCS#1 1.5 signatures.
</span><span class="kw">use crate</span>::{
arithmetic::montgomery::R,
bits, digest,
error::{<span class="self">self</span>, KeyRejected},
io::{<span class="self">self</span>, der, der_writer},
pkcs8, rand, signature,
};
<span class="kw">use </span>alloc::boxed::Box;
<span class="doccomment">/// An RSA key pair, used for signing.
</span><span class="kw">pub struct </span>RsaKeyPair {
p: PrivatePrime&lt;P&gt;,
q: PrivatePrime&lt;Q&gt;,
qInv: bigint::Elem&lt;P, R&gt;,
qq: bigint::Modulus&lt;QQ&gt;,
q_mod_n: bigint::Elem&lt;N, R&gt;,
public: verification::Key,
public_key: RsaSubjectPublicKey,
}
<span class="macro">derive_debug_via_field!</span>(RsaKeyPair, <span class="macro">stringify!</span>(RsaKeyPair), public_key);
<span class="kw">impl </span>RsaKeyPair {
<span class="doccomment">/// Parses an unencrypted PKCS#8-encoded RSA private key.
///
/// Only two-prime (not multi-prime) keys are supported. The public modulus
/// (n) must be at least 2047 bits. The public modulus must be no larger
/// than 4096 bits. It is recommended that the public modulus be exactly
/// 2048 or 3072 bits. The public exponent must be at least 65537.
///
/// This will generate a 2048-bit RSA private key of the correct form using
/// OpenSSL&#39;s command line tool:
///
/// ```sh
/// openssl genpkey -algorithm RSA \
/// -pkeyopt rsa_keygen_bits:2048 \
/// -pkeyopt rsa_keygen_pubexp:65537 | \
/// openssl pkcs8 -topk8 -nocrypt -outform der &gt; rsa-2048-private-key.pk8
/// ```
///
/// This will generate a 3072-bit RSA private key of the correct form:
///
/// ```sh
/// openssl genpkey -algorithm RSA \
/// -pkeyopt rsa_keygen_bits:3072 \
/// -pkeyopt rsa_keygen_pubexp:65537 | \
/// openssl pkcs8 -topk8 -nocrypt -outform der &gt; rsa-3072-private-key.pk8
/// ```
///
/// Often, keys generated for use in OpenSSL-based software are stored in
/// the Base64 “PEM” format without the PKCS#8 wrapper. Such keys can be
/// converted to binary PKCS#8 form using the OpenSSL command line tool like
/// this:
///
/// ```sh
/// openssl pkcs8 -topk8 -nocrypt -outform der \
/// -in rsa-2048-private-key.pem &gt; rsa-2048-private-key.pk8
/// ```
///
/// Base64 (“PEM”) PKCS#8-encoded keys can be converted to the binary PKCS#8
/// form like this:
///
/// ```sh
/// openssl pkcs8 -nocrypt -outform der \
/// -in rsa-2048-private-key.pem &gt; rsa-2048-private-key.pk8
/// ```
///
/// The private key is validated according to [NIST SP-800-56B rev. 1]
/// section 6.4.1.4.3, crt_pkv (Intended Exponent-Creation Method Unknown),
/// with the following exceptions:
///
/// * Section 6.4.1.2.1, Step 1: Neither a target security level nor an
/// expected modulus length is provided as a parameter, so checks
/// regarding these expectations are not done.
/// * Section 6.4.1.2.1, Step 3: Since neither the public key nor the
/// expected modulus length is provided as a parameter, the consistency
/// check between these values and the private key&#39;s value of n isn&#39;t
/// done.
/// * Section 6.4.1.2.1, Step 5: No primality tests are done, both for
/// performance reasons and to avoid any side channels that such tests
/// would provide.
/// * Section 6.4.1.2.1, Step 6, and 6.4.1.4.3, Step 7:
/// * *ring* has a slightly looser lower bound for the values of `p`
/// and `q` than what the NIST document specifies. This looser lower
/// bound matches what most other crypto libraries do. The check might
/// be tightened to meet NIST&#39;s requirements in the future. Similarly,
/// the check that `p` and `q` are not too close together is skipped
/// currently, but may be added in the future.
/// - The validity of the mathematical relationship of `dP`, `dQ`, `e`
/// and `n` is verified only during signing. Some size checks of `d`,
/// `dP` and `dQ` are performed at construction, but some NIST checks
/// are skipped because they would be expensive and/or they would leak
/// information through side channels. If a preemptive check of the
/// consistency of `dP`, `dQ`, `e` and `n` with each other is
/// necessary, that can be done by signing any message with the key
/// pair.
///
/// * `d` is not fully validated, neither at construction nor during
/// signing. This is OK as far as *ring*&#39;s usage of the key is
/// concerned because *ring* never uses the value of `d` (*ring* always
/// uses `p`, `q`, `dP` and `dQ` via the Chinese Remainder Theorem,
/// instead). However, *ring*&#39;s checks would not be sufficient for
/// validating a key pair for use by some other system; that other
/// system must check the value of `d` itself if `d` is to be used.
///
/// In addition to the NIST requirements, *ring* requires that `p &gt; q` and
/// that `e` must be no more than 33 bits.
///
/// See [RFC 5958] and [RFC 3447 Appendix A.1.2] for more details of the
/// encoding of the key.
///
/// [NIST SP-800-56B rev. 1]:
/// http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br1.pdf
///
/// [RFC 3447 Appendix A.1.2]:
/// https://tools.ietf.org/html/rfc3447#appendix-A.1.2
///
/// [RFC 5958]:
/// https://tools.ietf.org/html/rfc5958
</span><span class="kw">pub fn </span>from_pkcs8(pkcs8: <span class="kw-2">&amp;</span>[u8]) -&gt; <span class="prelude-ty">Result</span>&lt;<span class="self">Self</span>, KeyRejected&gt; {
<span class="kw">const </span>RSA_ENCRYPTION: <span class="kw-2">&amp;</span>[u8] = <span class="macro">include_bytes!</span>(<span class="string">&quot;../data/alg-rsa-encryption.der&quot;</span>);
<span class="kw">let </span>(der, <span class="kw">_</span>) = pkcs8::unwrap_key_(
untrusted::Input::from(<span class="kw-2">&amp;</span>RSA_ENCRYPTION),
pkcs8::Version::V1Only,
untrusted::Input::from(pkcs8),
)<span class="question-mark">?</span>;
<span class="self">Self</span>::from_der(der.as_slice_less_safe())
}
<span class="doccomment">/// Parses an RSA private key that is not inside a PKCS#8 wrapper.
///
/// The private key must be encoded as a binary DER-encoded ASN.1
/// `RSAPrivateKey` as described in [RFC 3447 Appendix A.1.2]). In all other
/// respects, this is just like `from_pkcs8()`. See the documentation for
/// `from_pkcs8()` for more details.
///
/// It is recommended to use `from_pkcs8()` (with a PKCS#8-encoded key)
/// instead.
///
/// [RFC 3447 Appendix A.1.2]:
/// https://tools.ietf.org/html/rfc3447#appendix-A.1.2
///
/// [NIST SP-800-56B rev. 1]:
/// http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br1.pdf
</span><span class="kw">pub fn </span>from_der(input: <span class="kw-2">&amp;</span>[u8]) -&gt; <span class="prelude-ty">Result</span>&lt;<span class="self">Self</span>, KeyRejected&gt; {
untrusted::Input::from(input).read_all(KeyRejected::invalid_encoding(), |input| {
der::nested(
input,
der::Tag::Sequence,
error::KeyRejected::invalid_encoding(),
<span class="self">Self</span>::from_der_reader,
)
})
}
<span class="kw">fn </span>from_der_reader(input: <span class="kw-2">&amp;mut </span>untrusted::Reader) -&gt; <span class="prelude-ty">Result</span>&lt;<span class="self">Self</span>, KeyRejected&gt; {
<span class="kw">let </span>version = der::small_nonnegative_integer(input)
.map_err(|error::Unspecified| KeyRejected::invalid_encoding())<span class="question-mark">?</span>;
<span class="kw">if </span>version != <span class="number">0 </span>{
<span class="kw">return </span><span class="prelude-val">Err</span>(KeyRejected::version_not_supported());
}
<span class="kw">fn </span>positive_integer&lt;<span class="lifetime">&#39;a</span>&gt;(
input: <span class="kw-2">&amp;mut </span>untrusted::Reader&lt;<span class="lifetime">&#39;a</span>&gt;,
) -&gt; <span class="prelude-ty">Result</span>&lt;io::Positive&lt;<span class="lifetime">&#39;a</span>&gt;, KeyRejected&gt; {
der::positive_integer(input)
.map_err(|error::Unspecified| KeyRejected::invalid_encoding())
}
<span class="kw">let </span>n = positive_integer(input)<span class="question-mark">?</span>;
<span class="kw">let </span>e = positive_integer(input)<span class="question-mark">?</span>;
<span class="kw">let </span>d = positive_integer(input)<span class="question-mark">?</span>.big_endian_without_leading_zero_as_input();
<span class="kw">let </span>p = positive_integer(input)<span class="question-mark">?</span>.big_endian_without_leading_zero_as_input();
<span class="kw">let </span>q = positive_integer(input)<span class="question-mark">?</span>.big_endian_without_leading_zero_as_input();
<span class="kw">let </span>dP = positive_integer(input)<span class="question-mark">?</span>.big_endian_without_leading_zero_as_input();
<span class="kw">let </span>dQ = positive_integer(input)<span class="question-mark">?</span>.big_endian_without_leading_zero_as_input();
<span class="kw">let </span>qInv = positive_integer(input)<span class="question-mark">?</span>.big_endian_without_leading_zero_as_input();
<span class="kw">let </span>(p, p_bits) = bigint::Nonnegative::from_be_bytes_with_bit_length(p)
.map_err(|error::Unspecified| KeyRejected::invalid_encoding())<span class="question-mark">?</span>;
<span class="kw">let </span>(q, q_bits) = bigint::Nonnegative::from_be_bytes_with_bit_length(q)
.map_err(|error::Unspecified| KeyRejected::invalid_encoding())<span class="question-mark">?</span>;
<span class="comment">// Our implementation of CRT-based modular exponentiation used requires
// that `p &gt; q` so swap them if `p &lt; q`. If swapped, `qInv` is
// recalculated below. `p != q` is verified implicitly below, e.g. when
// `q_mod_p` is constructed.
</span><span class="kw">let </span>((p, p_bits, dP), (q, q_bits, dQ, qInv)) = <span class="kw">match </span>q.verify_less_than(<span class="kw-2">&amp;</span>p) {
<span class="prelude-val">Ok</span>(<span class="kw">_</span>) =&gt; ((p, p_bits, dP), (q, q_bits, dQ, <span class="prelude-val">Some</span>(qInv))),
<span class="prelude-val">Err</span>(error::Unspecified) =&gt; {
<span class="comment">// TODO: verify `q` and `qInv` are inverses (mod p).
</span>((q, q_bits, dQ), (p, p_bits, dP, <span class="prelude-val">None</span>))
}
};
<span class="comment">// XXX: Some steps are done out of order, but the NIST steps are worded
// in such a way that it is clear that NIST intends for them to be done
// in order. TODO: Does this matter at all?
// 6.4.1.4.3/6.4.1.2.1 - Step 1.
// Step 1.a is omitted, as explained above.
// Step 1.b is omitted per above. Instead, we check that the public
// modulus is 2048 to `PRIVATE_KEY_PUBLIC_MODULUS_MAX_BITS` bits.
// XXX: The maximum limit of 4096 bits is primarily due to lack of
// testing of larger key sizes; see, in particular,
// https://www.mail-archive.com/openssl-dev@openssl.org/msg44586.html
// and
// https://www.mail-archive.com/openssl-dev@openssl.org/msg44759.html.
// Also, this limit might help with memory management decisions later.
// Step 1.c. We validate e &gt;= 65537.
</span><span class="kw">let </span>public_key = verification::Key::from_modulus_and_exponent(
n.big_endian_without_leading_zero_as_input(),
e.big_endian_without_leading_zero_as_input(),
bits::BitLength::from_usize_bits(<span class="number">2048</span>),
<span class="kw">super</span>::PRIVATE_KEY_PUBLIC_MODULUS_MAX_BITS,
<span class="number">65537</span>,
)<span class="question-mark">?</span>;
<span class="comment">// 6.4.1.4.3 says to skip 6.4.1.2.1 Step 2.
// 6.4.1.4.3 Step 3.
// Step 3.a is done below, out of order.
// Step 3.b is unneeded since `n_bits` is derived here from `n`.
// 6.4.1.4.3 says to skip 6.4.1.2.1 Step 4. (We don&#39;t need to recover
// the prime factors since they are already given.)
// 6.4.1.4.3 - Step 5.
// Steps 5.a and 5.b are omitted, as explained above.
// Step 5.c.
//
// TODO: First, stop if `p &lt; (√2) * 2**((nBits/2) - 1)`.
//
// Second, stop if `p &gt; 2**(nBits/2) - 1`.
</span><span class="kw">let </span>half_n_bits = public_key.n_bits.half_rounded_up();
<span class="kw">if </span>p_bits != half_n_bits {
<span class="kw">return </span><span class="prelude-val">Err</span>(KeyRejected::inconsistent_components());
}
<span class="comment">// TODO: Step 5.d: Verify GCD(p - 1, e) == 1.
// Steps 5.e and 5.f are omitted as explained above.
// Step 5.g.
//
// TODO: First, stop if `q &lt; (√2) * 2**((nBits/2) - 1)`.
//
// Second, stop if `q &gt; 2**(nBits/2) - 1`.
</span><span class="kw">if </span>p_bits != q_bits {
<span class="kw">return </span><span class="prelude-val">Err</span>(KeyRejected::inconsistent_components());
}
<span class="comment">// TODO: Step 5.h: Verify GCD(p - 1, e) == 1.
</span><span class="kw">let </span>q_mod_n_decoded = q
.to_elem(<span class="kw-2">&amp;</span>public_key.n)
.map_err(|error::Unspecified| KeyRejected::inconsistent_components())<span class="question-mark">?</span>;
<span class="comment">// TODO: Step 5.i
//
// 3.b is unneeded since `n_bits` is derived here from `n`.
// 6.4.1.4.3 - Step 3.a (out of order).
//
// Verify that p * q == n. We restrict ourselves to modular
// multiplication. We rely on the fact that we&#39;ve verified
// 0 &lt; q &lt; p &lt; n. We check that q and p are close to sqrt(n) and then
// assume that these preconditions are enough to let us assume that
// checking p * q == 0 (mod n) is equivalent to checking p * q == n.
</span><span class="kw">let </span>q_mod_n = bigint::elem_mul(
public_key.n.oneRR().as_ref(),
q_mod_n_decoded.clone(),
<span class="kw-2">&amp;</span>public_key.n,
);
<span class="kw">let </span>p_mod_n = p
.to_elem(<span class="kw-2">&amp;</span>public_key.n)
.map_err(|error::Unspecified| KeyRejected::inconsistent_components())<span class="question-mark">?</span>;
<span class="kw">let </span>pq_mod_n = bigint::elem_mul(<span class="kw-2">&amp;</span>q_mod_n, p_mod_n, <span class="kw-2">&amp;</span>public_key.n);
<span class="kw">if </span>!pq_mod_n.is_zero() {
<span class="kw">return </span><span class="prelude-val">Err</span>(KeyRejected::inconsistent_components());
}
<span class="comment">// 6.4.1.4.3/6.4.1.2.1 - Step 6.
// Step 6.a, partial.
//
// First, validate `2**half_n_bits &lt; d`. Since 2**half_n_bits has a bit
// length of half_n_bits + 1, this check gives us 2**half_n_bits &lt;= d,
// and knowing d is odd makes the inequality strict.
</span><span class="kw">let </span>(d, d_bits) = bigint::Nonnegative::from_be_bytes_with_bit_length(d)
.map_err(|<span class="kw">_</span>| error::KeyRejected::invalid_encoding())<span class="question-mark">?</span>;
<span class="kw">if </span>!(half_n_bits &lt; d_bits) {
<span class="kw">return </span><span class="prelude-val">Err</span>(KeyRejected::inconsistent_components());
}
<span class="comment">// XXX: This check should be `d &lt; LCM(p - 1, q - 1)`, but we don&#39;t have
// a good way of calculating LCM, so it is omitted, as explained above.
</span>d.verify_less_than_modulus(<span class="kw-2">&amp;</span>public_key.n)
.map_err(|error::Unspecified| KeyRejected::inconsistent_components())<span class="question-mark">?</span>;
<span class="kw">if </span>!d.is_odd() {
<span class="kw">return </span><span class="prelude-val">Err</span>(KeyRejected::invalid_component());
}
<span class="comment">// Step 6.b is omitted as explained above.
// 6.4.1.4.3 - Step 7.
// Step 7.a.
</span><span class="kw">let </span>p = PrivatePrime::new(p, dP)<span class="question-mark">?</span>;
<span class="comment">// Step 7.b.
</span><span class="kw">let </span>q = PrivatePrime::new(q, dQ)<span class="question-mark">?</span>;
<span class="kw">let </span>q_mod_p = q.modulus.to_elem(<span class="kw-2">&amp;</span>p.modulus);
<span class="comment">// Step 7.c.
</span><span class="kw">let </span>qInv = <span class="kw">if let </span><span class="prelude-val">Some</span>(qInv) = qInv {
bigint::Elem::from_be_bytes_padded(qInv, <span class="kw-2">&amp;</span>p.modulus)
.map_err(|error::Unspecified| KeyRejected::invalid_component())<span class="question-mark">?
</span>} <span class="kw">else </span>{
<span class="comment">// We swapped `p` and `q` above, so we need to calculate `qInv`.
// Step 7.f below will verify `qInv` is correct.
</span><span class="kw">let </span>q_mod_p = bigint::elem_mul(p.modulus.oneRR().as_ref(), q_mod_p.clone(), <span class="kw-2">&amp;</span>p.modulus);
bigint::elem_inverse_consttime(q_mod_p, <span class="kw-2">&amp;</span>p.modulus)
.map_err(|error::Unspecified| KeyRejected::unexpected_error())<span class="question-mark">?
</span>};
<span class="comment">// Steps 7.d and 7.e are omitted per the documentation above, and
// because we don&#39;t (in the long term) have a good way to do modulo
// with an even modulus.
// Step 7.f.
</span><span class="kw">let </span>qInv = bigint::elem_mul(p.modulus.oneRR().as_ref(), qInv, <span class="kw-2">&amp;</span>p.modulus);
bigint::verify_inverses_consttime(<span class="kw-2">&amp;</span>qInv, q_mod_p, <span class="kw-2">&amp;</span>p.modulus)
.map_err(|error::Unspecified| KeyRejected::inconsistent_components())<span class="question-mark">?</span>;
<span class="kw">let </span>qq = bigint::elem_mul(<span class="kw-2">&amp;</span>q_mod_n, q_mod_n_decoded, <span class="kw-2">&amp;</span>public_key.n).into_modulus::&lt;QQ&gt;()<span class="question-mark">?</span>;
<span class="kw">let </span>public_key_serialized = RsaSubjectPublicKey::from_n_and_e(n, e);
<span class="prelude-val">Ok</span>(<span class="self">Self </span>{
p,
q,
qInv,
q_mod_n,
qq,
public: public_key,
public_key: public_key_serialized,
})
}
<span class="doccomment">/// Returns the length in bytes of the key pair&#39;s public modulus.
///
/// A signature has the same length as the public modulus.
</span><span class="kw">pub fn </span>public_modulus_len(<span class="kw-2">&amp;</span><span class="self">self</span>) -&gt; usize {
<span class="self">self</span>.public_key
.modulus()
.big_endian_without_leading_zero_as_input()
.as_slice_less_safe()
.len()
}
}
<span class="kw">impl </span>signature::KeyPair <span class="kw">for </span>RsaKeyPair {
<span class="kw">type </span>PublicKey = RsaSubjectPublicKey;
<span class="kw">fn </span>public_key(<span class="kw-2">&amp;</span><span class="self">self</span>) -&gt; <span class="kw-2">&amp;</span><span class="self">Self</span>::PublicKey {
<span class="kw-2">&amp;</span><span class="self">self</span>.public_key
}
}
<span class="doccomment">/// A serialized RSA public key.
</span><span class="attribute">#[derive(Clone)]
</span><span class="kw">pub struct </span>RsaSubjectPublicKey(Box&lt;[u8]&gt;);
<span class="kw">impl </span>AsRef&lt;[u8]&gt; <span class="kw">for </span>RsaSubjectPublicKey {
<span class="kw">fn </span>as_ref(<span class="kw-2">&amp;</span><span class="self">self</span>) -&gt; <span class="kw-2">&amp;</span>[u8] {
<span class="self">self</span>.<span class="number">0</span>.as_ref()
}
}
<span class="macro">derive_debug_self_as_ref_hex_bytes!</span>(RsaSubjectPublicKey);
<span class="kw">impl </span>RsaSubjectPublicKey {
<span class="kw">fn </span>from_n_and_e(n: io::Positive, e: io::Positive) -&gt; <span class="self">Self </span>{
<span class="kw">let </span>bytes = der_writer::write_all(der::Tag::Sequence, <span class="kw-2">&amp;</span>|output| {
der_writer::write_positive_integer(output, <span class="kw-2">&amp;</span>n);
der_writer::write_positive_integer(output, <span class="kw-2">&amp;</span>e);
});
RsaSubjectPublicKey(bytes)
}
<span class="doccomment">/// The public modulus (n).
</span><span class="kw">pub fn </span>modulus(<span class="kw-2">&amp;</span><span class="self">self</span>) -&gt; io::Positive {
<span class="comment">// Parsing won&#39;t fail because we serialized it ourselves.
</span><span class="kw">let </span>(public_key, _exponent) =
<span class="kw">super</span>::parse_public_key(untrusted::Input::from(<span class="self">self</span>.as_ref())).unwrap();
public_key
}
<span class="doccomment">/// The public exponent (e).
</span><span class="kw">pub fn </span>exponent(<span class="kw-2">&amp;</span><span class="self">self</span>) -&gt; io::Positive {
<span class="comment">// Parsing won&#39;t fail because we serialized it ourselves.
</span><span class="kw">let </span>(_public_key, exponent) =
<span class="kw">super</span>::parse_public_key(untrusted::Input::from(<span class="self">self</span>.as_ref())).unwrap();
exponent
}
}
<span class="kw">struct </span>PrivatePrime&lt;M: Prime&gt; {
modulus: bigint::Modulus&lt;M&gt;,
exponent: bigint::PrivateExponent&lt;M&gt;,
}
<span class="kw">impl</span>&lt;M: Prime + Clone&gt; PrivatePrime&lt;M&gt; {
<span class="doccomment">/// Constructs a `PrivatePrime` from the private prime `p` and `dP` where
/// dP == d % (p - 1).
</span><span class="kw">fn </span>new(p: bigint::Nonnegative, dP: untrusted::Input) -&gt; <span class="prelude-ty">Result</span>&lt;<span class="self">Self</span>, KeyRejected&gt; {
<span class="kw">let </span>(p, p_bits) = bigint::Modulus::from_nonnegative_with_bit_length(p)<span class="question-mark">?</span>;
<span class="kw">if </span>p_bits.as_usize_bits() % <span class="number">512 </span>!= <span class="number">0 </span>{
<span class="kw">return </span><span class="prelude-val">Err</span>(error::KeyRejected::private_modulus_len_not_multiple_of_512_bits());
}
<span class="comment">// [NIST SP-800-56B rev. 1] 6.4.1.4.3 - Steps 7.a &amp; 7.b.
</span><span class="kw">let </span>dP = bigint::PrivateExponent::from_be_bytes_padded(dP, <span class="kw-2">&amp;</span>p)
.map_err(|error::Unspecified| KeyRejected::inconsistent_components())<span class="question-mark">?</span>;
<span class="comment">// XXX: Steps 7.d and 7.e are omitted. We don&#39;t check that
// `dP == d % (p - 1)` because we don&#39;t (in the long term) have a good
// way to do modulo with an even modulus. Instead we just check that
// `1 &lt;= dP &lt; p - 1`. We&#39;ll check it, to some unknown extent, when we
// do the private key operation, since we verify that the result of the
// private key operation using the CRT parameters is consistent with `n`
// and `e`. TODO: Either prove that what we do is sufficient, or make
// it so.
</span><span class="prelude-val">Ok</span>(PrivatePrime {
modulus: p,
exponent: dP,
})
}
}
<span class="kw">fn </span>elem_exp_consttime&lt;M, MM&gt;(
c: <span class="kw-2">&amp;</span>bigint::Elem&lt;MM&gt;,
p: <span class="kw-2">&amp;</span>PrivatePrime&lt;M&gt;,
) -&gt; <span class="prelude-ty">Result</span>&lt;bigint::Elem&lt;M&gt;, error::Unspecified&gt;
<span class="kw">where
</span>M: bigint::NotMuchSmallerModulus&lt;MM&gt;,
M: Prime,
{
<span class="kw">let </span>c_mod_m = bigint::elem_reduced(c, <span class="kw-2">&amp;</span>p.modulus);
<span class="comment">// We could precompute `oneRRR = elem_squared(&amp;p.oneRR`) as mentioned
// in the Smooth CRT-RSA paper.
</span><span class="kw">let </span>c_mod_m = bigint::elem_mul(p.modulus.oneRR().as_ref(), c_mod_m, <span class="kw-2">&amp;</span>p.modulus);
<span class="kw">let </span>c_mod_m = bigint::elem_mul(p.modulus.oneRR().as_ref(), c_mod_m, <span class="kw-2">&amp;</span>p.modulus);
bigint::elem_exp_consttime(c_mod_m, <span class="kw-2">&amp;</span>p.exponent, <span class="kw-2">&amp;</span>p.modulus)
}
<span class="comment">// Type-level representations of the different moduli used in RSA signing, in
// addition to `super::N`. See `super::bigint`&#39;s modulue-level documentation.
</span><span class="attribute">#[derive(Copy, Clone)]
</span><span class="kw">enum </span>P {}
<span class="kw">unsafe impl </span>Prime <span class="kw">for </span>P {}
<span class="kw">unsafe impl </span>bigint::SmallerModulus&lt;N&gt; <span class="kw">for </span>P {}
<span class="kw">unsafe impl </span>bigint::NotMuchSmallerModulus&lt;N&gt; <span class="kw">for </span>P {}
<span class="attribute">#[derive(Copy, Clone)]
</span><span class="kw">enum </span>QQ {}
<span class="kw">unsafe impl </span>bigint::SmallerModulus&lt;N&gt; <span class="kw">for </span>QQ {}
<span class="kw">unsafe impl </span>bigint::NotMuchSmallerModulus&lt;N&gt; <span class="kw">for </span>QQ {}
<span class="comment">// `q &lt; p &lt; 2*q` since `q` is slightly smaller than `p` (see below). Thus:
//
// q &lt; p &lt; 2*q
// q*q &lt; p*q &lt; 2*q*q.
// q**2 &lt; n &lt; 2*(q**2).
</span><span class="kw">unsafe impl </span>bigint::SlightlySmallerModulus&lt;N&gt; <span class="kw">for </span>QQ {}
<span class="attribute">#[derive(Copy, Clone)]
</span><span class="kw">enum </span>Q {}
<span class="kw">unsafe impl </span>Prime <span class="kw">for </span>Q {}
<span class="kw">unsafe impl </span>bigint::SmallerModulus&lt;N&gt; <span class="kw">for </span>Q {}
<span class="kw">unsafe impl </span>bigint::SmallerModulus&lt;P&gt; <span class="kw">for </span>Q {}
<span class="comment">// q &lt; p &amp;&amp; `p.bit_length() == q.bit_length()` implies `q &lt; p &lt; 2*q`.
</span><span class="kw">unsafe impl </span>bigint::SlightlySmallerModulus&lt;P&gt; <span class="kw">for </span>Q {}
<span class="kw">unsafe impl </span>bigint::SmallerModulus&lt;QQ&gt; <span class="kw">for </span>Q {}
<span class="kw">unsafe impl </span>bigint::NotMuchSmallerModulus&lt;QQ&gt; <span class="kw">for </span>Q {}
<span class="kw">impl </span>RsaKeyPair {
<span class="doccomment">/// Sign `msg`. `msg` is digested using the digest algorithm from
/// `padding_alg` and the digest is then padded using the padding algorithm
/// from `padding_alg`. The signature it written into `signature`;
/// `signature`&#39;s length must be exactly the length returned by
/// `public_modulus_len()`. `rng` may be used to randomize the padding
/// (e.g. for PSS).
///
/// Many other crypto libraries have signing functions that takes a
/// precomputed digest as input, instead of the message to digest. This
/// function does *not* take a precomputed digest; instead, `sign`
/// calculates the digest itself.
///
/// Lots of effort has been made to make the signing operations close to
/// constant time to protect the private key from side channel attacks. On
/// x86-64, this is done pretty well, but not perfectly. On other
/// platforms, it is done less perfectly.
</span><span class="kw">pub fn </span>sign(
<span class="kw-2">&amp;</span><span class="self">self</span>,
padding_alg: <span class="kw-2">&amp;</span><span class="lifetime">&#39;static </span><span class="kw">dyn </span>RsaEncoding,
rng: <span class="kw-2">&amp;</span><span class="kw">dyn </span>rand::SecureRandom,
msg: <span class="kw-2">&amp;</span>[u8],
signature: <span class="kw-2">&amp;mut </span>[u8],
) -&gt; <span class="prelude-ty">Result</span>&lt;(), error::Unspecified&gt; {
<span class="kw">let </span>mod_bits = <span class="self">self</span>.public.n_bits;
<span class="kw">if </span>signature.len() != mod_bits.as_usize_bytes_rounded_up() {
<span class="kw">return </span><span class="prelude-val">Err</span>(error::Unspecified);
}
<span class="kw">let </span>m_hash = digest::digest(padding_alg.digest_alg(), msg);
padding_alg.encode(<span class="kw-2">&amp;</span>m_hash, signature, mod_bits, rng)<span class="question-mark">?</span>;
<span class="comment">// RFC 8017 Section 5.1.2: RSADP, using the Chinese Remainder Theorem
// with Garner&#39;s algorithm.
</span><span class="kw">let </span>n = <span class="kw-2">&amp;</span><span class="self">self</span>.public.n;
<span class="comment">// Step 1. The value zero is also rejected.
</span><span class="kw">let </span>base = bigint::Elem::from_be_bytes_padded(untrusted::Input::from(signature), n)<span class="question-mark">?</span>;
<span class="comment">// Step 2
</span><span class="kw">let </span>c = base;
<span class="comment">// Step 2.b.i.
</span><span class="kw">let </span>m_1 = elem_exp_consttime(<span class="kw-2">&amp;</span>c, <span class="kw-2">&amp;</span><span class="self">self</span>.p)<span class="question-mark">?</span>;
<span class="kw">let </span>c_mod_qq = bigint::elem_reduced_once(<span class="kw-2">&amp;</span>c, <span class="kw-2">&amp;</span><span class="self">self</span>.qq);
<span class="kw">let </span>m_2 = elem_exp_consttime(<span class="kw-2">&amp;</span>c_mod_qq, <span class="kw-2">&amp;</span><span class="self">self</span>.q)<span class="question-mark">?</span>;
<span class="comment">// Step 2.b.ii isn&#39;t needed since there are only two primes.
// Step 2.b.iii.
</span><span class="kw">let </span>p = <span class="kw-2">&amp;</span><span class="self">self</span>.p.modulus;
<span class="kw">let </span>m_2 = bigint::elem_widen(m_2, p);
<span class="kw">let </span>m_1_minus_m_2 = bigint::elem_sub(m_1, <span class="kw-2">&amp;</span>m_2, p);
<span class="kw">let </span>h = bigint::elem_mul(<span class="kw-2">&amp;</span><span class="self">self</span>.qInv, m_1_minus_m_2, p);
<span class="comment">// Step 2.b.iv. The reduction in the modular multiplication isn&#39;t
// necessary because `h &lt; p` and `p * q == n` implies `h * q &lt; n`.
// Modular arithmetic is used simply to avoid implementing
// non-modular arithmetic.
</span><span class="kw">let </span>h = bigint::elem_widen(h, n);
<span class="kw">let </span>q_times_h = bigint::elem_mul(<span class="kw-2">&amp;</span><span class="self">self</span>.q_mod_n, h, n);
<span class="kw">let </span>m_2 = bigint::elem_widen(m_2, n);
<span class="kw">let </span>m = bigint::elem_add(m_2, q_times_h, n);
<span class="comment">// Step 2.b.v isn&#39;t needed since there are only two primes.
// Verify the result to protect against fault attacks as described
// in &quot;On the Importance of Checking Cryptographic Protocols for
// Faults&quot; by Dan Boneh, Richard A. DeMillo, and Richard J. Lipton.
// This check is cheap assuming `e` is small, which is ensured during
// `KeyPair` construction. Note that this is the only validation of `e`
// that is done other than basic checks on its size, oddness, and
// minimum value, since the relationship of `e` to `d`, `p`, and `q` is
// not verified during `KeyPair` construction.
</span>{
<span class="kw">let </span>verify = bigint::elem_exp_vartime(m.clone(), <span class="self">self</span>.public.e, n);
<span class="kw">let </span>verify = verify.into_unencoded(n);
bigint::elem_verify_equal_consttime(<span class="kw-2">&amp;</span>verify, <span class="kw-2">&amp;</span>c)<span class="question-mark">?</span>;
}
<span class="comment">// Step 3.
//
// See Falko Strenzke, &quot;Manger&#39;s Attack revisited&quot;, ICICS 2010.
</span>m.fill_be_bytes(signature);
<span class="prelude-val">Ok</span>(())
}
}
<span class="attribute">#[cfg(test)]
</span><span class="kw">mod </span>tests {
<span class="comment">// We intentionally avoid `use super::*` so that we are sure to use only
// the public API; this ensures that enough of the API is public.
</span><span class="kw">use crate</span>::{rand, signature};
<span class="kw">use </span>alloc::vec;
<span class="comment">// `KeyPair::sign` requires that the output buffer is the same length as
// the public key modulus. Test what happens when it isn&#39;t the same length.
</span><span class="attribute">#[test]
</span><span class="kw">fn </span>test_signature_rsa_pkcs1_sign_output_buffer_len() {
<span class="comment">// Sign the message &quot;hello, world&quot;, using PKCS#1 v1.5 padding and the
// SHA256 digest algorithm.
</span><span class="kw">const </span>MESSAGE: <span class="kw-2">&amp;</span>[u8] = <span class="string">b&quot;hello, world&quot;</span>;
<span class="kw">let </span>rng = rand::SystemRandom::new();
<span class="kw">const </span>PRIVATE_KEY_DER: <span class="kw-2">&amp;</span>[u8] = <span class="macro">include_bytes!</span>(<span class="string">&quot;signature_rsa_example_private_key.der&quot;</span>);
<span class="kw">let </span>key_pair = signature::RsaKeyPair::from_der(PRIVATE_KEY_DER).unwrap();
<span class="comment">// The output buffer is one byte too short.
</span><span class="kw">let </span><span class="kw-2">mut </span>signature = <span class="macro">vec!</span>[<span class="number">0</span>; key_pair.public_modulus_len() - <span class="number">1</span>];
<span class="macro">assert!</span>(key_pair
.sign(<span class="kw-2">&amp;</span>signature::RSA_PKCS1_SHA256, <span class="kw-2">&amp;</span>rng, MESSAGE, <span class="kw-2">&amp;mut </span>signature)
.is_err());
<span class="comment">// The output buffer is the right length.
</span>signature.push(<span class="number">0</span>);
<span class="macro">assert!</span>(key_pair
.sign(<span class="kw-2">&amp;</span>signature::RSA_PKCS1_SHA256, <span class="kw-2">&amp;</span>rng, MESSAGE, <span class="kw-2">&amp;mut </span>signature)
.is_ok());
<span class="comment">// The output buffer is one byte too long.
</span>signature.push(<span class="number">0</span>);
<span class="macro">assert!</span>(key_pair
.sign(<span class="kw-2">&amp;</span>signature::RSA_PKCS1_SHA256, <span class="kw-2">&amp;</span>rng, MESSAGE, <span class="kw-2">&amp;mut </span>signature)
.is_err());
}
}
</code></pre></div>
</section></div></main><div id="rustdoc-vars" data-root-path="../../../" data-current-crate="ring" data-themes="ayu,dark,light" data-resource-suffix="" data-rustdoc-version="1.66.0-nightly (5c8bff74b 2022-10-21)" ></div></body></html>