登录
首页 >  Golang >  Go问答

Golang rsa-oaep解密失败,前端使用webcrypto

来源:stackoverflow

时间:2024-04-26 10:00:45 501浏览 收藏

本篇文章给大家分享《Golang rsa-oaep解密失败,前端使用webcrypto》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我用 golang 编写了这个应用程序作为后端,使用 typescript 作为前端。我需要对传输的数据进行加密,所以我选择rsa加密,基本上步骤如下:

* 后端 *

  1. golang生成私钥和公钥,保存在redis中
  2. golang 使用 lestrrat-go/jwx/ 将公钥转换为 jwk(json web 密钥)
  3. golang 发送 jwk

* 前端 *

  1. typescript 使用 webcrypto api 导入 jwk 密钥
  2. typescript 使用导入的密钥来加密一些纯文本
  3. 加密后,我得到一个arraybuffer,为了防止任何编码问题,我然后将arraybuffer字节到字节转换为整数数组
  4. 将转换后的整数数组发送到字符串化 json 中的后端

* 后端 *

  1. golang 接收 json 并将整数数组转换为 []byte
  2. 从redis中检索私钥并解密

现在我得到的只是 解密错误 ...

我检查过的事情:

  • 后端 golang 单独加密/解密就可以了
  • 单独使用前端 webcrypto 加密/解密就可以了
  • 检查 golang rsa.publickey -> jwk 期间是否出现问题

    1. 如果前端从后端获取jwk
    2. 导入
    3. 然后导出
    4. 将导出的密钥发送回后端
    5. 后端将jwk转换回rsa公钥,相当于redis中保存的公钥
  • 后端接收到int数组后,将其转换为[]byte后,其长度和内容与前端的长度和内容相同

代码如下:

    func rsadecrypt(privatekey *rsa.privatekey, messagetodecrypt, cryptlabel []byte) (deciphertext []byte, err error) {
        if privatekey == nil {
            return nil, errors.new("private cannot be nil")
        }
        if messagetodecrypt == nil {
            return nil, errors.new("message cannot be nil")
        }
        rng := rand.reader
        return rsa.decryptoaep(sha256.new(), rng, privatekey, messagetodecrypt, cryptlabel)
    }

    func generatekeypair() (privatekey *rsa.privatekey, publickey *rsa.publickey, err error) {
        privatekey, err = rsa.generatekey(rand.reader, bitsize)
        if err != nil {
            return nil, nil, err
        }
        return privatekey, &privatekey.publickey, nil
    }

    func bytestorsaprivatekey(privatekeybytes []byte) (*rsa.privatekey, error) {
        if privatekeybytes == nil {
            return nil, errors.new("private key bytes cannot be nil")
        }
        block, _ := pem.decode(privatekeybytes)
        enc := x509.isencryptedpemblock(block)
        b := block.bytes
        var err error
        if enc {
            log.println("is encrypted pem block")
            b, err = x509.decryptpemblock(block, nil)
            if err != nil {
                return nil, err
            }
        }
        key, err := x509.parsepkcs1privatekey(b)
        if err != nil {
            return nil, err
        }
        return key, nil
    }
    ...
    func userlogin(useruuid string, loginuserinfo []byte) error {
        privatekeyinstring, err := adapter.get(useruuid + ":privatekey")
        if err != nil {
            return err
        }
        privatekey, err := cred.bytestorsaprivatekey([]byte(privatekeyinstring))
        if err != nil {
            return err
        }
            var userinfo struct {
            username          string `json:"username"`
            encryptedpassword []int  `json:"password"`
        }
        err = json.unmarshal(loginuserinfo, &userinfo)
        if err != nil {
            return err
        }
        encryptedinbytes := util.intarraytobytearray(userinfo.encryptedpassword)
        fmt.println("encrypted length: ", len(encryptedinbytes))
        fmt.println(encryptedinbytes)
        decrypted, err := cred.rsadecrypt(privatekey, encryptedinbytes, []byte("qp_user_login"))
        if err != nil {
            fmt.println("3, ", err)                 // <<<============================= i'm getting here
            return err
        }
        fmt.println(string(decrypted))

        return nil
    }

    static async importpublickey(keydata: string): promise<cryptokey> {
        return new promise<cryptokey>((resolve, reject) => {
            return window.crypto.subtle.importkey(
                "jwk", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
                {   //this is an example jwk key, other key types are uint8array objects
                    e: "aqab",
                    kty: "rsa",
                    n: keydata,
                    alg: "rsa-oaep-256",
                    ext: true,
                },
                {
                    name: 'rsa-oaep',
                    hash: {name: 'sha-256'}
                },
                true,
                ['encrypt']
            )
                .then(publickey => {
                    resolve(publickey);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }

    static async encrypt(publickey: cryptokey, l, datatoencrypt: string) {
        return new promise<number[]>((resolve, reject) => {
            return window.crypto.subtle.encrypt(
                {
                    name: 'rsa-oaep',
                    label: toolbox.stringtoarraybuffer(l)
                },
                publickey,
                toolbox.stringtoarraybuffer(datatoencrypt)
            )
                .then(encrypted => {
                    let uint8view = new uint8array(encrypted);
                    let intarray: number[] = [];
                    for (let i = 0; i < uint8view.bytelength; i++) {
                        intarray.push(uint8view[i]);
                    }
                    resolve(intarray);
                })
                .catch(err => {
                    console.error(err);
                    reject(err);
                });
        });
    }

    async sendlogin(jwkfromserver: any) {
        let serverpublickey = await crypto.importpublickey(message.content.n);
        let exported = await crypto.exportpublickey(serverpublickey);

        let encrypteddatachunk = await crypto.encrypt(serverpublickey, 'qp_user_login', 'hello foobar');
        // 正式发出包含用户名和加密的密码的登录请求
        let userlogininfo = {
            username: 'ycx',
            password: encrypteddatachunk
        };
        let tempuseruuid = ds.gettempuseruuid();
        console.log('-#@#!#!%%% stringify: ');
        console.log(json.stringify(userlogininfo));
        ws.sendmessage({
            p: tempuseruuid,
            t: `${constants.clienttoservermessage.officiallogin}`,
            c: json.stringify(userlogininfo)
            // c: json.stringify(exported)
        });
    }

更新

在此处添加一些打印日志:

  • 后端:
    jwk:  {
            "e": "aqab",
            "kty": "rsa",
            "n": "7uctpcmrhqvkfkqoouoiy57bfycm_mhmtuax6n1jj-jtlbpn799urwatj0tk5zl9ujzr89euntt0dcl0art7vukyyzw4sty7tk6ivkgkycmeqkam2yiy0g7agj1appdwnssmoxpfppdamjhezrxvtwvt1tohz9h_37x_xvwcfdlr6jpsrch-dmk87pwrvkxc6x1ijvfhmoaj9lvbrs0rxaf_sguhomsjzoufi9ikmvnonvo1r6dittqxj2ecj6-zo2e0qranqpu9__yvqg5bwkwn8-ficgohnam9-dmlekriiog3cgxvpjgea2akr0_xb-fsvzrrsyjyazietztk-q"
    }
    public key:
    -----begin rsa public key-----
    miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqea7uctpcmrhqvkfkqoouoi
    y57bfycm/mhmtuax6n1jj+jtlbpn799urwatj0tk5zl9ujzr89euntt0dcl0art7
    vukyyzw4sty7tk6ivkgkycmeqkam2yiy0g7agj1appdwnssmoxpfppdamjhezrxv
    twvt1tohz9h/37x/xvwcfdlr6jpsrch+dmk87pwrvkxc6x1ijvfhmoaj9lvbrs0r
    xaf/sguhomsjzoufi9ikmvnonvo1r6dittqxj2ecj6+zo2e0qranqpu9//yvqg5b
    wkwn8+ficgohnam9+dmlekriiog3cgxvpjgea2akr0/xb+fsvzrrsyjyazietztk
    +qidaqab
    -----end rsa public key-----

    encrypted length:  256 and its content in []byte:
    [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]
    3,  crypto/rsa: decryption error

  • 前端:
-#@#!#!%%% stringify: 
    {"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]}

解决方案


好吧,我的问题是客户端的数组缓冲区到字符串和字符串到数组缓冲区的转换。由于后端处理 []byte 中的几乎所有内容(实际上是字节数组),因此在前端进行转换时,始终使用 uint8array 而不是 uint16array ,如下所示:

    str2ab(str: string): arraybuffer {
        const buf = new arraybuffer(str.length);
        const bufview = new uint8array(buf);
        for (let i = 0, strlen = str.length; i < strlen; i++) {
            bufview[i] = str.charcodeat(i);
        }
        return buf;
    }

    ab2str(buf: arraybuffer): string {
        return string.fromcharcode.apply(null, new uint8array(buf));
    }

更具体地说,前端加密时的标签字段让我头疼。

一些旁注:在发送到后端之前将加密数据从 arraybuffer 转换为 int 数组并不是明智之举,这就是 base64 编码的用途:

    uint8ArrayToBase64(buf: Uint8Array): string {
        let binaryStr = Array.prototype.map.call(buf, function (ch) {
            return String.fromCharCode(ch);
        }).join('');
        return btoa(binaryStr);
    }
    ...
    const encrypted = await Crypto.encrypt(serverPublicKey, loginLabel, enteredPassword); // <<<================= encrypted is an ArrayBuffer
    const encryptedUint8Array = new Uint8Array(encrypted);
    const base64Encoded = uint8ArrayToBase64(encryptedUint8Array);
    // Now we're good to send the encrypted data to the backend
    ...

希望这能节省其他人的宝贵时间...干杯!

本篇关于《Golang rsa-oaep解密失败,前端使用webcrypto》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>