{"id":207861,"date":"2025-07-08T14:21:00","date_gmt":"2025-07-08T06:21:00","guid":{"rendered":"https:\/\/server.hk\/cnblog\/207861\/"},"modified":"2025-07-08T14:21:00","modified_gmt":"2025-07-08T06:21:00","slug":"golang-rsa-oaep%e8%a7%a3%e5%af%86%e5%a4%b1%e8%b4%a5%ef%bc%8c%e5%89%8d%e7%ab%af%e4%bd%bf%e7%94%a8webcrypto","status":"publish","type":"post","link":"https:\/\/server.hk\/cnblog\/207861\/","title":{"rendered":"Golang rsa-oaep\u89e3\u5bc6\u5931\u8d25\uff0c\u524d\u7aef\u4f7f\u7528webcrypto"},"content":{"rendered":"<p><b><\/b> <\/p>\n<p>\u5f53\u524d\u4f4d\u7f6e\uff1a <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>Golang rsa-oaep\u89e3\u5bc6\u5931\u8d25\uff0c\u524d\u7aef\u4f7f\u7528webcrypto<\/span><\/p>\n<p><span>\u6765\u6e90\uff1astackoverflow<\/span><br \/>\n<span>2024-04-26 10:00:45<\/span><br \/>\n<span><i><\/i>0\u6d4f\u89c8<\/span><br \/>\n<span style=\"cursor: pointer\"><i><\/i>\u6536\u85cf<\/span> <\/p>\n<p>\u672c\u7bc7\u6587\u7ae0\u7ed9\u5927\u5bb6\u5206\u4eab\u300aGolang rsa-oaep\u89e3\u5bc6\u5931\u8d25\uff0c\u524d\u7aef\u4f7f\u7528webcrypto\u300b\uff0c\u8986\u76d6\u4e86Golang\u7684\u5e38\u89c1\u57fa\u7840\u77e5\u8bc6\uff0c\u5176\u5b9e\u4e00\u4e2a\u8bed\u8a00\u7684\u5168\u90e8\u77e5\u8bc6\u70b9\u4e00\u7bc7\u6587\u7ae0\u662f\u4e0d\u53ef\u80fd\u8bf4\u5b8c\u7684\uff0c\u4f46\u5e0c\u671b\u901a\u8fc7\u8fd9\u4e9b\u95ee\u9898\uff0c\u8ba9\u8bfb\u8005\u5bf9\u81ea\u5df1\u7684\u638c\u63e1\u7a0b\u5ea6\u6709\u4e00\u5b9a\u7684\u8ba4\u8bc6(B \u6570)\uff0c\u4ece\u800c\u5f25\u8865\u81ea\u5df1\u7684\u4e0d\u8db3\uff0c\u66f4\u597d\u7684\u638c\u63e1\u5b83\u3002<\/p>\n<p> \u95ee\u9898\u5185\u5bb9<br \/>\n <\/p>\n<p>\u6211\u7528 golang \u7f16\u5199\u4e86\u8fd9\u4e2a\u5e94\u7528\u7a0b\u5e8f\u4f5c\u4e3a\u540e\u7aef\uff0c\u4f7f\u7528 typescript \u4f5c\u4e3a\u524d\u7aef\u3002\u6211\u9700\u8981\u5bf9\u4f20\u8f93\u7684\u6570\u636e\u8fdb\u884c\u52a0\u5bc6\uff0c\u6240\u4ee5\u6211\u9009\u62e9rsa\u52a0\u5bc6\uff0c\u57fa\u672c\u4e0a\u6b65\u9aa4\u5982\u4e0b\uff1a<\/p>\n<p><strong>* \u540e\u7aef *<\/strong><\/p>\n<ol>\n<li>golang\u751f\u6210\u79c1\u94a5\u548c\u516c\u94a5\uff0c\u4fdd\u5b58\u5728redis\u4e2d<\/li>\n<li>golang \u4f7f\u7528 lestrrat-go\/jwx\/ \u5c06\u516c\u94a5\u8f6c\u6362\u4e3a jwk\uff08json web \u5bc6\u94a5\uff09<\/li>\n<li>golang \u53d1\u9001 jwk<\/li>\n<\/ol>\n<p><strong>* \u524d\u7aef *<\/strong><\/p>\n<ol>\n<li>typescript \u4f7f\u7528 webcrypto api \u5bfc\u5165 jwk \u5bc6\u94a5<\/li>\n<li>typescript \u4f7f\u7528\u5bfc\u5165\u7684\u5bc6\u94a5\u6765\u52a0\u5bc6\u4e00\u4e9b\u7eaf\u6587\u672c<\/li>\n<li>\u52a0\u5bc6\u540e\uff0c\u6211\u5f97\u5230\u4e00\u4e2aarraybuffer\uff0c\u4e3a\u4e86\u9632\u6b62\u4efb\u4f55\u7f16\u7801\u95ee\u9898\uff0c\u6211\u7136\u540e\u5c06arraybuffer\u5b57\u8282\u5230\u5b57\u8282\u8f6c\u6362\u4e3a\u6574\u6570\u6570\u7ec4<\/li>\n<li>\u5c06\u8f6c\u6362\u540e\u7684\u6574\u6570\u6570\u7ec4\u53d1\u9001\u5230\u5b57\u7b26\u4e32\u5316 json \u4e2d\u7684\u540e\u7aef<\/li>\n<\/ol>\n<p><strong>* \u540e\u7aef *<\/strong><\/p>\n<ol>\n<li>golang \u63a5\u6536 json \u5e76\u5c06\u6574\u6570\u6570\u7ec4\u8f6c\u6362\u4e3a <code>[]byte<\/code><\/li>\n<li>\u4eceredis\u4e2d\u68c0\u7d22\u79c1\u94a5\u5e76\u89e3\u5bc6<\/li>\n<\/ol>\n<p>\u73b0\u5728\u6211\u5f97\u5230\u7684\u53ea\u662f <code> \u89e3\u5bc6\u9519\u8bef <\/code>&#8230;<\/p>\n<p>\u6211\u68c0\u67e5\u8fc7\u7684\u4e8b\u60c5\uff1a<\/p>\n<ul>\n<li>\u540e\u7aef golang \u5355\u72ec\u52a0\u5bc6\/\u89e3\u5bc6\u5c31\u53ef\u4ee5\u4e86<\/li>\n<li>\u5355\u72ec\u4f7f\u7528\u524d\u7aef webcrypto \u52a0\u5bc6\/\u89e3\u5bc6\u5c31\u53ef\u4ee5\u4e86<\/li>\n<li>\n<p>\u68c0\u67e5 golang rsa.publickey -&gt; jwk \u671f\u95f4\u662f\u5426\u51fa\u73b0\u95ee\u9898<\/p>\n<ol>\n<li>\u5982\u679c\u524d\u7aef\u4ece\u540e\u7aef\u83b7\u53d6jwk<\/li>\n<li>\u5bfc\u5165<\/li>\n<li>\u7136\u540e\u5bfc\u51fa<\/li>\n<li>\u5c06\u5bfc\u51fa\u7684\u5bc6\u94a5\u53d1\u9001\u56de\u540e\u7aef<\/li>\n<li>\u540e\u7aef\u5c06jwk\u8f6c\u6362\u56dersa\u516c\u94a5\uff0c\u76f8\u5f53\u4e8eredis\u4e2d\u4fdd\u5b58\u7684\u516c\u94a5<\/li>\n<\/ol>\n<\/li>\n<li>\n<p>\u540e\u7aef\u63a5\u6536\u5230int\u6570\u7ec4\u540e\uff0c\u5c06\u5176\u8f6c\u6362\u4e3a<code>[]byte<\/code>\u540e\uff0c\u5176\u957f\u5ea6\u548c\u5185\u5bb9\u4e0e\u524d\u7aef\u7684\u957f\u5ea6\u548c\u5185\u5bb9\u76f8\u540c<\/p>\n<\/li>\n<\/ul>\n<p>\u4ee3\u7801\u5982\u4e0b\uff1a<\/p>\n<pre>\n    func rsadecrypt(privatekey *rsa.privatekey, messagetodecrypt, cryptlabel []byte) (deciphertext []byte, err error) {\n        if privatekey == nil {\n            return nil, errors.new(\"private cannot be nil\")\n        }\n        if messagetodecrypt == nil {\n            return nil, errors.new(\"message cannot be nil\")\n        }\n        rng := rand.reader\n        return rsa.decryptoaep(sha256.new(), rng, privatekey, messagetodecrypt, cryptlabel)\n    }\n\n    func generatekeypair() (privatekey *rsa.privatekey, publickey *rsa.publickey, err error) {\n        privatekey, err = rsa.generatekey(rand.reader, bitsize)\n        if err != nil {\n            return nil, nil, err\n        }\n        return privatekey, &amp;privatekey.publickey, nil\n    }\n\n    func bytestorsaprivatekey(privatekeybytes []byte) (*rsa.privatekey, error) {\n        if privatekeybytes == nil {\n            return nil, errors.new(\"private key bytes cannot be nil\")\n        }\n        block, _ := pem.decode(privatekeybytes)\n        enc := x509.isencryptedpemblock(block)\n        b := block.bytes\n        var err error\n        if enc {\n            log.println(\"is encrypted pem block\")\n            b, err = x509.decryptpemblock(block, nil)\n            if err != nil {\n                return nil, err\n            }\n        }\n        key, err := x509.parsepkcs1privatekey(b)\n        if err != nil {\n            return nil, err\n        }\n        return key, nil\n    }\n    ...\n    func userlogin(useruuid string, loginuserinfo []byte) error {\n        privatekeyinstring, err := adapter.get(useruuid + \":privatekey\")\n        if err != nil {\n            return err\n        }\n        privatekey, err := cred.bytestorsaprivatekey([]byte(privatekeyinstring))\n        if err != nil {\n            return err\n        }\n            var userinfo struct {\n            username          string `json:\"username\"`\n            encryptedpassword []int  `json:\"password\"`\n        }\n        err = json.unmarshal(loginuserinfo, &amp;userinfo)\n        if err != nil {\n            return err\n        }\n        encryptedinbytes := util.intarraytobytearray(userinfo.encryptedpassword)\n        fmt.println(\"encrypted length: \", len(encryptedinbytes))\n        fmt.println(encryptedinbytes)\n        decrypted, err := cred.rsadecrypt(privatekey, encryptedinbytes, []byte(\"qp_user_login\"))\n        if err != nil {\n            fmt.println(\"3, \", err)                 \/\/ &lt;&lt;&lt;============================= i'm getting here\n            return err\n        }\n        fmt.println(string(decrypted))\n\n        return nil\n    }\n\n<\/pre>\n<pre>\n    static async importpublickey(keydata: string): promise&lt;cryptokey&gt; {\n        return new promise&lt;cryptokey&gt;((resolve, reject) =&gt; {\n            return window.crypto.subtle.importkey(\n                \"jwk\", \/\/can be \"jwk\" (public or private), \"spki\" (public only), or \"pkcs8\" (private only)\n                {   \/\/this is an example jwk key, other key types are uint8array objects\n                    e: \"aqab\",\n                    kty: \"rsa\",\n                    n: keydata,\n                    alg: \"rsa-oaep-256\",\n                    ext: true,\n                },\n                {\n                    name: 'rsa-oaep',\n                    hash: {name: 'sha-256'}\n                },\n                true,\n                ['encrypt']\n            )\n                .then(publickey =&gt; {\n                    resolve(publickey);\n                })\n                .catch(err =&gt; {\n                    reject(err);\n                });\n        });\n    }\n\n    static async encrypt(publickey: cryptokey, l, datatoencrypt: string) {\n        return new promise&lt;number[]&gt;((resolve, reject) =&gt; {\n            return window.crypto.subtle.encrypt(\n                {\n                    name: 'rsa-oaep',\n                    label: toolbox.stringtoarraybuffer(l)\n                },\n                publickey,\n                toolbox.stringtoarraybuffer(datatoencrypt)\n            )\n                .then(encrypted =&gt; {\n                    let uint8view = new uint8array(encrypted);\n                    let intarray: number[] = [];\n                    for (let i = 0; i &lt; uint8view.bytelength; i++) {\n                        intarray.push(uint8view[i]);\n                    }\n                    resolve(intarray);\n                })\n                .catch(err =&gt; {\n                    console.error(err);\n                    reject(err);\n                });\n        });\n    }\n\n    async sendlogin(jwkfromserver: any) {\n        let serverpublickey = await crypto.importpublickey(message.content.n);\n        let exported = await crypto.exportpublickey(serverpublickey);\n\n        let encrypteddatachunk = await crypto.encrypt(serverpublickey, 'qp_user_login', 'hello foobar');\n        \/\/ \u6b63\u5f0f\u53d1\u51fa\u5305\u542b\u7528\u6237\u540d\u548c\u52a0\u5bc6\u7684\u5bc6\u7801\u7684\u767b\u5f55\u8bf7\u6c42\n        let userlogininfo = {\n            username: 'ycx',\n            password: encrypteddatachunk\n        };\n        let tempuseruuid = ds.gettempuseruuid();\n        console.log('-#@#!#!%%% stringify: ');\n        console.log(json.stringify(userlogininfo));\n        ws.sendmessage({\n            p: tempuseruuid,\n            t: `${constants.clienttoservermessage.officiallogin}`,\n            c: json.stringify(userlogininfo)\n            \/\/ c: json.stringify(exported)\n        });\n    }\n<\/pre>\n<p><strong>\u66f4\u65b0<\/strong><\/p>\n<p>\u5728\u6b64\u5904\u6dfb\u52a0\u4e00\u4e9b\u6253\u5370\u65e5\u5fd7\uff1a<\/p>\n<ul>\n<li>\u540e\u7aef\uff1a<\/li>\n<\/ul>\n<pre>\n    jwk:  {\n            \"e\": \"aqab\",\n            \"kty\": \"rsa\",\n            \"n\": \"7uctpcmrhqvkfkqoouoiy57bfycm_mhmtuax6n1jj-jtlbpn799urwatj0tk5zl9ujzr89euntt0dcl0art7vukyyzw4sty7tk6ivkgkycmeqkam2yiy0g7agj1appdwnssmoxpfppdamjhezrxvtwvt1tohz9h_37x_xvwcfdlr6jpsrch-dmk87pwrvkxc6x1ijvfhmoaj9lvbrs0rxaf_sguhomsjzoufi9ikmvnonvo1r6dittqxj2ecj6-zo2e0qranqpu9__yvqg5bwkwn8-ficgohnam9-dmlekriiog3cgxvpjgea2akr0_xb-fsvzrrsyjyazietztk-q\"\n    }\n    public key:\n    -----begin rsa public key-----\n    miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqea7uctpcmrhqvkfkqoouoi\n    y57bfycm\/mhmtuax6n1jj+jtlbpn799urwatj0tk5zl9ujzr89euntt0dcl0art7\n    vukyyzw4sty7tk6ivkgkycmeqkam2yiy0g7agj1appdwnssmoxpfppdamjhezrxv\n    twvt1tohz9h\/37x\/xvwcfdlr6jpsrch+dmk87pwrvkxc6x1ijvfhmoaj9lvbrs0r\n    xaf\/sguhomsjzoufi9ikmvnonvo1r6dittqxj2ecj6+zo2e0qranqpu9\/\/yvqg5b\n    wkwn8+ficgohnam9+dmlekriiog3cgxvpjgea2akr0\/xb+fsvzrrsyjyazietztk\n    +qidaqab\n    -----end rsa public key-----\n\n    encrypted length:  256 and its content in []byte:\n    [187 39 30 53 22 144 100 28 16 168 214 201 115 116 147 82 95 117 84 226 22 100 216 250 222 149 230 162 79 205 19 100 146 226 221 110 155 9 177 19 254 13 141 31 23 208 187 177 228 229 121 148 186 8 213 61 130 230 190 98 147 10 197 138 68 30 243 121 212 4 243 52 240 108 143 126 181 71 5 223 159 27 242 15 150 84 233 255 218 194 151 183 203 158 199 246 128 122 6 45 137 252 48 30 80 150 100 121 158 240 96 164 45 142 110 182 98 230 107 198 142 250 107 38 224 152 228 195 0 38 102 208 216 5 138 67 249 110 171 49 84 195 42 29 74 147 56 233 193 168 189 142 110 24 16 188 210 20 149 44 172 100 1 119 4 21 81 121 26 98 2 163 219 225 218 186 144 220 78 243 212 5 66 40 116 160 147 128 41 201 194 0 74 69 116 204 202 88 204 86 16 164 16 8 142 36 154 189 228 144 61 233 128 247 80 95 190 39 82 34 155 197 130 74 215 73 6 240 37 158 130 11 66 192 54 252 197 71 247 69 115 202 234 30 57 192 254 136 150 71 149 231 207 237 108 217]\n    3,  crypto\/rsa: decryption error\n\n<\/pre>\n<ul>\n<li>\u524d\u7aef\uff1a<\/li>\n<\/ul>\n<pre>-#@#!#!%%% stringify: \n    {\"username\":\"ycx\",\"password\":[187,39,30,53,22,144,100,28,16,168,214,201,115,116,147,82,95,117,84,226,22,100,216,250,222,149,230,162,79,205,19,100,146,226,221,110,155,9,177,19,254,13,141,31,23,208,187,177,228,229,121,148,186,8,213,61,130,230,190,98,147,10,197,138,68,30,243,121,212,4,243,52,240,108,143,126,181,71,5,223,159,27,242,15,150,84,233,255,218,194,151,183,203,158,199,246,128,122,6,45,137,252,48,30,80,150,100,121,158,240,96,164,45,142,110,182,98,230,107,198,142,250,107,38,224,152,228,195,0,38,102,208,216,5,138,67,249,110,171,49,84,195,42,29,74,147,56,233,193,168,189,142,110,24,16,188,210,20,149,44,172,100,1,119,4,21,81,121,26,98,2,163,219,225,218,186,144,220,78,243,212,5,66,40,116,160,147,128,41,201,194,0,74,69,116,204,202,88,204,86,16,164,16,8,142,36,154,189,228,144,61,233,128,247,80,95,190,39,82,34,155,197,130,74,215,73,6,240,37,158,130,11,66,192,54,252,197,71,247,69,115,202,234,30,57,192,254,136,150,71,149,231,207,237,108,217]}<\/pre>\n<p> <\/p>\n<h2>\u89e3\u51b3\u65b9\u6848<\/h2>\n<p> <\/p>\n<p>\u597d\u5427\uff0c\u6211\u7684\u95ee\u9898\u662f\u5ba2\u6237\u7aef\u7684\u6570\u7ec4\u7f13\u51b2\u533a\u5230\u5b57\u7b26\u4e32\u548c\u5b57\u7b26\u4e32\u5230\u6570\u7ec4\u7f13\u51b2\u533a\u7684\u8f6c\u6362\u3002\u7531\u4e8e\u540e\u7aef\u5904\u7406 <code>[]byte<\/code> \u4e2d\u7684\u51e0\u4e4e\u6240\u6709\u5185\u5bb9\uff08\u5b9e\u9645\u4e0a\u662f\u5b57\u8282\u6570\u7ec4\uff09\uff0c\u56e0\u6b64\u5728\u524d\u7aef\u8fdb\u884c\u8f6c\u6362\u65f6\uff0c<strong>\u59cb\u7ec8<\/strong>\u4f7f\u7528 <code>uint8array<\/code> \u800c\u4e0d\u662f <code>uint16array<\/code> \uff0c\u5982\u4e0b\u6240\u793a\uff1a<\/p>\n<pre>    str2ab(str: string): arraybuffer {\n        const buf = new arraybuffer(str.length);\n        const bufview = new uint8array(buf);\n        for (let i = 0, strlen = str.length; i &lt; strlen; i++) {\n            bufview[i] = str.charcodeat(i);\n        }\n        return buf;\n    }\n\n    ab2str(buf: arraybuffer): string {\n        return string.fromcharcode.apply(null, new uint8array(buf));\n    }\n<\/pre>\n<p>\u66f4\u5177\u4f53\u5730\u8bf4\uff0c\u524d\u7aef\u52a0\u5bc6\u65f6\u7684\u6807\u7b7e\u5b57\u6bb5\u8ba9\u6211\u5934\u75bc\u3002 <\/p>\n<p>\u4e00\u4e9b\u65c1\u6ce8\uff1a\u5728\u53d1\u9001\u5230\u540e\u7aef\u4e4b\u524d\u5c06\u52a0\u5bc6\u6570\u636e\u4ece arraybuffer \u8f6c\u6362\u4e3a int \u6570\u7ec4\u5e76\u4e0d\u662f\u660e\u667a\u4e4b\u4e3e\uff0c\u8fd9\u5c31\u662f base64 \u7f16\u7801\u7684\u7528\u9014\uff1a<\/p>\n<pre>    uint8ArrayToBase64(buf: Uint8Array): string {\n        let binaryStr = Array.prototype.map.call(buf, function (ch) {\n            return String.fromCharCode(ch);\n        }).join('');\n        return btoa(binaryStr);\n    }\n    ...\n    const encrypted = await Crypto.encrypt(serverPublicKey, loginLabel, enteredPassword); \/\/ &lt;&lt;&lt;================= encrypted is an ArrayBuffer\n    const encryptedUint8Array = new Uint8Array(encrypted);\n    const base64Encoded = uint8ArrayToBase64(encryptedUint8Array);\n    \/\/ Now we're good to send the encrypted data to the backend\n    ...\n<\/pre>\n<p>\u5e0c\u671b\u8fd9\u80fd\u8282\u7701\u5176\u4ed6\u4eba\u7684\u5b9d\u8d35\u65f6\u95f4&#8230;\u5e72\u676f\uff01<\/p>\n<p>\u672c\u7bc7\u5173\u4e8e\u300aGolang rsa-oaep\u89e3\u5bc6\u5931\u8d25\uff0c\u524d\u7aef\u4f7f\u7528webcrypto\u300b\u7684\u4ecb\u7ecd\u5c31\u5230\u6b64\u7ed3\u675f\u5566\uff0c\u4f46\u662f\u5b66\u65e0\u6b62\u5883\uff0c\u60f3\u8981\u4e86\u89e3\u5b66\u4e60\u66f4\u591a\u5173\u4e8eGolang\u7684\u76f8\u5173\u77e5\u8bc6\uff0c\u8bf7\u5173\u6ce8\u516c\u4f17\u53f7\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5f53\u524d\u4f4d\u7f6e\uff1a &gt; &gt; &#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4925],"tags":[],"class_list":["post-207861","post","type-post","status-publish","format-standard","hentry","category-4925"],"_links":{"self":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/207861","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/comments?post=207861"}],"version-history":[{"count":0,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/207861\/revisions"}],"wp:attachment":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/media?parent=207861"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/categories?post=207861"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/tags?post=207861"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}