Пример #1
0
        public static JwsPacket Encapsulate(PrivKey key, string?kid, string nonce, string url, object?payload)
        {
            JwsKey jwk = CreateJwsKey(key.PublicKey, out string algName, out string signerName);

            JwsProtected protect = new JwsProtected()
            {
                alg   = algName,
                jwk   = kid._IsEmpty() ? jwk : null,
                kid   = kid._IsEmpty() ? null : kid,
                nonce = nonce,
                url   = url,
            };

            JwsPacket ret = new JwsPacket()
            {
                Protected = protect._ObjectToJson(base64url: true, includeNull: true),
                payload   = (payload == null ? "" : payload._ObjectToJson(base64url: true)),
            };

            var signer = key.GetSigner(signerName);

            byte[] signature = signer.Sign((ret.Protected + "." + ret.payload)._GetBytes_Ascii());

            ret.signature = signature._Base64UrlEncode();

            return(ret);
        }
Пример #2
0
        public static JwsKey CreateJwsKey(PubKey key, out string algName, out string signerName)
        {
            JwsKey jwk;

            switch (key.Algorithm)
            {
            case PkiAlgorithm.ECDSA:
                jwk = new JwsKey()
                {
                    kty = "EC",
                    crv = "P-" + key.BitsSize,
                    x   = key.EcdsaParameters.Q.AffineXCoord.GetEncoded()._Base64UrlEncode(),
                    y   = key.EcdsaParameters.Q.AffineYCoord.GetEncoded()._Base64UrlEncode(),
                };

                switch (key.BitsSize)
                {
                case 256:
                    algName    = "ES256";
                    signerName = "SHA-256withPLAIN-ECDSA";
                    break;

                case 384:
                    algName    = "ES384";
                    signerName = "SHA-384withPLAIN-ECDSA";
                    break;

                default:
                    throw new ArgumentException("Unsupported key length.");
                }

                break;

            case PkiAlgorithm.RSA:
                jwk = new JwsKey()
                {
                    kty = "RSA",
                    n   = key.RsaParameters.Modulus.ToByteArray()._Base64UrlEncode(),
                    e   = key.RsaParameters.Exponent.ToByteArray()._Base64UrlEncode(),
                };

                algName    = "RS256";
                signerName = PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id;
                break;

            default:
                throw new ArgumentException("Unsupported key.Algorithm.");
            }

            return(jwk);
        }