dter8514 2019-09-24 14:58
浏览 207

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

I have this app written in Golang as backend and Typescript as frontend. I need the transfered data to be encrypted so I choose RSA encryption, basically the steps are as follows:

* Backend *

  1. Golang generates private key and public key, save them in redis
  2. Golang converts the public key to JWK(json web key) using lestrrat-go/jwx/
  3. Golang sends the JWK

* Frontend *

  1. Typescript uses Webcrypto API to import JWK key
  2. Typescript uses the imported key to encrypt some plain text
  3. After encryption, I get an ArrayBuffer, in order to prevent any encoding issue, I then convert the ArrayBuffer byte to byte to an integer array
  4. Sending the converted integer array to backend inside a stringified JSON

* Backend *

  1. Golang receives the JSON and convert the integer array to []byte
  2. retrieve private key from redis and then decrypt

Now all I get is a decryption error...

Things I've checked:

  • Backend Golang alone encrypt/decrypt just fine
  • Frontend webcrypto alone encrypt/decrypt just fine
  • Check if anything went wrong during golang rsa.PublicKey -> JWK

    1. If the frontend gets the jwk from backend
    2. import it
    3. then export it
    4. send the exported key back to backend
    5. backend convert the jwk back to rsa public key, it equals to the public key saved in redis
  • After backend receives the int array and convert it to []byte, its length and content equals to that from frontend

Code as follows:


    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)
        });
    }

UPDATE

Adding some print log here:

  • Backend:

    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

  • Frontend:
    -#@#!#!%%% 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条回答 默认 最新

  • dragon_9000 2019-09-25 12:24
    关注

    Ok my problem is with the arraybuffer to string and string to arraybuffer conversion on the client side. Since the backend treats just about everything in []byte which is literally byte array, when doing the conversion at frontend, ALWAYS use Uint8Array instead of Uint16Array like the following:

        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));
        }
    

    To be more specific, it's the label field when doing encryption at frontend that's causing me all the headache.

    Some side notes: it isn't a smart move to convert the encrypted data from arraybuffer to int array before sending to the backend, that's what base64 encoding is for:

        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
        ...
    

    Hope this will save someone else's precious time... Cheers!

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题