Пример #1
0
 public bool IsVerified(byte[] signature)
 {
     return(mSigner.VerifySignature(signature));
 }
Пример #2
0
        private bool VerifyDigest(
            byte[]                                  digest,
            AsymmetricKeyParameter key,
            byte[]                                  signature)
        {
            string algorithm = Helper.GetEncryptionAlgName(this.EncryptionAlgOid);

            try
            {
                if (algorithm.Equals("RSA"))
                {
                    IBufferedCipher c = CmsEnvelopedHelper.Instance.CreateAsymmetricCipher("RSA/ECB/PKCS1Padding");

                    c.Init(false, key);

                    byte[] decrypt = c.DoFinal(signature);

                    DigestInfo digInfo = DerDecode(decrypt);

                    if (!digInfo.AlgorithmID.ObjectID.Equals(digestAlgorithm.ObjectID))
                    {
                        return(false);
                    }

                    if (!IsNull(digInfo.AlgorithmID.Parameters))
                    {
                        return(false);
                    }

                    byte[] sigHash = digInfo.GetDigest();

                    return(Arrays.ConstantTimeAreEqual(digest, sigHash));
                }
                else if (algorithm.Equals("DSA"))
                {
                    ISigner sig = SignerUtilities.GetSigner("NONEwithDSA");

                    sig.Init(false, key);

                    sig.BlockUpdate(digest, 0, digest.Length);

                    return(sig.VerifySignature(signature));
                }
                else
                {
                    throw new CmsException("algorithm: " + algorithm + " not supported in base signatures.");
                }
            }
            catch (SecurityUtilityException e)
            {
                throw e;
            }
            catch (GeneralSecurityException e)
            {
                throw new CmsException("Exception processing signature: " + e, e);
            }
            catch (IOException e)
            {
                throw new CmsException("Exception decoding signature: " + e, e);
            }
        }
Пример #3
0
        // TODO Move this when other JCE tests are ported from Java

        /**
         * signature with a "forged signature" (sig block not at end of plain text)
         */
        private void doTestBadSig()        //PrivateKey priv, PublicKey pub)
        {
//			Signature           sig = Signature.getInstance("SHA1WithRSAEncryption", "BC");
            ISigner sig = SignerUtilities.GetSigner("SHA1WithRSAEncryption");
//			KeyPairGenerator    fact;
//			KeyPair             keyPair;
//			byte[]              data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

//			fact = KeyPairGenerator.getInstance("RSA", "BC");
            RsaKeyPairGenerator fact = new RsaKeyPairGenerator();

//			fact.initialize(768, new SecureRandom());
            RsaKeyGenerationParameters factParams = new RsaKeyGenerationParameters(
//				BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25);
                BigInteger.ValueOf(3), new SecureRandom(), 768, 25);

            fact.Init(factParams);

//			keyPair = fact.generateKeyPair();
//
//			PrivateKey  signingKey = keyPair.getPrivate();
//			PublicKey   verifyKey = keyPair.getPublic();
            IAsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();

            IAsymmetricKeyParameter priv = keyPair.Private;
            IAsymmetricKeyParameter pub  = keyPair.Public;

//			testBadSig(signingKey, verifyKey);



//			MessageDigest sha1 = MessageDigest.getInstance("SHA1", "BC");
            IDigest sha1 = DigestUtilities.GetDigest("SHA1");

//			Cipher signer = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
//			IBufferedCipher signer = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
            IAsymmetricBlockCipher signer = new Pkcs1Encoding(new RsaEngine());

//			signer.init(Cipher.ENCRYPT_MODE, priv);
            signer.Init(true, priv);

//			byte[] block = new byte[signer.getBlockSize()];
//			byte[] block = new byte[signer.GetBlockSize()];
            byte[] block = new byte[signer.GetInputBlockSize()];

//			sha1.update((byte)0);
            sha1.Update(0);

//			byte[] sigHeader = Hex.decode("3021300906052b0e03021a05000414");
            byte[] sigHeader = Hex.Decode("3021300906052b0e03021a05000414");
//			System.arraycopy(sigHeader, 0, block, 0, sigHeader.length);
            Array.Copy(sigHeader, 0, block, 0, sigHeader.Length);

//			sha1.digest(block, sigHeader.length, sha1.getDigestLength());
            sha1.DoFinal(block, sigHeader.Length);

//			System.arraycopy(sigHeader, 0, block,
//				sigHeader.length + sha1.getDigestLength(), sigHeader.length);
            Array.Copy(sigHeader, 0, block,
                       sigHeader.Length + sha1.GetDigestSize(), sigHeader.Length);

//			byte[] sigBytes = signer.doFinal(block);
            byte[] sigBytes = signer.ProcessBlock(block, 0, block.Length);

//			Signature verifier = Signature.getInstance("SHA1WithRSA", "BC");
            ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA");

//			verifier.initVerify(pub);
            verifier.Init(false, pub);

//			verifier.update((byte)0);
            verifier.Update(0);

//			if (verifier.verify(sig))
            if (verifier.VerifySignature(sigBytes))
            {
//				fail("bad signature passed");
                Fail("bad signature passed");
            }
        }
Пример #4
0
        public override void PerformTest()
        {
            ISigner sig = SignerUtilities.GetSigner("SHA1WithRSAEncryption");

            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            IAsymmetricCipherKeyPairGenerator fact = GeneratorUtilities.GetKeyPairGenerator("RSA");

            fact.Init(
                new RsaKeyGenerationParameters(
                    BigInteger.ValueOf(0x10001),
                    new SecureRandom(),
                    768,
                    25));

            AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();

            AsymmetricKeyParameter signingKey = keyPair.Private;
            AsymmetricKeyParameter verifyKey  = keyPair.Public;

            doTestBadSig(signingKey, verifyKey);

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA1 verification failed");
            }

            sig = SignerUtilities.GetSigner("MD2WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("MD2 verification failed");
            }

            sig = SignerUtilities.GetSigner("MD5WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("MD5 verification failed");
            }

            sig = SignerUtilities.GetSigner("RIPEMD160WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD160 verification failed");
            }

            //
            // RIPEMD-128
            //
            sig = SignerUtilities.GetSigner("RIPEMD128WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD128 verification failed");
            }

            //
            // RIPEMD256
            //
            sig = SignerUtilities.GetSigner("RIPEMD256WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD256 verification failed");
            }

            //
            // SHA-224
            //
            sig = SignerUtilities.GetSigner("SHA224WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA224 verification failed");
            }

            //
            // SHA-256
            //
            sig = SignerUtilities.GetSigner("SHA256WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA256 verification failed");
            }

            //
            // SHA-384
            //
            sig = SignerUtilities.GetSigner("SHA384WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA384 verification failed");
            }

            //
            // SHA-512
            //
            sig = SignerUtilities.GetSigner("SHA512WithRSAEncryption");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA512 verification failed");
            }

            //
            // ISO Sigs.
            //
            sig = SignerUtilities.GetSigner("MD5WithRSA/ISO9796-2");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("MD5/ISO verification failed");
            }

            sig = SignerUtilities.GetSigner("SHA1WithRSA/ISO9796-2");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("SHA1/ISO verification failed");
            }

            sig = SignerUtilities.GetSigner("RIPEMD160WithRSA/ISO9796-2");

            sig.Init(true, signingKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            sig.Init(false, verifyKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD160/ISO verification failed");
            }

            //
            // standard vector test - B.1.3 RIPEMD160, implicit.
            //
            BigInteger mod = new BigInteger("ffffffff78f6c55506c59785e871211ee120b0b5dd644aa796d82413a47b24573f1be5745b5cd9950f6b389b52350d4e01e90009669a8720bf265a2865994190a661dea3c7828e2e7ca1b19651adc2d5", 16);
            BigInteger pub = new BigInteger("03", 16);
            BigInteger pri = new BigInteger("2aaaaaaa942920e38120ee965168302fd0301d73a4e60c7143ceb0adf0bf30b9352f50e8b9e4ceedd65343b2179005b2f099915e4b0c37e41314bb0821ad8330d23cba7f589e0f129b04c46b67dfce9d", 16);

//			KeyFactory  f = KeyFactory.getInstance("RSA");
//			AsymmetricKeyParameter privKey = f.generatePrivate(new RSAPrivateKeySpec(mod, pri));
//			AsymmetricKeyParameter pubKey = f.generatePublic(new RSAPublicKeySpec(mod, pub));
            AsymmetricKeyParameter privKey = new RsaKeyParameters(true, mod, pri);
            AsymmetricKeyParameter pubKey  = new RsaKeyParameters(false, mod, pub);

            byte[] testSig = Hex.Decode("5cf9a01854dbacaec83aae8efc563d74538192e95466babacd361d7c86000fe42dcb4581e48e4feb862d04698da9203b1803b262105104d510b365ee9c660857ba1c001aa57abfd1c8de92e47c275cae");

            data = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");

            sig = SignerUtilities.GetSigner("RIPEMD160WithRSA/ISO9796-2");

            sig.Init(true, privKey);

            sig.BlockUpdate(data, 0, data.Length);

            sigBytes = sig.GenerateSignature();

            if (!AreEqual(testSig, sigBytes))
            {
                Fail("SigTest: failed ISO9796-2 generation Test");
            }

            sig.Init(false, pubKey);

            sig.BlockUpdate(data, 0, data.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("RIPEMD160/ISO verification failed");
            }
        }
        protected virtual void CheckSignature(
			IAsymmetricKeyParameter	publicKey,
			ISigner					signature)
        {
            if (!IsAlgIDEqual(c.SignatureAlgorithm, c.TbsCertificate.Signature))
                throw new CertificateException("signature algorithm in TBS cert not same as outer cert");

            Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;

            X509SignatureUtilities.SetSignatureParameters(signature, parameters);

            signature.Init(false, publicKey);

            byte[] b = this.GetTbsCertificate();
            signature.BlockUpdate(b, 0, b.Length);

            byte[] sig = this.GetSignature();
            if (!signature.VerifySignature(sig))
            {
                throw new InvalidKeyException("Public key presented not for certificate signature");
            }
        }
Пример #6
0
        protected override async Task OnOpenAsync(CancellationToken token)
        {
            this.Logger?.LogInformation($"Opening session channel with endpoint '{this.RemoteEndpoint.EndpointUrl}'.");
            this.Logger?.LogInformation($"SecurityPolicy: '{this.RemoteEndpoint.SecurityPolicyUri}'.");
            this.Logger?.LogInformation($"SecurityMode: '{this.RemoteEndpoint.SecurityMode}'.");
            this.Logger?.LogInformation($"UserIdentityToken: '{this.UserIdentity}'.");

            await base.OnOpenAsync(token).ConfigureAwait(false);

            token.ThrowIfCancellationRequested();

            // if SessionId is provided then we skip the CreateSessionRequest and go directly to (re)ActivateSession.
            // requires from previous Session: SessionId, AuthenticationToken, RemoteNonce
            if (this.SessionId == null)
            {
                var localNonce           = this.RemoteEndpoint.SecurityMode != MessageSecurityMode.None ? this.GetNextNonce(NonceLength) : null;
                var localCertificate     = this.RemoteEndpoint.SecurityMode != MessageSecurityMode.None ? this.LocalCertificate : null;
                var createSessionRequest = new CreateSessionRequest
                {
                    ClientDescription       = this.LocalDescription,
                    EndpointUrl             = this.RemoteEndpoint.EndpointUrl,
                    SessionName             = this.LocalDescription.ApplicationName,
                    ClientNonce             = localNonce,
                    ClientCertificate       = localCertificate,
                    RequestedSessionTimeout = this.SessionTimeout,
                    MaxResponseMessageSize  = this.RemoteMaxMessageSize
                };

                var createSessionResponse = await this.CreateSessionAsync(createSessionRequest).ConfigureAwait(false);

                this.SessionId           = createSessionResponse.SessionId;
                this.AuthenticationToken = createSessionResponse.AuthenticationToken;
                this.RemoteNonce         = createSessionResponse.ServerNonce;

                // verify the server's certificate is the same as the certificate from the selected endpoint.
                if (this.RemoteEndpoint.ServerCertificate != null && !this.RemoteEndpoint.ServerCertificate.SequenceEqual(createSessionResponse.ServerCertificate))
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Server did not return the same certificate used to create the channel.");
                }

                // verify the server's signature.
                ISigner verifier     = null;
                byte[]  dataToVerify = null;
                switch (this.RemoteEndpoint.SecurityPolicyUri)
                {
                case SecurityPolicyUris.Basic128Rsa15:
                case SecurityPolicyUris.Basic256:
                    dataToVerify = Concat(localCertificate, localNonce);
                    verifier     = SignerUtilities.GetSigner("SHA-1withRSA");
                    verifier.Init(false, this.RemotePublicKey);
                    verifier.BlockUpdate(dataToVerify, 0, dataToVerify.Length);
                    if (!verifier.VerifySignature(createSessionResponse.ServerSignature.Signature))
                    {
                        throw new ServiceResultException(StatusCodes.BadApplicationSignatureInvalid, "Server did not provide a correct signature for the nonce data provided by the client.");
                    }

                    break;

                case SecurityPolicyUris.Basic256Sha256:
                    dataToVerify = Concat(localCertificate, localNonce);
                    verifier     = SignerUtilities.GetSigner("SHA-256withRSA");
                    verifier.Init(false, this.RemotePublicKey);
                    verifier.BlockUpdate(dataToVerify, 0, dataToVerify.Length);
                    if (!verifier.VerifySignature(createSessionResponse.ServerSignature.Signature))
                    {
                        throw new ServiceResultException(StatusCodes.BadApplicationSignatureInvalid, "Server did not provide a correct signature for the nonce data provided by the client.");
                    }

                    break;

                default:
                    break;
                }
            }

            // create client signature
            SignatureData clientSignature = null;
            ISigner       signer          = null;

            byte[] dataToSign = null;
            switch (this.RemoteEndpoint.SecurityPolicyUri)
            {
            case SecurityPolicyUris.Basic128Rsa15:
            case SecurityPolicyUris.Basic256:
                dataToSign = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce);
                signer     = SignerUtilities.GetSigner("SHA-1withRSA");
                signer.Init(true, this.LocalPrivateKey);
                signer.BlockUpdate(dataToSign, 0, dataToSign.Length);
                clientSignature = new SignatureData
                {
                    Signature = signer.GenerateSignature(),
                    Algorithm = RsaSha1Signature,
                };

                break;

            case SecurityPolicyUris.Basic256Sha256:
                dataToSign = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce);
                signer     = SignerUtilities.GetSigner("SHA-256withRSA");
                signer.Init(true, this.LocalPrivateKey);
                signer.BlockUpdate(dataToSign, 0, dataToSign.Length);
                clientSignature = new SignatureData
                {
                    Signature = signer.GenerateSignature(),
                    Algorithm = RsaSha256Signature,
                };

                break;

            default:
                clientSignature = new SignatureData();
                break;
            }

            // supported UserIdentityToken types are AnonymousIdentityToken, UserNameIdentityToken, IssuedIdentityToken, X509IdentityToken
            UserIdentityToken identityToken  = null;
            SignatureData     tokenSignature = null;

            // if UserIdentity type is IssuedIdentity
            if (this.UserIdentity is IssuedIdentity)
            {
                var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.IssuedToken);
                if (tokenPolicy == null)
                {
                    throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                }

                var    issuedIdentity = (IssuedIdentity)this.UserIdentity;
                byte[] plainText      = Concat(issuedIdentity.TokenData, this.RemoteNonce);
                var    secPolicyUri   = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri;
                switch (secPolicyUri)
                {
                case SecurityPolicyUris.Basic128Rsa15:
                    identityToken = new IssuedIdentityToken
                    {
                        TokenData           = this.RemotePublicKey.EncryptTokenData(plainText, secPolicyUri),
                        EncryptionAlgorithm = RsaV15KeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                case SecurityPolicyUris.Basic256:
                case SecurityPolicyUris.Basic256Sha256:
                    identityToken = new IssuedIdentityToken
                    {
                        TokenData           = this.RemotePublicKey.EncryptTokenData(plainText, secPolicyUri),
                        EncryptionAlgorithm = RsaOaepKeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                default:
                    identityToken = new IssuedIdentityToken
                    {
                        TokenData           = issuedIdentity.TokenData,
                        EncryptionAlgorithm = null,
                        PolicyId            = tokenPolicy.PolicyId
                    };
                    break;
                }

                tokenSignature = new SignatureData();
            }

            // if UserIdentity type is X509Identity
            else if (this.UserIdentity is X509Identity)
            {
                throw new NotImplementedException("A user identity of X509Identity is not implemented.");

                /*
                 * var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.Certificate);
                 * if (tokenPolicy == null)
                 * {
                 *  throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                 * }
                 *
                 * var x509Identity = (X509Identity)this.UserIdentity;
                 * identityToken = new X509IdentityToken { CertificateData = x509Identity.Certificate?.RawData, PolicyId = tokenPolicy.PolicyId };
                 * var secPolicyUri = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri;
                 * switch (secPolicyUri)
                 * {
                 *  case SecurityPolicyUris.Basic128Rsa15:
                 *  case SecurityPolicyUris.Basic256:
                 *      var asymSigningKey = x509Identity.Certificate?.GetRSAPrivateKey();
                 *      if (asymSigningKey != null)
                 *      {
                 *          dataToSign = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce);
                 *          tokenSignature = new SignatureData
                 *          {
                 *              Signature = asymSigningKey.SignData(dataToSign, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1),
                 *              Algorithm = RsaSha1Signature,
                 *          };
                 *          break;
                 *      }
                 *
                 *      tokenSignature = new SignatureData();
                 *      break;
                 *
                 *  case SecurityPolicyUris.Basic256Sha256:
                 *      var asymSigningKey256 = x509Identity.Certificate?.GetRSAPrivateKey();
                 *      if (asymSigningKey256 != null)
                 *      {
                 *          dataToSign = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce);
                 *          tokenSignature = new SignatureData
                 *          {
                 *              Signature = asymSigningKey256.SignData(dataToSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1),
                 *              Algorithm = RsaSha256Signature,
                 *          };
                 *          break;
                 *      }
                 *
                 *      tokenSignature = new SignatureData();
                 *      break;
                 *
                 *  default:
                 *      tokenSignature = new SignatureData();
                 *      break;
                 * }
                 */
            }

            // if UserIdentity type is UserNameIdentity
            else if (this.UserIdentity is UserNameIdentity)
            {
                var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.UserName);
                if (tokenPolicy == null)
                {
                    throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                }

                var    userNameIdentity = (UserNameIdentity)this.UserIdentity;
                byte[] plainText        = Concat(System.Text.Encoding.UTF8.GetBytes(userNameIdentity.Password), this.RemoteNonce);
                var    secPolicyUri     = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri;
                switch (secPolicyUri)
                {
                case SecurityPolicyUris.Basic128Rsa15:
                    identityToken = new UserNameIdentityToken
                    {
                        UserName            = userNameIdentity.UserName,
                        Password            = this.RemotePublicKey.EncryptTokenData(plainText, secPolicyUri),
                        EncryptionAlgorithm = RsaV15KeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                case SecurityPolicyUris.Basic256:
                case SecurityPolicyUris.Basic256Sha256:
                    identityToken = new UserNameIdentityToken
                    {
                        UserName            = userNameIdentity.UserName,
                        Password            = this.RemotePublicKey.EncryptTokenData(plainText, secPolicyUri),
                        EncryptionAlgorithm = RsaOaepKeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                default:
                    identityToken = new UserNameIdentityToken
                    {
                        UserName            = userNameIdentity.UserName,
                        Password            = System.Text.Encoding.UTF8.GetBytes(userNameIdentity.Password),
                        EncryptionAlgorithm = null,
                        PolicyId            = tokenPolicy.PolicyId
                    };
                    break;
                }

                tokenSignature = new SignatureData();
            }

            // if UserIdentity type is AnonymousIdentity or null
            else
            {
                var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.Anonymous);
                if (tokenPolicy == null)
                {
                    throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                }

                identityToken = new AnonymousIdentityToken {
                    PolicyId = tokenPolicy.PolicyId
                };
                tokenSignature = new SignatureData();
            }

            var activateSessionRequest = new ActivateSessionRequest
            {
                ClientSignature    = clientSignature,
                LocaleIds          = new[] { CultureInfo.CurrentUICulture.TwoLetterISOLanguageName },
                UserIdentityToken  = identityToken,
                UserTokenSignature = tokenSignature
            };
            var activateSessionResponse = await this.ActivateSessionAsync(activateSessionRequest).ConfigureAwait(false);

            this.RemoteNonce = activateSessionResponse.ServerNonce;

            // fetch namespace array, etc.
            var readValueIds = new ReadValueId[]
            {
                new ReadValueId
                {
                    NodeId      = NodeId.Parse(VariableIds.Server_NamespaceArray),
                    AttributeId = AttributeIds.Value
                },
                new ReadValueId
                {
                    NodeId      = NodeId.Parse(VariableIds.Server_ServerArray),
                    AttributeId = AttributeIds.Value
                }
            };
            var readRequest = new ReadRequest
            {
                NodesToRead = readValueIds
            };

            var readResponse = await this.ReadAsync(readRequest).ConfigureAwait(false);

            if (readResponse.Results.Length == 2)
            {
                if (StatusCode.IsGood(readResponse.Results[0].StatusCode))
                {
                    this.NamespaceUris.Clear();
                    this.NamespaceUris.AddRange(readResponse.Results[0].GetValueOrDefault <string[]>());
                }

                if (StatusCode.IsGood(readResponse.Results[1].StatusCode))
                {
                    this.ServerUris.Clear();
                    this.ServerUris.AddRange(readResponse.Results[1].GetValueOrDefault <string[]>());
                }
            }
        }
Пример #7
0
        public void doTestECDsa(
            string name)
        {
//			ECGenParameterSpec ecSpec = new ECGenParameterSpec(name);
            ECDomainParameters ecSpec = GetCurveParameters(name);

            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

//			g.initialize(ecSpec, new SecureRandom());
            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            ISigner sgr = SignerUtilities.GetSigner("ECDSA");
            AsymmetricCipherKeyPair pair = g.GenerateKeyPair();
            AsymmetricKeyParameter  sKey = pair.Private;
            AsymmetricKeyParameter  vKey = pair.Public;

            sgr.Init(true, sKey);

            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail(name + " verification failed");
            }

            //
            // public key encoding test
            //
//			byte[]              pubEnc = vKey.getEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded();

//			KeyFactory          keyFac = KeyFactory.getInstance("ECDH");
//			X509EncodedKeySpec  pubX509 = new X509EncodedKeySpec(pubEnc);
//			ECPublicKey         pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
            ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc);

//			if (!pubKey.getW().Equals(((ECPublicKey)vKey).getW()))
            if (!pubKey.Q.Equals(((ECPublicKeyParameters)vKey).Q))
            {
                Fail("public key encoding (Q test) failed");
            }

            // TODO Put back in?
//			if (!(pubKey.Parameters is ECNamedCurveSpec))
//			{
//				Fail("public key encoding not named curve");
//			}

            //
            // private key encoding test
            //
//			byte[]              privEnc = sKey.getEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded();

//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			ECPrivateKey        privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
            ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc);

//			if (!privKey.getS().Equals(((ECPrivateKey)sKey).getS()))
            if (!privKey.D.Equals(((ECPrivateKeyParameters)sKey).D))
            {
                Fail("private key encoding (D test) failed");
            }

            // TODO Put back in?
//			if (!(privKey.Parameters is ECNamedCurveSpec))
//			{
//				Fail("private key encoding not named curve");
//			}
//
//			ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams();
//			if (!privSpec.GetName().EqualsIgnoreCase(name)
//				&& !privSpec.GetName().EqualsIgnoreCase((string) CurveAliases[name]))
//			{
//				Fail("private key encoding wrong named curve. Expected: " + name + " got " + privSpec.GetName());
//			}
        }
Пример #8
0
		private void processDHEKeyExchange(
			MemoryStream	inStr,
			ISigner			signer)
		{
			Stream sigIn = inStr;
			if (signer != null)
			{
				signer.Init(false, this.serverPublicKey);
				signer.BlockUpdate(this.clientRandom, 0, this.clientRandom.Length);
				signer.BlockUpdate(this.serverRandom, 0, this.serverRandom.Length);

				sigIn = new SignerStream(inStr, signer, null);
			}

			/*
			* Parse the Structure
			*/
			byte[] pByte = TlsUtilities.ReadOpaque16(sigIn);
			byte[] gByte = TlsUtilities.ReadOpaque16(sigIn);
			byte[] YsByte = TlsUtilities.ReadOpaque16(sigIn);

			if (signer != null)
			{
				byte[] sigByte = TlsUtilities.ReadOpaque16(sigIn);

				/*
				* Verify the Signature.
				*/
				if (!signer.VerifySignature(sigByte))
				{
					this.FailWithError(AL_fatal, AP_bad_certificate);
				}
			}

			this.AssertEmpty(inStr);

			/*
			* Do the DH calculation.
			*/
			BigInteger p = new BigInteger(1, pByte);
			BigInteger g = new BigInteger(1, gByte);
			BigInteger Ys = new BigInteger(1, YsByte);

			/*
			* Check the DH parameter values
			*/
			if (!p.IsProbablePrime(10))
			{
				this.FailWithError(AL_fatal, AP_illegal_parameter);
			}
			if (g.CompareTo(BigInteger.Two) < 0 || g.CompareTo(p.Subtract(BigInteger.Two)) > 0)
			{
				this.FailWithError(AL_fatal, AP_illegal_parameter);
			}
			// TODO For static DH public values, see additional checks in RFC 2631 2.1.5 
			if (Ys.CompareTo(BigInteger.Two) < 0 || Ys.CompareTo(p.Subtract(BigInteger.One)) > 0)
			{
				this.FailWithError(AL_fatal, AP_illegal_parameter);
			}

			/*
			* Diffie-Hellman basic key agreement
			*/
			DHParameters dhParams = new DHParameters(p, g);

			// Generate a keypair
			DHBasicKeyPairGenerator dhGen = new DHBasicKeyPairGenerator();
			dhGen.Init(new DHKeyGenerationParameters(random, dhParams));

			AsymmetricCipherKeyPair dhPair = dhGen.GenerateKeyPair();

			// Store the public value to send to server
			this.Yc = ((DHPublicKeyParameters)dhPair.Public).Y;

			// Calculate the shared secret
			DHBasicAgreement dhAgree = new DHBasicAgreement();
			dhAgree.Init(dhPair.Private);

			BigInteger agreement = dhAgree.CalculateAgreement(new DHPublicKeyParameters(Ys, dhParams));

			this.pms = BigIntegers.AsUnsignedByteArray(agreement);
		}
        /// <summary>
        ///     Verify signed bytes and signature.
        /// </summary>
        /// <param name="signedBytes">signed bytes</param>
        /// <param name="signatureBytes">signature bytes</param>
        /// <param name="data">must include certificate bytes</param>
        public void Verify(byte[] signedBytes, byte[] signatureBytes, CryptoSignatureVerificationData data)
        {
            if (signedBytes == null)
            {
                throw new ArgumentNullException(nameof(signedBytes));
            }

            if (signatureBytes == null)
            {
                throw new ArgumentNullException(nameof(signatureBytes));
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            byte[] certificateBytes = data.CertificateBytes;

            if (certificateBytes == null)
            {
                throw new PkiVerificationErrorException("Certificate in data parameter cannot be null.");
            }

            X509Certificate certificate;

            try
            {
                certificate = new X509CertificateParser().ReadCertificate(certificateBytes);
            }
            catch (Exception e)
            {
                throw new PkiVerificationErrorException("Could not create certificate from given bytes.", e);
            }

            if (certificate == null)
            {
                throw new PkiVerificationErrorException("Could not create certificate from given bytes.");
            }

            CertificateTimeVerifier.Verify(certificate, data.SignTime);

            try
            {
                ISigner signer = SignerUtilities.GetSigner(_algorithm + "withRSA");
                signer.Init(false, certificate.GetPublicKey());
                signer.BlockUpdate(signedBytes, 0, signedBytes.Length);

                if (!signer.VerifySignature(signatureBytes))
                {
                    throw new PkiVerificationFailedException("Failed to verify RSA signature.");
                }
            }
            catch (PkiVerificationFailedException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new PkiVerificationErrorException("Error when verifying RSA signature.", e);
            }
        }
Пример #10
0
        private bool DoVerify(
            AsymmetricKeyParameter key,
            Asn1.Cms.AttributeTable signedAttrTable)
        {
            string digestName    = Helper.GetDigestAlgName(this.DigestAlgOid);
            string signatureName = digestName + "with"
                                   + Helper.GetEncryptionAlgName(this.EncryptionAlgOid);
            ISigner sig    = Helper.GetSignatureInstance(signatureName);
            IDigest digest = Helper.GetDigestInstance(digestName);

            try
            {
                sig.Init(false, key);

                if (signedAttributes == null)
                {
                    if (content != null)
                    {
                        content.Write(new CmsSignedDataGenerator.SigOutputStream(sig));
                        content.Write(new CmsSignedDataGenerator.DigOutputStream(digest));

                        _resultDigest = DigestUtilities.DoFinal(digest);
                    }
                    else
                    {
                        _resultDigest = _digest;

                        // need to decrypt signature and check message bytes
                        return(VerifyDigest(_digest, key, this.GetSignature()));
                    }
                }
                else
                {
                    byte[] hash;
                    if (content != null)
                    {
                        content.Write(
                            new CmsSignedDataGenerator.DigOutputStream(digest));

                        hash = DigestUtilities.DoFinal(digest);
                    }
                    else
                    {
                        hash = _digest;
                    }

                    _resultDigest = hash;

                    Asn1.Cms.Attribute dig  = signedAttrTable[Asn1.Cms.CmsAttributes.MessageDigest];
                    Asn1.Cms.Attribute type = signedAttrTable[Asn1.Cms.CmsAttributes.ContentType];

                    if (dig == null)
                    {
                        throw new SignatureException("no hash for content found in signed attributes");
                    }

                    if (type == null)
                    {
                        throw new SignatureException("no content type id found in signed attributes");
                    }

                    Asn1Object hashObj = dig.AttrValues[0].ToAsn1Object();

                    if (hashObj is Asn1OctetString)
                    {
                        byte[] signedHash = ((Asn1OctetString)hashObj).GetOctets();

                        if (!Arrays.AreEqual(hash, signedHash))
                        {
                            throw new SignatureException("content hash found in signed attributes different");
                        }
                    }
                    else if (hashObj is DerNull)
                    {
                        if (hash != null)
                        {
                            throw new SignatureException("NULL hash found in signed attributes when one expected");
                        }
                    }

                    DerObjectIdentifier typeOID = (DerObjectIdentifier)type.AttrValues[0];

                    if (!typeOID.Equals(contentType))
                    {
                        throw new SignatureException("contentType in signed attributes different");
                    }

                    {
                        byte[] tmp = this.GetEncodedSignedAttributes();
                        sig.BlockUpdate(tmp, 0, tmp.Length);
                    }
                }

                return(sig.VerifySignature(this.GetSignature()));
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException(
                          "key not appropriate to signature in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException(
                          "can't process mime object to create signature.", e);
            }
            catch (SignatureException e)
            {
                throw new CmsException(
                          "invalid signature format in message: " + e.Message, e);
            }
        }
Пример #11
0
        public void TestDsa2Parameters()
        {
            byte[] seed = Hex.Decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0");

            //AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC");
            //a.init(2048, new DSATestSecureRandom(seed));
            DsaParametersGenerator a = new DsaParametersGenerator(new Sha256Digest());

            a.Init(new DsaParameterGenerationParameters(2048, 256, 80, new DsaTestSecureRandom(seed)));

            //AlgorithmParameters parameters = a.generateParameters();

            //DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(DSAParameterSpec.class);
            DsaParameters dsaP = a.GenerateParameters();

            if (!dsaP.Q.Equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16)))
            {
                Fail("Q incorrect");
            }

            if (!dsaP.P.Equals(new BigInteger(
                                   "F56C2A7D366E3EBDEAA1891FD2A0D099" +
                                   "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" +
                                   "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" +
                                   "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" +
                                   "5909132627F51A0C866877E672E555342BDF9355347DBD43" +
                                   "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" +
                                   "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" +
                                   "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" +
                                   "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" +
                                   "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" +
                                   "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16)))
            {
                Fail("P incorrect");
            }

            if (!dsaP.G.Equals(new BigInteger(
                                   "8DC6CC814CAE4A1C05A3E186A6FE27EA" +
                                   "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" +
                                   "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" +
                                   "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" +
                                   "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" +
                                   "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" +
                                   "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" +
                                   "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" +
                                   "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" +
                                   "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" +
                                   "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16)))
            {
                Fail("G incorrect");
            }

            //KeyPairGenerator    g = KeyPairGenerator.getInstance("DSA", "BC");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

            //g.initialize(dsaP, FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")));
            g.Init(new DsaKeyGenerationParameters(FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")), dsaP));
            //KeyPair p = g.generateKeyPair();
            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            //DSAPrivateKey  sKey = (DSAPrivateKey)p.getPrivate();
            //DSAPublicKey   vKey = (DSAPublicKey)p.getPublic();
            DsaPrivateKeyParameters sKey = (DsaPrivateKeyParameters)p.Private;
            DsaPublicKeyParameters  vKey = (DsaPublicKeyParameters)p.Public;

            if (!vKey.Y.Equals(new BigInteger(
                                   "2828003D7C747199143C370FDD07A286" +
                                   "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" +
                                   "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" +
                                   "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" +
                                   "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" +
                                   "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" +
                                   "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" +
                                   "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" +
                                   "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" +
                                   "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" +
                                   "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16)))
            {
                Fail("Y value incorrect");
            }

            if (!sKey.X.Equals(
                    new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16)))
            {
                Fail("X value incorrect");
            }

            //byte[] encodeParams = parameters.getEncoded();
            byte[] encodeParams = new DsaParameter(dsaP.P, dsaP.Q, dsaP.G).GetDerEncoded();

            //AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC");
            //a2.init(encodeParams);
            DsaParameter  dsaP2 = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams));
            DsaParameters p2    = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G);

            // a and a2 should be equivalent!
            //byte[] encodeParams_2 = a2.GetEncoded();
            byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded();

            if (!AreEqual(encodeParams, encodeParams_2))
            {
                Fail("encode/decode parameters failed");
            }

            ISigner s = SignerUtilities.GetSigner("DSA");

            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }
        }
Пример #12
0
        public void TestParameters()
        {
//			AlgorithmParameterGenerator a = AlgorithmParameterGenerator.GetInstance("DSA");
//			a.init(512, random);
            DsaParametersGenerator a = new DsaParametersGenerator();

            a.Init(512, 20, random);

//			AlgorithmParameters parameters = a.generateParameters();
            DsaParameters p = a.GenerateParameters();

//			byte[] encodeParams = parameters.GetEncoded();
            byte[] encodeParams = new DsaParameter(p.P, p.Q, p.G).GetDerEncoded();

//			AlgorithmParameters a2 = AlgorithmParameters.GetInstance("DSA");
//			a2.init(encodeParams);
            DsaParameter  dsaP = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams));
            DsaParameters p2   = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G);

            // a and a2 should be equivalent!
//			byte[] encodeParams_2 = a2.GetEncoded();
            byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded();

            if (!AreEqual(encodeParams, encodeParams_2))
            {
                Fail("encode/Decode parameters failed");
            }

//			DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(typeof(DSAParameterSpec));

//			KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

//			g.initialize(dsaP, new SecureRandom());
            g.Init(new DsaKeyGenerationParameters(new SecureRandom(), p));
//			KeyPair p = g.generateKeyPair();
            AsymmetricCipherKeyPair pair = g.GenerateKeyPair();

//			PrivateKey sKey = p.Private;
//			PublicKey vKey = p.Public;
            AsymmetricKeyParameter sKey = pair.Private;
            AsymmetricKeyParameter vKey = pair.Public;

            ISigner s = SignerUtilities.GetSigner("DSA");

            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }
        }
Пример #13
0
        public void TestGeneration()
        {
            ISigner s = SignerUtilities.GetSigner("DSA");

            byte[]       data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            SecureRandom rand = new SecureRandom();

            // KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

            // test exception
            //

            doTestBadStrength(513);
            doTestBadStrength(510);
            doTestBadStrength(1025);

            //g.initialize(512, rand);
            {
                DsaParametersGenerator pGen = new DsaParametersGenerator();
                pGen.Init(512, 80, rand);

                g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters()));
            }

            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            AsymmetricKeyParameter sKey = p.Private;
            AsymmetricKeyParameter vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }



            //
            // ECDSA Fp generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

            ECCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),         // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16));        // b

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"));     // n

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }

            //
            // ECDSA F2m generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

            curve = new F2mCurve(
                239,                                                                                 // m
                36,                                                                                  // k
                new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16),  // a
                new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b

            ecSpec = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G
                new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"),                                                                  // n
                BigInteger.ValueOf(4));                                                                                                                                      // h

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }
        }
Пример #14
0
        public void TestECDsa239BitPrime()
        {
            BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176");
            BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783");

            byte[] kData = BigIntegers.AsUnsignedByteArray(
                new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655"));

            SecureRandom k = FixedSecureRandom.From(kData);

            ECCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),         // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),                 // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16));                // b

            ECDomainParameters spec = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")),             // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"));                 // n

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"),                 // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")),                 // Q
                spec);

            ISigner sgr = SignerUtilities.GetSigner("ECDSA");

//			KeyFactory f = KeyFactory.GetInstance("ECDSA");
//			PrivateKey sKey = f.generatePrivate(priKey);
//			PublicKey vKey = f.generatePublic(pubKey);
            AsymmetricKeyParameter sKey = priKey;
            AsymmetricKeyParameter vKey = pubKey;

            sgr.Init(true, new ParametersWithRandom(sKey, k));

            byte[] message = Encoding.ASCII.GetBytes("abc");

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail("239 Bit EC verification failed");
            }

            BigInteger[] sig = DerDecode(sigBytes);

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + SimpleTest.NewLine
                     + " expecting: " + r + SimpleTest.NewLine
                     + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + SimpleTest.NewLine
                     + " expecting: " + s + SimpleTest.NewLine
                     + " got      : " + sig[1]);
            }
        }
Пример #15
0
        public void TestAlgorithms()
        {
            //
            // RSA parameters
            //
            BigInteger rsaMod    = new BigInteger("a7295693155b1813bb84877fb45343556e0568043de5910872a3a518cc11e23e2db74eaf4545068c4e3d258a2718fbacdcc3eafa457695b957e88fbf110aed049a992d9c430232d02f3529c67a3419935ea9b569f85b1bcd37de6b899cd62697e843130ff0529d09c97d813cb15f293751ff56f943fbdabb63971cc7f4f6d5bff1594416b1f5907bde5a84a44f9802ef29b43bda1960f948f8afb8766c1ab80d32eec88ed66d0b65aebe44a6d0b3c5e0ab051aaa1b912fbcc17b8e751ddecc5365b6db6dab0020c3057db4013a51213a5798a3aab67985b0f4d88627a54a0f3f0285fbcb4afdfeb65cb153af66825656d43238b75503231500753f4e421e3c57", 16);
            BigInteger rsaPubExp = new BigInteger("10001", 16);

            BigInteger rsaPrivExp  = new BigInteger("65dad56ac7df7abb434e4cb5eeadb16093aa6da7f0033aad3815289b04757d32bfee6ade7749c8e4a323b5050a2fb9e2a99e23469e1ed4ba5bab54336af20a5bfccb8b3424cc6923db2ffca5787ed87aa87aa614cd04cedaebc8f623a2d2063017910f436dff18bb06f01758610787f8b258f0a8efd8bd7de30007c47b2a1031696c7d6523bc191d4d918927a7e0b09584ed205bd2ff4fc4382678df82353f7532b3bbb81d69e3f39070aed3fb64fce032a089e8e64955afa5213a6eb241231bd98d702fba725a9b205952fda186412d9e0d9344d2998c455ad8c2bae85ee672751466d5288304032b5b7e02f7e558c7af82c7fbf58eea0bb4ef0f001e6cd0a9", 16);
            BigInteger rsaPrivP    = new BigInteger("d4fd9ac3474fb83aaf832470643609659e511b322632b239b688f3cd2aad87527d6cf652fb9c9ca67940e84789444f2e99b0cb0cfabbd4de95396106c865f38e2fb7b82b231260a94df0e01756bf73ce0386868d9c41645560a81af2f53c18e4f7cdf3d51d80267372e6e0216afbf67f655c9450769cca494e4f6631b239ce1b", 16);
            BigInteger rsaPrivQ    = new BigInteger("c8eaa0e2a1b3a4412a702bccda93f4d150da60d736c99c7c566fdea4dd1b401cbc0d8c063daaf0b579953d36343aa18b33dbf8b9eae94452490cc905245f8f7b9e29b1a288bc66731a29e1dd1a45c9fd7f8238ff727adc49fff73991d0dc096206b9d3a08f61e7462e2b804d78cb8c5eccdb9b7fbd2ad6a8fea46c1053e1be75", 16);
            BigInteger rsaPrivDP   = new BigInteger("10edcb544421c0f9e123624d1099feeb35c72a8b34e008ac6fa6b90210a7543f293af4e5299c8c12eb464e70092805c7256e18e5823455ba0f504d36f5ccacac1b7cd5c58ff710f9c3f92646949d88fdd1e7ea5fed1081820bb9b0d2a8cd4b093fecfdb96dabd6e28c3a6f8c186dc86cddc89afd3e403e0fcf8a9e0bcb27af0b", 16);
            BigInteger rsaPrivDQ   = new BigInteger("97fc25484b5a415eaa63c03e6efa8dafe9a1c8b004d9ee6e80548fefd6f2ce44ee5cb117e77e70285798f57d137566ce8ea4503b13e0f1b5ed5ca6942537c4aa96b2a395782a4cb5b58d0936e0b0fa63b1192954d39ced176d71ef32c6f42c84e2e19f9d4dd999c2151b032b97bd22aa73fd8c5bcd15a2dca4046d5acc997021", 16);
            BigInteger rsaPrivQinv = new BigInteger("4bb8064e1eff7e9efc3c4578fcedb59ca4aef0993a8312dfdcb1b3decf458aa6650d3d0866f143cbf0d3825e9381181170a0a1651eefcd7def786b8eb356555d9fa07c85b5f5cbdd74382f1129b5e36b4166b6cc9157923699708648212c484958351fdc9cf14f218dbe7fbf7cbd93a209a4681fe23ceb44bab67d66f45d1c9d", 16);

            RsaKeyParameters           rsaPublic  = new RsaKeyParameters(false, rsaMod, rsaPubExp);
            RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(
                rsaMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv);

            //
            // ECDSA parameters
            //
            BigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv"));
            BigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R"));
            BigInteger ECParraH  = new BigInteger(Base64.Decode("AQ=="));
            BigInteger ECParraN  = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L"));
            BigInteger ECPubQX   = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l"));
            BigInteger ECPubQY   = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx"));
            BigInteger ECPrivD   = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo"));

            FpCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),         // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),                 // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16));                // b

            ECDomainParameters ecDomain = new ECDomainParameters(curve,
                                                                 new FpPoint(curve,
                                                                             curve.FromBigInteger(ECParraGX),
                                                                             curve.FromBigInteger(ECParraGY)),
                                                                 ECParraN);

            ECPublicKeyParameters ecPub = new ECPublicKeyParameters(
                new FpPoint(curve,
                            curve.FromBigInteger(ECPubQX),
                            curve.FromBigInteger(ECPubQY)),
                ecDomain);

            ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters(ECPrivD, ecDomain);

            //
            // DSA parameters
            //
            BigInteger DSAParaG    = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            BigInteger DSAParaP    = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            BigInteger DSAParaQ    = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            BigInteger DSAPublicY  = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            BigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters           para    = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters  dsaPub  = new DsaPublicKeyParameters(DSAPublicY, para);

            //
            // ECGOST3410 parameters
            //
            IAsymmetricCipherKeyPairGenerator ecGostKpg = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");

            ecGostKpg.Init(
                new ECKeyGenerationParameters(
                    CryptoProObjectIdentifiers.GostR3410x2001CryptoProA,
                    new SecureRandom()));

            AsymmetricCipherKeyPair ecGostPair = ecGostKpg.GenerateKeyPair();

            //
            // GOST3410 parameters
            //
            IAsymmetricCipherKeyPairGenerator gostKpg = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            gostKpg.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            AsymmetricCipherKeyPair gostPair = gostKpg.GenerateKeyPair();



            //
            // signer loop
            //
            byte[] shortMsg = new byte[] { 1, 4, 5, 6, 8, 8, 4, 2, 1, 3 };
            byte[] longMsg  = new byte[100];
            new SecureRandom().NextBytes(longMsg);

            foreach (string algorithm in SignerUtilities.Algorithms)
            {
                ISigner signer = SignerUtilities.GetSigner(algorithm);

                string upper   = algorithm.ToUpper(CultureInfo.InvariantCulture);
                int    withPos = upper.LastIndexOf("WITH");

                string cipherName = withPos < 0
                                        ?       upper
                                        :       upper.Substring(withPos + "WITH".Length);

                ICipherParameters signParams = null, verifyParams = null;

                if (cipherName == "RSA" || cipherName == "RSAANDMGF1")
                {
                    signParams   = rsaPrivate;
                    verifyParams = rsaPublic;
                }
                else if (cipherName == "ECDSA")
                {
                    signParams   = ecPriv;
                    verifyParams = ecPub;
                }
                else if (cipherName == "DSA")
                {
                    signParams   = dsaPriv;
                    verifyParams = dsaPub;
                }
                else if (cipherName == "ECGOST3410")
                {
                    signParams   = ecGostPair.Private;
                    verifyParams = ecGostPair.Public;
                }
                else if (cipherName == "GOST3410")
                {
                    signParams   = gostPair.Private;
                    verifyParams = gostPair.Public;
                }
                else
                {
                    Assert.Fail("Unknown algorithm encountered: " + cipherName);
                }

                signer.Init(true, signParams);
                foreach (byte b in shortMsg)
                {
                    signer.Update(b);
                }
                signer.BlockUpdate(longMsg, 0, longMsg.Length);
                byte[] sig = signer.GenerateSignature();

                signer.Init(false, verifyParams);
                foreach (byte b in shortMsg)
                {
                    signer.Update(b);
                }
                signer.BlockUpdate(longMsg, 0, longMsg.Length);

                Assert.IsTrue(signer.VerifySignature(sig), cipherName + " signer " + algorithm + " failed.");
            }
        }
Пример #16
0
        public void TestECDsa239BitBinary()
        {
            BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552");
            BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174");

            byte[] kData = BigIntegers.AsUnsignedByteArray(
                new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363"));

            SecureRandom k = FixedSecureRandom.From(kData);

            ECCurve curve = new F2mCurve(
                239,                                                                                 // m
                36,                                                                                  // k
                new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16),  // a
                new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G
                new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"),                                                                  // n
                BigInteger.ValueOf(4));                                                                                                                                      // h

            ECPrivateKeyParameters sKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"),                 // d
                parameters);

            ECPublicKeyParameters vKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")),                 // Q
                parameters);

            ISigner sgr = SignerUtilities.GetSigner("ECDSA");

            byte[] message = Encoding.ASCII.GetBytes("abc");

            sgr.Init(true, new ParametersWithRandom(sKey, k));

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail("239 Bit EC verification failed");
            }

            BigInteger[] sig = DerDecode(sigBytes);

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + SimpleTest.NewLine
                     + " expecting: " + r + SimpleTest.NewLine
                     + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + SimpleTest.NewLine
                     + " expecting: " + s + SimpleTest.NewLine
                     + " got      : " + sig[1]);
            }
        }
Пример #17
0
        private void ecGOST3410Test()
        {
            BigInteger r = new BigInteger("29700980915817952874371204983938256990422752107994319651632687982059210933395");
            BigInteger s = new BigInteger("46959264877825372965922731380059061821746083849389763294914877353246631700866");

            byte[] kData = new BigInteger("53854137677348463731403841147996619241504003434302020712960838528893196233395").ToByteArrayUnsigned();

            SecureRandom k = FixedSecureRandom.From(kData);

            BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041");
            BigInteger mod_q = new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619");

            ECCurve curve = new FpCurve(
                mod_p,
                new BigInteger("7"),                                                                             // a
                new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414"), // b
                mod_q, BigInteger.One);

            ECDomainParameters spec = new ECDomainParameters(
                curve,
                curve.CreatePoint(
                    new BigInteger("2"),
                    new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")),
                mod_q, BigInteger.One);

            ECPrivateKeyParameters sKey = new ECPrivateKeyParameters(
                "ECGOST3410",
                new BigInteger("55441196065363246126355624130324183196576709222340016572108097750006097525544"), // d
                spec);

            ECPublicKeyParameters vKey = new ECPublicKeyParameters(
                "ECGOST3410",
                curve.CreatePoint(
                    new BigInteger("57520216126176808443631405023338071176630104906313632182896741342206604859403"),
                    new BigInteger("17614944419213781543809391949654080031942662045363639260709847859438286763994")),
                spec);

            ISigner sgr = SignerUtilities.GetSigner("ECGOST3410");

            sgr.Init(true, new ParametersWithRandom(sKey, k));

            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail("ECGOST3410 verification failed");
            }

            BigInteger[] sig = decode(sigBytes);

            if (!r.Equals(sig[0]))
            {
                Fail(
                    ": r component wrong." + SimpleTest.NewLine
                    + " expecting: " + r + SimpleTest.NewLine
                    + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail(
                    ": s component wrong." + SimpleTest.NewLine
                    + " expecting: " + s + SimpleTest.NewLine
                    + " got      : " + sig[1]);
            }
        }
Пример #18
0
		private void processSRPKeyExchange(
			MemoryStream	inStr,
			ISigner			signer)
		{
			Stream sigIn = inStr;
			if (signer != null)
			{
				signer.Init(false, this.serverPublicKey);
				signer.BlockUpdate(this.clientRandom, 0, this.clientRandom.Length);
				signer.BlockUpdate(this.serverRandom, 0, this.serverRandom.Length);

				sigIn = new SignerStream(inStr, signer, null);
			}

			/*
			* Parse the Structure
			*/
			byte[] NByte = TlsUtilities.ReadOpaque16(sigIn);
			byte[] gByte = TlsUtilities.ReadOpaque16(sigIn);
			byte[] sByte = TlsUtilities.ReadOpaque8(sigIn);
			byte[] BByte = TlsUtilities.ReadOpaque16(sigIn);

			if (signer != null)
			{
				byte[] sigByte = TlsUtilities.ReadOpaque16(sigIn);

				/*
				* Verify the Signature.
				*/
				if (!signer.VerifySignature(sigByte))
				{
					this.FailWithError(AL_fatal, AP_bad_certificate);
				}
			}

			this.AssertEmpty(inStr);

			BigInteger N = new BigInteger(1, NByte);
			BigInteger g = new BigInteger(1, gByte);
			byte[] s = sByte;
			BigInteger B = new BigInteger(1, BByte);

			Srp6Client srpClient = new Srp6Client();
			srpClient.Init(N, g, new Sha1Digest(), random);

			this.SRP_A = srpClient.GenerateClientCredentials(s, this.SRP_identity,
				this.SRP_password);

			try
			{
				BigInteger S = srpClient.CalculateSecret(B);
				this.pms = BigIntegers.AsUnsignedByteArray(S);
			}
			catch (CryptoException)
			{
				this.FailWithError(AL_fatal, AP_illegal_parameter);
			}
		}
Пример #19
0
        private void generationTest()
        {
            byte[]  data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            ISigner s    = SignerUtilities.GetSigner("GOST3410");

            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            AsymmetricKeyParameter sKey = p.Private;
            AsymmetricKeyParameter vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("GOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("GOST3410 verification failed");
            }

            //
            // default initialisation test
            //
            s = SignerUtilities.GetSigner("GOST3410");
            g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            // TODO This is supposed to be a 'default initialisation' test, but don't have a factory
            // These values are defaults from JCE provider
            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("GOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("GOST3410 verification failed");
            }

            //
            // encoded test
            //
            //KeyFactory f = KeyFactory.getInstance("GOST3410");
            //X509EncodedKeySpec  x509s = new X509EncodedKeySpec(vKey.GetEncoded());
            //Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)f.generatePublic(x509s);
            byte[] vKeyEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded();
            Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)
                                             PublicKeyFactory.CreateKey(vKeyEnc);

            if (!k1.Y.Equals(((Gost3410PublicKeyParameters)vKey).Y))
            {
                Fail("public number not decoded properly");
            }

            //PKCS8EncodedKeySpec  pkcs8 = new PKCS8EncodedKeySpec(sKey.GetEncoded());
            //Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)f.generatePrivate(pkcs8);
            byte[] sKeyEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded();
            Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)
                                              PrivateKeyFactory.CreateKey(sKeyEnc);

            if (!k2.X.Equals(((Gost3410PrivateKeyParameters)sKey).X))
            {
                Fail("private number not decoded properly");
            }

            //
            // ECGOST3410 generation test
            //
            s = SignerUtilities.GetSigner("ECGOST3410");
            g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");

            BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041");
            BigInteger mod_q = new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619");

            ECCurve curve = new FpCurve(
                mod_p,
                new BigInteger("7"),                                                                             // a
                new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414"), // b
                mod_q, BigInteger.One);

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
                curve.CreatePoint(
                    new BigInteger("2"),
                    new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")),
                mod_q, BigInteger.One);

            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECGOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECGOST3410 verification failed");
            }
        }
Пример #20
0
		private void checkSignature(
			int						size,
			ECPrivateKeyParameters	sKey,
			ECPublicKeyParameters	vKey,
			ISigner					sgr,
			SecureRandom			k,
			byte[]					message,
			BigInteger				r,
			BigInteger				s)
		{
			sgr.Init(true, new ParametersWithRandom(sKey, k));

			sgr.BlockUpdate(message, 0, message.Length);

			byte[] sigBytes = sgr.GenerateSignature();

			sgr.Init(false, vKey);

			sgr.BlockUpdate(message, 0, message.Length);

			if (!sgr.VerifySignature(sigBytes))
			{
				Fail(size + " bit EC verification failed");
			}

			BigInteger[] sig = derDecode(sigBytes);

			if (!r.Equals(sig[0]))
			{
				Fail(size + "bit"
					+ ": r component wrong." + SimpleTest.NewLine
					+ " expecting: " + r + SimpleTest.NewLine
					+ " got      : " + sig[0]);
			}

			if (!s.Equals(sig[1]))
			{
				Fail(size + "bit"
					+ ": s component wrong." + SimpleTest.NewLine
					+ " expecting: " + s + SimpleTest.NewLine
					+ " got      : " + sig[1]);
			}
		}
        /*
         * we generate a self signed certificate for the sake of testing - SHA224withECDSA
         */
        private void createECRequest(
            string algorithm,
            DerObjectIdentifier algOid)
        {
            FpCurve curve = new FpCurve(
                new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p)
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16),                      // a
                new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16));                     // b

            ECDomainParameters spec = new ECDomainParameters(
                curve,
//				curve.DecodePoint(Hex.Decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
                curve.DecodePoint(Hex.Decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16));             // n

            ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
                new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
//				curve.DecodePoint(Hex.Decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                spec);

//			//
//			// set up the keys
//			//
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;
//
//			KeyFactory fact = KeyFactory.getInstance("ECDSA");
//
//			privKey = fact.generatePrivate(privKeySpec);
//			pubKey = fact.generatePublic(pubKeySpec);

            Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(
                algorithm, new X509Name("CN=XXX"), pubKey, null, privKey);

            if (!req.Verify())
            {
                Fail("Failed Verify check EC.");
            }

            req = new Pkcs10CertificationRequest(req.GetEncoded());
            if (!req.Verify())
            {
                Fail("Failed Verify check EC encoded.");
            }

            //
            // try with point compression turned off
            //
//			((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
            ECPoint q = pubKey.Q.Normalize();

            pubKey = new ECPublicKeyParameters(
                pubKey.AlgorithmName,
                q.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()),
                pubKey.Parameters);

            req = new Pkcs10CertificationRequest(
                algorithm, new X509Name("CN=XXX"), pubKey, null, privKey);
            if (!req.Verify())
            {
                Fail("Failed Verify check EC uncompressed.");
            }

            req = new Pkcs10CertificationRequest(req.GetEncoded());
            if (!req.Verify())
            {
                Fail("Failed Verify check EC uncompressed encoded.");
            }

            if (!req.SignatureAlgorithm.Algorithm.Equals(algOid))
            {
                Fail("ECDSA oid incorrect.");
            }

            if (req.SignatureAlgorithm.Parameters != null)
            {
                Fail("ECDSA parameters incorrect.");
            }

            ISigner sig = SignerUtilities.GetSigner(algorithm);

            sig.Init(false, pubKey);

            byte[] b = req.GetCertificationRequestInfo().GetEncoded();
            sig.BlockUpdate(b, 0, b.Length);

            if (!sig.VerifySignature(req.GetSignatureOctets()))
            {
                Fail("signature not mapped correctly.");
            }
        }