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

时间:2019-09-24 14:58:24

标签: go rsa jwk webcrypto

我有这个用Golang编写的应用程序作为后端,而Typescript则作为前端。我需要对传输的数据进行加密,因此我选择RSA加密,基本上步骤如下:

*后端*

  1. Golang会生成私钥和公钥,并将其保存在redis中
  2. Golang使用lestrrat-go/jwx/
  3. 将公共密钥转换为JWK(json网络密钥)
  4. Golang发送JWK

*前端*

  1. Typescript使用Webcrypto API导入JWK密钥
  2. Typescript使用导入的密钥来加密一些纯文本
  3. 加密后,我得到一个ArrayBuffer,为了防止出现任何编码问题,然后将ArrayBuffer字节转换为一个整数数组
  4. 将转换后的整数数组发送到字符串化JSON内的后端

*后端*

  1. Golang接收JSON并将整数数组转换为[]byte
  2. 从redis检索私钥,然后解密

现在我得到的只是一个decryption error ...

我检查过的东西

  • 仅后端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]}

1 个答案:

答案 0 :(得分:0)

好吧,我的问题是在客户端将arraybuffer转换为字符串并将字符串转换为arraybuffer。由于后端几乎处理[]byte中的几乎所有字节数组,因此在前端进行转换时, ALWAYS 始终使用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
    ...

希望这可以节省别人的宝贵时间...干杯!