当前位置: 首页 > 知识库问答 >
问题:

Golang rsa-oaep解密失败,前端使用网络加密

仇正豪
2023-03-14

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

*后端*

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

    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

    null
    -#@#!#!%%% 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个答案

许远航
2023-03-14

好的,我的问题是客户端的arraybuffer到string和string到arraybuffer转换。由于后端以[]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 array不是一个明智的做法,这就是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
    ...

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

 类似资料:
  • 我使用的是Web加密,更具体地说,这些示例是:https://github.com/diafygi/webcrypto-examples/#rsa-oaep 更新

  • 我尝试在服务器上进行gpg加密/解密,对于加密,我使用以下命令行: 我想要找到原因:同一个用户有2个不同的密钥和1个秘密密钥。但现在又出现了一个问题:我删除了错误的键,并再次进行相同的测试。 解密后的答案是: 您需要一个密码短语来解锁用户的密钥:“Droli Mail_Adress”2048位RSA密钥,ID 6D2F1BE9,创建2017-07-19(主密钥ID 09C41BAC) 没有关于gp

  • 因此,这种特殊的异常非常常见,但我的问题与通常被问到的略有不同。 我有一个AES解密和加密函数,定义如下: 现在,如果我像这样执行单个解密: 字节数组输出很好。而如果我执行双重加密/解密: 我得到了著名的<code>javax.crypto。BadPaddingException:给定的最终块未正确填充异常。请注意,和只是整数(假设它们都是0)。目前,IVBytes只是一个大小为16的空字节数组,

  • 我正在尝试使用在我的设备上生成的RSA密钥解密我的android应用程序中的字符串。加密由php服务完成,使用我的应用程序提供的公共rsa密钥。我的问题是解密,解密失败了。 我正在做以下工作: 在用base64.encode(pubkey.getencoded())和私钥进行“base64”编码后,这两个密钥(公共和私有)都保存到文件中。->好 当我调用我的webservice时,我在post变量

  • 我对Docker很陌生,尝试用普通html构建Docker图像,但我有一条错误消息,说用前端dockerfile解决问题失败。v0:无法读取dockerfile:open/var/lib/docker/tmp/buildkit-mount602954594/dockerfile:没有这样的文件或目录 我的文件夹目录如下 在Dockerfile里面,我有 我做了我的命令docker构建。在目录C:\

  • 我有一个问题与ADFS身份验证,因为我升级了Spring启动版本从2.2.5。释放到2.5. x 在新版本中,我收到以下错误消息:未能解密EncryptedData 依赖性: SAML请求 重新分析:/ SAML请求: 西格尔:http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 2.vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv