<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vaibhav Meshram on Medium]]></title>
        <description><![CDATA[Stories by Vaibhav Meshram on Medium]]></description>
        <link>https://medium.com/@vaibhav.pmeshram?source=rss-dc09494ad3b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*WKDXUORoxYig1WQ_QKshVw.jpeg</url>
            <title>Stories by Vaibhav Meshram on Medium</title>
            <link>https://medium.com/@vaibhav.pmeshram?source=rss-dc09494ad3b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 07:26:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vaibhav.pmeshram/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating and Dismantling RSA Key in SecKey Swift iOS]]></title>
            <link>https://medium.com/@vaibhav.pmeshram/creating-and-dismantling-rsa-key-in-seckey-swift-ios-7b5077e41244?source=rss-dc09494ad3b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b5077e41244</guid>
            <category><![CDATA[modulus]]></category>
            <category><![CDATA[rsa-keys]]></category>
            <category><![CDATA[ne-to-seckey]]></category>
            <category><![CDATA[seckey]]></category>
            <category><![CDATA[exponent]]></category>
            <dc:creator><![CDATA[Vaibhav Meshram]]></dc:creator>
            <pubDate>Sun, 29 Mar 2020 21:20:45 GMT</pubDate>
            <atom:updated>2025-07-31T06:53:02.701Z</atom:updated>
            <content:encoded><![CDATA[<h3>Managing RSA Keys with SecKey in Swift on iOS: Creation and Deletion</h3><p>RSA Key Management in iOS with Swift and Objective-C</p><h3>JWK/PEM RSA Key to SecKey/SecKeyRef and back</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*HfnZCziVqP1KWpWtof07Ww.png" /></figure><p>In Swift, security keys are represented using the SecKey type. The characteristics of a key are defined by several factors, primarily including KeyClass, KeyType, key length, and more.</p><ul><li><strong>KeyClass</strong>: Indicates whether the key is a public or private key.</li><li><strong>Key Length</strong>: Typically 1024, 2048, 3072, or 4096 bits — always a multiple of 1024.</li></ul><p>RSA keys can be represented in various formats such as <strong>OpenSSH</strong>, <strong>PEM</strong>, or <strong>JWK</strong> (JSON Web Key).</p><h3>RSA Key Structure in JWK Format</h3><p>An <strong>RSA private key</strong> in JWK format includes both public and private components:</p><p><strong>Public Key</strong>:</p><ul><li>n – Modulus</li><li>e – Public exponent</li></ul><p><strong>Private Key Components</strong>:</p><ul><li>n, e – Public parts</li><li>d – Private exponent</li><li>p, q – Prime factors</li><li>dp, dq, qi – CRT (Chinese Remainder Theorem) parameters</li></ul><p>For more detailed information, refer to the <a href="https://en.wikipedia.org/wiki/RSA_(cryptosystem)">Wikipedia article on RSA</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkEpPmargIQYXDpHseqHFQ.png" /></figure><p>One frequently asked question is how to convert RSA keys from JWE (n and e) into SecKey, and back again.</p><p><strong>modules/exponent to SecKey</strong> and <strong>SecKey to modules/exponent</strong></p><h3>Creating New RSA key pair with random data</h3><pre>var publicKeySec, privateKeySec: SecKey?<br>let keyattribute = [<br>    kSecAttrKeyType as String: kSecAttrKeyTypeRSA,<br>    kSecAttrKeySizeInBits as String: 2048<br>] as CFDictionary<br>var error: Unmanaged&lt;CFError&gt;?<br>if #available(iOS 15.0.0, *) {<br>    privateKeySec = SecKeyCreateRandomKey(keyattribute, &amp;error)<br>    publicKeySec = SecKeyCopyPublicKey(privateKeySec!)<br>} else {<br>    SecKeyGeneratePair(keyattribute, &amp;publicKeySec, &amp;privateKeySec)<br>}</pre><p>Once created, the public and private keys are returned as SecKey objects. Their contents can be viewed via debugDescription.</p><h3>Extracting Data from RSA key</h3><pre>var keyData: Data!<br>if let data = SecKeyCopyExternalRepresentation(privateKeySec!, &amp;error) {<br>    keyData = data as Data<br>    let base64Key = keyData.base64EncodedString()<br>}</pre><h3>Creating RSA key from specific data</h3><pre>var keyData: Data = /*..........*/<br>//keyData length will be ((key length * 3) + 1)<br>let attributes: [String: Any] = [<br>    kSecAttrKeyType as String: kSecAttrKeyTypeRSA,<br>    kSecAttrKeyClass as String: kSecAttrKeyClassPrivate<br>]<br>var error: Unmanaged&lt;CFError&gt;?<br>let privKey: SecKey = SecKeyCreateWithData(keyData as CFData, attributes as CFDictionary, &amp;error)!</pre><p><strong>Only valid data will produce a valid </strong><strong>SecKey; otherwise, an error will be thrown.</strong><br> The data must be in Base64 format, where any - and _ characters are replaced with + and /, respectively.<br> Additionally, the Base64 string must be properly padded with = at the end so that its length is divisible by 4.</p><h3>Creating RSA Public key from n and e</h3><pre>var nStr = /* ...... */ //Base64 Formatted data<br>var eStr = /* ...... */<br>//Padding required<br>nStr = nStr.replacingOccurrences(of: &quot;-&quot;, with: &quot;+&quot;).replacingOccurrences(of: &quot;_&quot;, with: &quot;/&quot;)<br>  if nStr.count % 4 == 2 {<br>   nStr.append(&quot;==&quot;)<br>  }<br>  if nStr.count % 4 == 3 {<br>   nStr.append(&quot;=&quot;)<br>  }<br>  let nBytes = Data(base64Encoded: nStr)<br>  /*Same with e*/<br>  let eBytes = Data(base64Encoded: eStr)<br>  <br>//Now this bytes we have to append such that [48, 130, 1, 10, 2, 130, 1, 1, 0, /* nBytes */, 0x02 , 0x03 ,/* eBytes */ ]<br>var padding1 = Data([0x030,0x82,0x01,0x0a,0x02,0x82,0x01,0x01])<br>let padding2 = Data([0x02,0x03])<br>if nBytes[0] != 0 {<br>    padding1.append([0x00], count: 1)<br>}<br>var keyData = Data(padding1)<br>keyData.append(nBytes)<br>keyData.append(padding2)<br>keyData.append(eBytes)<br>let attributes: [String: Any] = [<br>            kSecAttrKeyType as String: kSecAttrKeyTypeRSA,<br>            kSecAttrKeyClass as String: kSecAttrKeyClassPublic,<br>            kSecAttrKeySizeInBits as String: 2048,<br>            kSecAttrIsPermanent as String: false<br>        ]<br>        var error: Unmanaged&lt;CFError&gt;?<br>        let keyReference = SecKeyCreateWithData(keyData as CFData, attributes as CFDictionary, &amp;error) as! SecKey</pre><p>To generate the private key, the following components are required: d, p, q, dp, dq, and qi.</p><h3>Getting n and e from SecKey RSA Public Key</h3><pre>var error: Unmanaged&lt;CFError&gt;?<br>let keyData = SecKeyCopyExternalRepresentation(publicKey, &amp;error)<br>var publicKeyBytes = keyData! as Data<br>publicKeyBytes.removeSubrange(Range(NSRange(location: 0, length: 9))!)<br>let n = publicKeyBytes.subdata(in: Range(NSRange.init(location: 0, length: 256))!)<br>let e = publicKeyBytes.subdata(in: Range(NSRange.init(location: publicKeyBytes.count - 3, length: 3))!)<br>//this n and e bytes can be expressed in HexaDecimal format or base64 format</pre><p>For example, here is a demo RSA public key with a size of 2048 bits.</p><pre>PKCS#8<br>-----BEGIN PUBLIC KEY-----<br>MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwBt3DQ6NHD6fGnq1yMlI<br>M71kL16/ySj6ZqmnKRGqIkPkXvTf5ZY4UUy3agbio8u49ULhW4iXa6h8t+GHLBPv<br>rL48YAggLwYaJaTmpM058ic3k0ed0MV2PoQEoVj+UyjD1tuqIqfNq9SxFkEmLjHU<br>TSBILEgS1dm0cxq6XRIXPtaEWYJsFruy9fXdzXica5Rrp5rrmKXHDmaR+5v/oX8B<br>mH+Yxd+hkSPRZPDN5aNsAeZeUnGrtgKYXxLBxPx27/UoiKaJ9qkVtTnzYqSzYWl/<br>HKr64PMiNdOi3nzqBs7Gx5BPA0k/O2B74kckuD7Z7Hu7qIDgxq1l4RS5bpIdaDYY<br>lQIDAQAH<br>-----END PUBLIC KEY-----<br><br>PKCS#1<br>-----BEGIN RSA PUBLIC KEY-----<br>MIIBCgKCAQEAwBt3DQ6NHD6fGnq1yMlIM71kL16/ySj6ZqmnKRGqIkPkXvTf5ZY4<br>UUy3agbio8u49ULhW4iXa6h8t+GHLBPvrL48YAggLwYaJaTmpM058ic3k0ed0MV2<br>PoQEoVj+UyjD1tuqIqfNq9SxFkEmLjHUTSBILEgS1dm0cxq6XRIXPtaEWYJsFruy<br>9fXdzXica5Rrp5rrmKXHDmaR+5v/oX8BmH+Yxd+hkSPRZPDN5aNsAeZeUnGrtgKY<br>XxLBxPx27/UoiKaJ9qkVtTnzYqSzYWl/HKr64PMiNdOi3nzqBs7Gx5BPA0k/O2B7<br>4kckuD7Z7Hu7qIDgxq1l4RS5bpIdaDYYlQIDAQAH<br>-----END RSA PUBLIC KEY-----<br><br>JWK<br>{<br>  &quot;kty&quot;: &quot;RSA&quot;,<br>  &quot;e&quot;: &quot;AQAH&quot;,<br>  &quot;n&quot;: &quot;wBt3DQ6NHD6fGnq1yMlIM71kL16_ySj6ZqmnKRGqIkPkXvTf5ZY4UUy3agbio8u49ULhW4iXa6h8t-GHLBPvrL48YAggLwYaJaTmpM058ic3k0ed0MV2PoQEoVj-UyjD1tuqIqfNq9SxFkEmLjHUTSBILEgS1dm0cxq6XRIXPtaEWYJsFruy9fXdzXica5Rrp5rrmKXHDmaR-5v_oX8BmH-Yxd-hkSPRZPDN5aNsAeZeUnGrtgKYXxLBxPx27_UoiKaJ9qkVtTnzYqSzYWl_HKr64PMiNdOi3nzqBs7Gx5BPA0k_O2B74kckuD7Z7Hu7qIDgxq1l4RS5bpIdaDYYlQ&quot;<br>}</pre><h3>For creating SecKey From Public key in PEM PKCS Format</h3><pre>let pubicKeyPem = &quot;MIIBCgKCAQEAwBt3DQ6NHD6fGnq1yMlIM71kL16/ySj6ZqmnKRGqIkPkXvTf5ZY4UUy3agbio8u49ULhW4iXa6h8t+GHLBPvrL48YAggLwYaJaTmpM058ic3k0ed0MV2PoQEoVj+UyjD1tuqIqfNq9SxFkEmLjHUTSBILEgS1dm0cxq6XRIXPtaEWYJsFruy9fXdzXica5Rrp5rrmKXHDmaR+5v/oX8BmH+Yxd+hkSPRZPDN5aNsAeZeUnGrtgKYXxLBxPx27/UoiKaJ9qkVtTnzYqSzYWl/HKr64PMiNdOi3nzqBs7Gx5BPA0k/O2B74kckuD7Z7Hu7qIDgxq1l4RS5bpIdaDYYlQIDAQAH&quot;</pre><h3>n and e in JWK related to above keys</h3><pre>var nStr = &quot;wBt3DQ6NHD6fGnq1yMlIM71kL16_ySj6ZqmnKRGqIkPkXvTf5ZY4UUy3agbio8u49ULhW4iXa6h8t-GHLBPvrL48YAggLwYaJaTmpM058ic3k0ed0MV2PoQEoVj-UyjD1tuqIqfNq9SxFkEmLjHUTSBILEgS1dm0cxq6XRIXPtaEWYJsFruy9fXdzXica5Rrp5rrmKXHDmaR-5v_oX8BmH-Yxd-hkSPRZPDN5aNsAeZeUnGrtgKYXxLBxPx27_UoiKaJ9qkVtTnzYqSzYWl_HKr64PMiNdOi3nzqBs7Gx5BPA0k_O2B74kckuD7Z7Hu7qIDgxq1l4RS5bpIdaDYYlQ&quot;<br>var eStr = &quot;AQAH&quot;</pre><h3>the attributes as Dictionay will be</h3><pre>let attributesRSAPub: [String:Any] = [<br>    kSecAttrKeyType as String: kSecAttrKeyTypeRSA,<br>    kSecAttrKeyClass as String: kSecAttrKeyClassPublic,<br>    kSecAttrKeySizeInBits as String: 2048,<br>    kSecAttrIsPermanent as String: false<br>]</pre><h3>PEM to SecKey</h3><pre>var error: Unmanaged&lt;CFError&gt;?<br>// PEM to Sec<br>let pubKeyRSAData = Data(base64Encoded: pubicKeyPem, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)<br>//printing<br>//pubKeyRSAData as CFData<br>&lt;3082010a 02820101 00a0d148 398e2c45 775c3b63 3b25eaaa 89c4dbf8 d69e700a 21361518 dea6f57b 086d7ae2 d967a049 80e6cff9 ec4851a4 8941af74 2f6a9db5 46a082ad cf6e64d0 dbf53109 af018e64 0e902c86 d514c222 06505596 5e093bbd 633d29f5 014c8074 db36c4ec ab54ee54 ae4e7516 4125edb0 01990e66 eeb21669 b2f0965b 5e61386a ed064389 b46a9591 5bd02cee 4a26be2b c132f671 0f4229b2 3d4cde8b 4e526354 8c5ecf18 c9a35b8b 6935b434 a9e188ac dc4521e7 a719bc84 4d09ca18 03dbe483 1c7f1afb f418820c 91cadaab a736ebf9 3765287c 4f99c891 8230a4a2 b717d818 8601da59 8f904336 483876dc 6a8199eb 9f1adb6d 2f7f2f6a a6017621 bf14f747 7302030f fbff&gt;<br>let publicKeySec = SecKeyCreateWithData(pubKeyRSAData as! CFData, attributesRSAPub as CFDictionary, &amp;error)<br>//printing<br>//SecKey <br>&lt;SecKeyRef algorithm id: 1, key type: RSAPublicKey, version: 4, block size: 2048 bits, exponent: {hex: ffbff, decimal: 1047551}, modulus: A0D148398E2C45775C3B633B25EAAA89C4DBF8D69E700A21361518DEA6F57B086D7AE2D967A04980E6CFF9EC4851A48941AF742F6A9DB546A082ADCF6E64D0DBF53109AF018E640E902C86D514C222065055965E093BBD633D29F5014C8074DB36C4ECAB54EE54AE4E75164125EDB001990E66EEB21669B2F0965B5E61386AED064389B46A95915BD02CEE4A26BE2BC132F6710F4229B23D4CDE8B4E5263548C5ECF18C9A35B8B6935B434A9E188ACDC4521E7A719BC844D09CA1803DBE4831C7F1AFBF418820C91CADAABA736EBF93765287C4F99C8918230A4A2B717D8188601DA598F904336483876DC6A8199EB9F1ADB6D2F7F2F6AA6017621BF14F74773, addr: 0x600002336e60&gt;</pre><h3>n and e (JWK) to SecKey</h3><pre>nStr = nStr.replacingOccurrences(of: “-”, with: “+”).replacingOccurrences(of: “_”, with: “/”)<br>if nStr.count % 4 == 2 {<br>    nStr.append(“==”)<br>}<br>if nStr.count % 4 == 3 {<br>    nStr.append(“=”)<br>}<br>eStr = eStr.replacingOccurrences(of: “-”, with: “+”).replacingOccurrences(of: “_”, with: “/”)<br>if eStr.count % 4 == 2 {<br>    eStr.append(“==”)<br>}<br>if eStr.count % 4 == 3 {<br>    eStr.append(“=”)<br>}<br>let n = [UInt8] (Data(base64Encoded: nStr)!)<br>let e = [UInt8] (Data(base64Encoded: eStr)!)<br>var padding1 = [UInt8](Data([0x030,0x82,0x01,0x0a,0x02,0x82,0x01,0x01]))<br>var padding2 = [UInt8](Data([0x02,0x03]))<br>if n[0] != 0 {<br>   padding12.append(0)<br>}<br>let pubBytes = padding1 + n + padding2 + e<br>let publicKey = SecKeyCreateWithData(Data.init(bytes: pubBytes) as CFData, attributesRSAPub as CFDictionary, &amp;error)<br>//Optional&lt;SecKeyRef&gt; - some : &lt;SecKeyRef algorithm id: 1, key type: RSAPublicKey, version: 4, block size: 2048 bits, exponent: {hex: 10007, decimal: 65543}, modulus: C01B770D0E8D1C3E9F1A7AB5C8C94833BD642F5EBFC928FA66A9A72911AA2243E45EF4DFE59638514CB76A06E2A3CBB8F542E15B88976BA87CB7E1872C13EFACBE3C6008202F061A25A4E6A4CD39F2273793479DD0C5763E8404A158FE5328C3D6DBAA22A7CDABD4B11641262E31D44D20482C4812D5D9B4731ABA5D12173ED68459826C16BBB2F5F5DDCD789C6B946BA79AEB98A5C70E6691FB9BFFA17F01987F98C5DFA19123D164F0CDE5A36C01E65E5271ABB602985F12C1C4FC76EFF52888A689F6A915B539F362A4B361697F1CAAFAE0F32235D3A2DE7CEA06CEC6C7904F03493F3B607BE24724B83ED9EC7BBBA880E0C6AD65E114B96E921D68361895, addr: 0x600003013720&gt;</pre><h3>SecKey to n and e</h3><pre>var error: Unmanaged&lt;CFError&gt;?<br>let keyData = SecKeyCopyExternalRepresentation(publicKey!, &amp;error)<br>keyData.removeSubrange(Range(NSRange(location: 0, length: 9))!)<br>let n = keyData.subdata(in: Range(NSRange(location: 0, length: 256))!)<br>let e = keyData.subdata(in: Range(NSRange(location: keyData.count - 3, length: 3))!)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8dDoUbkp2h6uvWNKInXUMw.jpeg" /></figure><p>Reach out to me for help with RSA public/private keys — please include “<strong>RSA Key Related</strong>” in your message subject.</p><p>vaibhav.pmeshram@gmail.com</p><p>StackoverFlow — <a href="https://stackoverflow.com/users/4030310/vaibby">https://stackoverflow.com/users/4030310/vaibby</a></p><p>Github — <a href="https://github.com/vaibhav1don">https://github.com/vaibhav1don</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b5077e41244" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating and Dismantling EC key in Swift]]></title>
            <link>https://medium.com/@vaibhav.pmeshram/creating-and-dismantling-ec-key-in-swift-f5bde8cb633f?source=rss-dc09494ad3b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5bde8cb633f</guid>
            <category><![CDATA[ecdh]]></category>
            <category><![CDATA[xy]]></category>
            <category><![CDATA[ec-key]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[public-private-ec-key]]></category>
            <dc:creator><![CDATA[Vaibhav Meshram]]></dc:creator>
            <pubDate>Tue, 28 May 2019 20:13:19 GMT</pubDate>
            <atom:updated>2025-09-29T14:38:27.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating and Dismantling EC Key in SecKey Swift (iOS)</h3><p>Working with and Understanding EC Keys in iOS using Swift and Objective-C</p><h3>JWK/PEM EC Key to SecKey/SecKeyRef and back</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*JnbLz-yl2M_prtf5cb9w1w.png" /></figure><h3>Understanding EC Key</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*tDZMxGL7MmxBzXW9HCycNQ.png" /></figure><p>Elliptic-curve cryptography (ECC) is an approach to public-key cryptography based on the algebraic structure of elliptic curves over finite fields. ECC requires smaller keys compared to non-EC cryptography (based on plain Galois fields) to provide equivalent security.<br>Elliptic curves are applicable for key agreement, digital signatures, pseudo-random generators and other tasks. Indirectly, they can be used for encryption by combining the key agreement with a symmetric encryption scheme. They are also used in several integer factorization algorithms based on elliptic curves that have applications in cryptography, such as Lenstra elliptic-curve factorization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*UlO9KjUqzHivPAfvphWAaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVgSA8lppCUu7idWMgMMyw.png" /></figure><p>In Swift (and Objective-C), security keys are represented by the SecKey type. A key is defined by several attributes, the most important being:</p><ul><li><strong>KeyClass</strong> — Whether the key is a <em>public key</em> or a <em>private key</em>.</li><li><strong>KeyType</strong> — The algorithm, such as <em>RSA</em> or <em>Elliptic Curve (EC)</em>.</li><li><strong>KeyLength</strong> — The curve size or modulus length, e.g., <em>P-256</em>, <em>P-384</em>, <em>P-521</em>, <em>B-283</em>, <em>B-409</em>, <em>B-571</em>.</li><li><strong>EC Size</strong> — The corresponding byte length, e.g., <em>32</em>, <em>48</em>, or <em>66</em>.</li></ul><h3>Key Formats</h3><p>Keys can be represented in multiple formats depending on the use case:</p><ul><li><strong>OpenSSH</strong></li><li><strong>PEM</strong> (Privacy-Enhanced Mail)</li><li><strong>JWK</strong> (JSON Web Key)</li></ul><h3>EC Keys in JWK Format</h3><p>An Elliptic Curve (EC) key in <strong>JWK</strong> format contains the following components:</p><ul><li><strong>Public Key</strong>:</li></ul><p>x – the x-coordinate of the curve point</p><p>y – the y-coordinate of the curve point</p><ul><li><strong>Private Key</strong>:</li></ul><p>Includes both the public key (x, y) and the private scalar (d)</p><p>Thus:</p><ul><li><strong>Public EC Key</strong> = { x, y }</li><li><strong>Private EC Key</strong> = { x, y, d }</li></ul><h3>Generating a new EC key pair with random data</h3><pre>var publicKeySec, privateKeySec: SecKey?<br>  let keyattribute = [<br>      kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,<br>      kSecAttrKeySizeInBits as String : 256<br>      ] as CFDictionary<br>  SecKeyGeneratePair(keyattribute, &amp;publicKeySec, &amp;privateKeySec)</pre><p>When you generate a new EC key pair with random data, you receive freshly created Public and Private keys in SecKey format. Their contents can be inspected using debugDescription.</p><h3>Generating an EC key from specific data</h3><pre>var keyData : Data = /*..........*/<br>//keyData length will be ((key length * 3) + 1)</pre><pre>let attributes: [String: Any] = [<br>            kSecAttrKeyType as String: kSecAttrKeyTypeEC,<br>            kSecAttrKeyClass as String: kSecAttrKeyClassPrivate<br>        ]</pre><pre>var error: Unmanaged&lt;CFError&gt;?<br>  let privKey : SecKey = SecKeyCreateWithData(keyData as CFData, attributes as CFDictionary, &amp;error)</pre><p>Generating an EC key from provided data requires that the input be properly formatted. A valid format will produce a SecKey, while an invalid one results in an error. The data must be Base64-encoded, where - and _ are substituted with + and /, and the string is padded with = until its length is a multiple of 4.</p><h3>Creating an EC key involves using the components <strong>x</strong>, <strong>y</strong>, and optionally <strong>d</strong></h3><pre>  var xStr = /* ...... */ //Base64 Formatted data<br>  var yStr = /* ...... */<br>  var dStr = /* ...... */ //For Public key we won&#39;t be using d value</pre><pre>  //Padding required </pre><pre>  xStr = xStr.replacingOccurrences(of: &quot;-&quot;, with: &quot;+&quot;).replacingOccurrences(of: &quot;_&quot;, with: &quot;/&quot;)<br>  if xStr.count % 4 == 2 {<br>   xStr.append(&quot;==&quot;)<br>  }<br>  if xStr.count % 4 == 3 {<br>   xStr.append(&quot;=&quot;)<br>  }<br>  let xBytes = Data(base64Encoded: xStr)<br>  /*Same with y and d*/<br>  let yBytes = Data(base64Encoded: yStr)<br>  let dBytes = Data(base64Encoded: dStr)<br>        </pre><pre>  //Now this bytes we have to append such that [0x04 , /* xBytes */, /* yBytes */, /* dBytes */]<br>  //Initial byte for uncompressed y as Key.<br>  let keyData = NSMutableData.init(bytes: [0x04], length: [0x04].count)<br>        keyData.append(xBytes)<br>        keyData.append(yBytes)<br>        keyData.append(dBytes)<br>        let attributes: [String: Any] = [<br>            kSecAttrKeyType as String: kSecAttrKeyTypeEC,<br>            kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,<br>            kSecAttrKeySizeInBits as String: 256,<br>            kSecAttrIsPermanent as String: false<br>        ]<br>        var error: Unmanaged&lt;CFError&gt;?<br>        let keyReference = SecKeyCreateWithData(keyData as CFData, attributes as CFDictionary, &amp;error) as! SecKey</pre><h3>Creating an EC Key</h3><p>To construct an EC key, you work with three possible components:</p><ul><li><strong>x and </strong><strong>y</strong> → These are required and represent the public key coordinates on the elliptic curve.</li><li><strong>d</strong> → This is optional and represents the private key value.</li></ul><h4>Public Key Only</h4><p>If you only need a <strong>public key</strong>, provide the x and y values. Together, they define the point on the elliptic curve.</p><h4>Full Key Pair (Public + Private)</h4><p>If you want a <strong>full key pair</strong>, include the d component in addition to x and y. The d value is the private scalar, which allows the key to perform signing or decryption operations.</p><p>By combining these components correctly, you can generate a valid EC key in SecKey format.</p><h3>Getting x, y and d from SecKey EC Key</h3><pre>var error: Unmanaged&lt;CFError&gt;?<br>let keyData = SecKeyCopyExternalRepresentation(privateKey, &amp;error)<br>let data = keyData! as Data<br>var privateKeyBytes = data.bytes<br>privateKeyBytes.removeFirst()</pre><pre>//For public key bytes will be divide into 2<br>let pointSize = privateKeyBytes.count / 3<br>let xBytes = privateKeyBytes[0..&lt;pointSize]<br>let yBytes = privateKeyBytes[pointSize..&lt;pointSize*2]</pre><pre>//dBytes wont be there in public key<br>let dBytes = privateKeyBytes[pointSize*2..&lt;pointSize*3]<br>//this x, y and d bytes can be expressed in HexaDecimal format or base64 format</pre><h3>Extracting EC Key Components (x, y, d) from a SecKey</h3><p>To obtain the raw components of an EC key (x, y, and optionally d), you generally follow these steps:</p><ol><li><strong>Export the Key Data</strong><br> Use SecKeyCopyExternalRepresentation to export the SecKey into raw binary data. This gives you the encoded key material.</li><li><strong>Decode the Key</strong><br> The exported data is usually encoded in <strong>ASN.1 (DER)</strong> or another standard format. You’ll need to parse this data to extract the elliptic curve parameters:</li></ol><ul><li><strong>x and </strong><strong>y</strong> → the coordinates of the public key on the elliptic curve.</li><li><strong>d</strong> → the private scalar, available only if the key is a <strong>private key</strong>.</li></ul><ol><li><strong>Understand Key Types</strong></li></ol><ul><li><strong>Public Keys</strong> → contain only x and y.</li><li><strong>Private Keys</strong> → contain x, y, and d.</li></ul><p><strong>Use Specialized Tools if Needed</strong><br> While you can manually parse ASN.1 data, it’s often easier to use a cryptography library (e.g., <strong>OpenSSL</strong> or Swift-compatible frameworks) to extract these values in a more direct way.</p><p>For example, this is a demo 256-bit EC private key, with a key length of 32 bytes.</p><pre>Curve name:[secp256r1, P-256, prime256v1]<br>Field Size:256<br>x:405964ECD9FB3142E17FFC9A765300F50005761207275E27A98F554BB78E904B<br>y:2E4D27C6DBA042BD31C5326049F24198A667213EBF61FA31918E9DD535D6BF7B<br>q:04405964ECD9FB3142E17FFC9A765300F50005761207275E27A98F554BB78E904B2E4D27C6DBA042BD31C5326049F24198A667213EBF61FA31918E9DD535D6BF7B<br>d:53893267A86D63D134001E5690436FE6AFB05F04820BA58A2197347C97B5279A</pre><pre>-----BEGIN OPENSSH PRIVATE KEY-----<br>b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNl<br>Y2RzYS1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQRAWWTs2fsxQuF//Jp2<br>UwD1AAV2EgcnXiepj1VLt46QSy5NJ8bboEK9McUyYEnyQZimZyE+v2H6MZGOndU1<br>1r97AAAAsFWwyYJVsMmCAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAy<br>NTYAAABBBEBZZOzZ+zFC4X/8mnZTAPUABXYSBydeJ6mPVUu3jpBLLk0nxtugQr0x<br>xTJgSfJBmKZnIT6/YfoxkY6d1TXWv3sAAAAgU4kyZ6htY9E0AB5WkENv5q+wXwSC<br>C6WKIZc0fJe1J5oAAAASZWNkc2Eta2V5LTIwMTkwNTI2AQIDBAUG<br>-----END OPENSSH PRIVATE KEY-----</pre><pre>-----BEGIN PRIVATE KEY-----<br>MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgU4kyZ6htY9E0AB5W<br>kENv5q+wXwSCC6WKIZc0fJe1J5qhRANCAARAWWTs2fsxQuF//Jp2UwD1AAV2Egcn<br>Xiepj1VLt46QSy5NJ8bboEK9McUyYEnyQZimZyE+v2H6MZGOndU11r97<br>-----END PRIVATE KEY-----</pre><pre>{<br>  &quot;kty&quot;: &quot;EC&quot;,<br>  &quot;d&quot;: &quot;U4kyZ6htY9E0AB5WkENv5q-wXwSCC6WKIZc0fJe1J5o&quot;,<br>  &quot;crv&quot;: &quot;P-256&quot;,<br>  &quot;x&quot;: &quot;QFlk7Nn7MULhf_yadlMA9QAFdhIHJ14nqY9VS7eOkEs&quot;,<br>  &quot;y&quot;: &quot;Lk0nxtugQr0xxTJgSfJBmKZnIT6_YfoxkY6d1TXWv3s&quot;<br>}</pre><h3>For creating SecKey From Private key &amp; Public key in PEM PKCS 8 Format</h3><pre>let privateKeyPem = &quot;MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgU4kyZ6htY9E0AB5WkENv5q+wXwSCC6WKIZc0fJe1J5qhRANCAARAWWTs2fsxQuF//Jp2UwD1AAV2EgcnXiepj1VLt46QSy5NJ8bboEK9McUyYEnyQZimZyE+v2H6MZGOndU11r97&quot;</pre><pre>let pubicKeyPem = &quot;MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEQFlk7Nn7MULhf/yadlMA9QAFdhIHJ14nqY9VS7eOkEsuTSfG26BCvTHFMmBJ8kGYpmchPr9h+jGRjp3VNda/ew==&quot;</pre><h3>x, y and d in JWK related to above keys</h3><pre>var xStr = &quot;QFlk7Nn7MULhf_yadlMA9QAFdhIHJ14nqY9VS7eOkEs&quot;<br>var yStr = &quot;Lk0nxtugQr0xxTJgSfJBmKZnIT6_YfoxkY6d1TXWv3s&quot;<br>var dStr = &quot;U4kyZ6htY9E0AB5WkENv5q-wXwSCC6WKIZc0fJe1J5o&quot;</pre><h3>the attributes as Dictionay will be</h3><pre>let attributesECPri: [String:Any] = [<br>    kSecAttrKeyType as String: kSecAttrKeyTypeEC,<br>    kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,<br>    kSecAttrKeySizeInBits as String: 256,<br>    kSecAttrIsPermanent as String: false<br>]</pre><pre>let attributesECPub: [String:Any] = [<br>    kSecAttrKeyType as String: kSecAttrKeyTypeEC,<br>    kSecAttrKeyClass as String: kSecAttrKeyClassPublic,<br>    kSecAttrKeySizeInBits as String: 256,<br>    kSecAttrIsPermanent as String: false<br>]</pre><h3>PEM to SecKey</h3><pre>// PEM to Sec</pre><pre>let priKeyECData = Data(base64Encoded: privateKeyPem, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)?.bytes</pre><pre>let priKeyECStriped = priKeyECData![(priKeyECData?.count)!-65..&lt;(priKeyECData?.count)!] + priKeyECData![36..&lt;68]</pre><pre>//Optional&lt;CFDataRef&gt; — some : &lt;04405964 ecd9fb31 42e17ffc 9a765300 f5000576 1207275e 27a98f55 4bb78e90 4b2e4d27 c6dba042 bd31c532 6049f241 98a66721 3ebf61fa 31918e9d d535d6bf 7b538932 67a86d63 d134001e 5690436f e6afb05f 04820ba5 8a219734 7c97b527 9a&gt;</pre><pre>let pubKeyECData = Data(base64Encoded: pubicKeyPem, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)?.bytes</pre><pre>let pubKeyECStriped = pubKeyECData![(pubKeyECData?.count)!-65..&lt;(pubKeyECData?.count)!]</pre><pre>//Optional&lt;CFDataRef&gt; — some : &lt;04405964 ecd9fb31 42e17ffc 9a765300 f5000576 1207275e 27a98f55 4bb78e90 4b2e4d27 c6dba042 bd31c532 6049f241 98a66721 3ebf61fa 31918e9d d535d6bf 7b&gt;</pre><pre>let privateKeySec = SecKeyCreateWithData(Data.init(bytes: priKeyECStriped) as CFData, attributesECPri as CFDictionary, &amp;error)</pre><pre>//Optional&lt;SecKeyRef&gt; — some : &lt;SecKeyRef curve type: kSecECCurveSecp256r1, algorithm id: 3, key type: ECPrivateKey, version: 4, block size: 256 bits, addr: 0x7f944bc1fc20&gt;</pre><pre>let publicKeySec = SecKeyCreateWithData(Data.init(bytes: pubKeyECStriped) as CFData, attributesECPub as CFDictionary, &amp;error)</pre><pre>//Optional&lt;SecKeyRef&gt; — some : &lt;SecKeyRef curve type: kSecECCurveSecp256r1, algorithm id: 3, key type: ECPublicKey, version: 4, block size: 256 bits, y: 2E4D27C6DBA042BD31C5326049F24198A667213EBF61FA31918E9DD535D6BF7B, x: 405964ECD9FB3142E17FFC9A765300F50005761207275E27A98F554BB78E904B, addr: 0x7f944bc1dff0&gt;</pre><h3>x, y and d (JWK) to SecKey</h3><pre>dStr = dStr.replacingOccurrences(of: “-”, with: “+”).replacingOccurrences(of: “_”, with: “/”)</pre><pre>if dStr.count % 4 == 2 {<br>    dStr.append(“==”)<br>}</pre><pre>if dStr.count % 4 == 3 {<br>    dStr.append(“=”)<br>}</pre><pre>xStr = xStr.replacingOccurrences(of: “-”, with: “+”).replacingOccurrences(of: “_”, with: “/”)</pre><pre>if xStr.count % 4 == 2 {<br>    xStr.append(“==”)<br>}</pre><pre>if xStr.count % 4 == 3 {<br>    xStr.append(“=”)<br>}</pre><pre>yStr = yStr.replacingOccurrences(of: “-”, with: “+”).replacingOccurrences(of: “_”, with: “/”)</pre><pre>if yStr.count % 4 == 2 {<br>    yStr.append(“==”)<br>}</pre><pre>if yStr.count % 4 == 3 {<br>    yStr.append(“=”)<br>}</pre><pre>let d : [UInt8] = (Data.init(base64Encoded: dStr)?.bytes)!<br>let x : [UInt8] = (Data.init(base64Encoded: xStr)?.bytes)!<br>let y : [UInt8] = (Data.init(base64Encoded: yStr)?.bytes)!<br>let i : [UInt8] = [0x04]<br>let privBytes = i + x + y + d<br>let pubBytes = i + x + y</pre><pre>let privateKey = SecKeyCreateWithData(Data.init(bytes: privBytes) as CFData, attributesECPri as CFDictionary, &amp;error)</pre><pre>//Optional&lt;SecKeyRef&gt; — some : &lt;SecKeyRef curve type: kSecECCurveSecp256r1, algorithm id: 3, key type: ECPrivateKey, version: 4, block size: 256 bits, addr: 0x7f944bc1fc20&gt;</pre><pre>let publicKey = SecKeyCreateWithData(Data.init(bytes: pubBytes) as CFData, attributesECPub as CFDictionary, &amp;error)</pre><pre>//Optional&lt;SecKeyRef&gt; — some : &lt;SecKeyRef curve type: kSecECCurveSecp256r1, algorithm id: 3, key type: ECPublicKey, version: 4, block size: 256 bits, y: 2E4D27C6DBA042BD31C5326049F24198A667213EBF61FA31918E9DD535D6BF7B, x: 405964ECD9FB3142E17FFC9A765300F50005761207275E27A98F554BB78E904B, addr: 0x7f944bc1dff0&gt;</pre><h3>SecKey to x, y and d</h3><pre>let ixyd = SecKeyCopyExternalRepresentation(privateKey!, &amp;error)</pre><pre>//Optional&lt;CFDataRef&gt; — some : &lt;04405964 ecd9fb31 42e17ffc 9a765300 f5000576 1207275e 27a98f55 4bb78e90 4b2e4d27 c6dba042 bd31c532 6049f241 98a66721 3ebf61fa 31918e9d d535d6bf 7b538932 67a86d63 d134001e 5690436f e6afb05f 04820ba5 8a219734 7c97b527 9a&gt;</pre><pre>let ixy = SecKeyCopyExternalRepresentation(publicKey!, &amp;error)</pre><pre>//Optional&lt;CFDataRef&gt; — some : &lt;04405964 ecd9fb31 42e17ffc 9a765300 f5000576 1207275e 27a98f55 4bb78e90 4b2e4d27 c6dba042 bd31c532 6049f241 98a66721 3ebf61fa 31918e9d d535d6bf 7b&gt;<br></pre><pre>if publicKeySec == publicKey &amp;&amp; privateKey == privateKeySec &amp;&amp; error == nil {<br>    print(“the end”)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8dDoUbkp2h6uvWNKInXUMw.jpeg" /></figure><p>Feel free to reach out for assistance with ECDH operations or other EC key–related topics. Make sure to use ‘EC Key’ as the subject.</p><p>vaibhav.pmeshram@gmail.com</p><p>StackoverFlow — <a href="https://stackoverflow.com/users/4030310/vaibby">https://stackoverflow.com/users/4030310/vaibby</a></p><p>Github — <a href="https://github.com/vaibhav1don">https://github.com/vaibhav1don</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5bde8cb633f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>