singpass / myinfo-demo-app-v4

13 stars 8 forks source link

Issue on production. #1

Open aqshah20 opened 1 year ago

aqshah20 commented 1 year ago

How to create pem format from json for the production? I have keys in json format.

jwwb681232 commented 1 year ago

@aqshah20 我的方法是在app.js文件里写一个gen-jwksGET方法路由,然后在terminal中得到类似以下字符串

-----BEGIN EC PRIVATE KEY-----                                  
MHcCAQEEIFttQW8HLog4gPR90X6zUxvpqzIc+ATJNZbsfxFCJZ68oAoGCCqGSM49
AwEHoUQDQgAEAFXSiTqDjEHwwdgQRksLo3s+Mzwo/dr6OwAwtfCjFWbc2CaG0Kjw
Fp7N3wmP4b+kyuC5c/I4S25umND91FLRKg==                            
-----END EC PRIVATE KEY-----                                    

-----BEGIN EC PRIVATE KEY-----
MHcCAQEEINFBzXnzZj3moZ3JEgequtezB0Z1czKNHKfAjpXYi30GoAoGCCqGSM49
AwEHoUQDQgAEuSX/hH3tIIa2Hm29C28s4+pzCeQHS1PrKcJ0l1qHX/fc2sfqFZW8
sgquaRjctanK7hFxUUHBVAKe7OJ4TNlhHw==
-----END EC PRIVATE KEY-----

{"keys":[{"kty":"EC","kid":"inCo96FXYYPKC0e3eOWqunNAbkPhuQ6Oc1dJjlIUWXk","crv":"P-256","x":"AFXSiTqDjEHwwdgQRksLo3s-Mzwo_dr6OwAwtfCjFWY","y":"3NgmhtCo8Baezd8Jj-G_pMrguXPyOEtubpjQ_dRS0So","use":"sig","alg":"ES256"},{"kty":"EC","kid":"6qYAQ96uSN2eyx5P086PyFVxTV3lN
EzTRwKCODraMQw","crv":"P-256","x":"uSX_hH3tIIa2Hm29C28s4-pzCeQHS1PrKcJ0l1qHX_c","y":"3NrH6hWVvLIKrmkY3LWpyu4RcVFBwVQCnuzieEzZYR8","use":"enc","alg":"ECDH-ES+A256KW"}]}

以上字符串第一个区块为签名秘钥,第二个区块为加密秘钥。你需要将这两个区块分别存储为相应的pem文件。第三个区块为JWKS。你需要将第三个区块的内容放在公开可访问的URL地址里(Singpass后台的JWKS Endpoint)。

生成以上字符串的代码如下:

只需在terminal里运行npm start,然后浏览器访问http://localhost:3001/gen-jwks就可得到

app.get("/gen-jwks", function (req, res) {
  async function generateKey(){
    let key = crypto.generateKeyPairSync('ec', {
      namedCurve: 'prime256v1',
      publicKeyEncoding: {
        type: 'spki',
        format: 'pem',
      },
      privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem',
      },
    });
    let cryptoKey = await jose.JWK.asKey(key.privateKey, 'pem');
    console.log(cryptoKey.toPEM(true)); //!important
    return cryptoKey;
  }

  async function generateJwks() {
    //Creating Signing Key
    let signingKey = await generateKey();
    let publicSigningKeyJSON = signingKey.toJSON();

    //Creating Encryption Key
    let encryptionKey = await generateKey();
    let publicEncryptionKeyJSON = encryptionKey.toJSON();

    let jwks = {
      keys: [{...publicSigningKeyJSON,
        ...{use: 'sig'},
        ...{crv: 'P-256'},
        ...{alg: 'ES256'},
      },
        {...publicEncryptionKeyJSON,
          ...{use: 'enc'},
          ...{crv: 'P-256'},
          ...{alg: 'ECDH-ES+A256KW'},
        }]};

    console.log(JSON.stringify(jwks));
  }

  generateJwks();
});

注意

config/config.js 文件里的AUTHORIZE_JWKS_URLMYINFO_JWKS_URL请保持demo里的值不变