Exemplo n.º 1
0
        public byte[] computeSharedSecret(byte[] pri, byte[] pub)
        {
            const string Algorithm = "ECDH";
            //const int KeyBitSize = 128;

            X9ECParameters     ecPars    = NistNamedCurves.GetByName("P-256");
            ECDomainParameters ecDomPars = new ECDomainParameters(ecPars.Curve, ecPars.G, ecPars.N, ecPars.H, ecPars.GetSeed());
            var curve = ecDomPars.Curve;

            var pubQ = curve.DecodePoint(pub);
            //ECPoint pubQ = ecPars.Curve.DecodePoint(pub);
            //ECPoint priQ = curve.DecodePoint(pri);
            IBasicAgreement _aliceKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            //csPri = ((ECPrivateKeyParameters)aliceKeyPair.Private).D.ToByteArray();
            var priKeyPara = new ECPrivateKeyParameters(new BigInteger(pri), ecDomPars);            //priQ.Curve.

            _aliceKeyAgree.Init(priKeyPara);

            AsymmetricKeyParameter pubKeyPara = new ECPublicKeyParameters(pubQ, ecDomPars);
            //SubjectPublicKeyInfo _key = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKeyPara);
            //var pubPara = new ECPublicKeyParameters(priQ, ecDomPars);
            BigInteger aliceAgree = _aliceKeyAgree.CalculateAgreement(pubKeyPara);

            KeyParameter sharedKey = new KeyParameter(aliceAgree.ToByteArrayUnsigned());

            //return sharedKey.;
            return(sharedKey.GetKey());
        }
Exemplo n.º 2
0
 public IesEngine(IBasicAgreement agree, IDerivationFunction kdf, IMac mac)
 {
     this.agree = agree;
     this.kdf   = kdf;
     this.mac   = mac;
     macBuf     = new byte[mac.GetMacSize()];
 }
 public DefaultTlsAgreementCredentials(Certificate certificate, AsymmetricKeyParameter privateKey)
 {
     if (certificate == null)
     {
         throw new ArgumentNullException("certificate");
     }
     if (certificate.IsEmpty)
     {
         throw new ArgumentException("cannot be empty", "certificate");
     }
     if (privateKey == null)
     {
         throw new ArgumentNullException("privateKey");
     }
     if (!privateKey.IsPrivate)
     {
         throw new ArgumentException("must be private", "privateKey");
     }
     if (privateKey is DHPrivateKeyParameters)
     {
         this.mBasicAgreement    = new DHBasicAgreement();
         this.mTruncateAgreement = true;
     }
     else
     {
         if (!(privateKey is ECPrivateKeyParameters))
         {
             throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey");
         }
         this.mBasicAgreement    = new ECDHBasicAgreement();
         this.mTruncateAgreement = false;
     }
     this.mCertificate = certificate;
     this.mPrivateKey  = privateKey;
 }
Exemplo n.º 4
0
        public static EncryptionResult Encrypt(byte[] userKey, byte[] userSecret, byte[] payload)
        {
            byte[] salt = GenerateSalt(16);
            AsymmetricCipherKeyPair serverKeyPair = ECKeyHelper.GenerateKeys();

            IBasicAgreement ecdhAgreement = AgreementUtilities.GetBasicAgreement("ECDH");

            ecdhAgreement.Init(serverKeyPair.Private);

            ECPublicKeyParameters userPublicKey = ECKeyHelper.GetPublicKey(userKey);

            byte[] key             = ecdhAgreement.CalculateAgreement(userPublicKey).ToByteArrayUnsigned();
            byte[] serverPublicKey = ((ECPublicKeyParameters)serverKeyPair.Public).Q.GetEncoded(false);

            byte[] prk   = HKDF(userSecret, key, Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32);
            byte[] cek   = HKDF(salt, prk, CreateInfoChunk("aesgcm", userKey, serverPublicKey), 16);
            byte[] nonce = HKDF(salt, prk, CreateInfoChunk("nonce", userKey, serverPublicKey), 12);

            byte[] input            = AddPaddingToInput(payload);
            byte[] encryptedMessage = EncryptAes(nonce, cek, input);

            return(new EncryptionResult
            {
                Salt = salt,
                Payload = encryptedMessage,
                PublicKey = serverPublicKey
            });
        }
        public DefaultTlsAgreementCredentials(Certificate certificate, AsymmetricKeyParameter privateKey)
        {
            if (certificate == null)
                throw new ArgumentNullException("certificate");
            if (certificate.IsEmpty)
                throw new ArgumentException("cannot be empty", "certificate");
            if (privateKey == null)
                throw new ArgumentNullException("privateKey");
            if (!privateKey.IsPrivate)
                throw new ArgumentException("must be private", "privateKey");

            if (privateKey is DHPrivateKeyParameters)
            {
                mBasicAgreement = new DHBasicAgreement();
                mTruncateAgreement = true;
            }
            else if (privateKey is ECPrivateKeyParameters)
            {
                mBasicAgreement = new ECDHBasicAgreement();
                mTruncateAgreement = false;
            }
            else
            {
                throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey");
            }

            this.mCertificate = certificate;
            this.mPrivateKey = privateKey;
        }
Exemplo n.º 6
0
        public static void TestMethod()
        {
            //BEGIN SETUP ALICE
            var aliceKeyGen    = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
            var aliceGenerator = new DHParametersGenerator();

            aliceGenerator.Init(KeyBitSize, DefaultPrimeProbability, new SecureRandom());
            DHParameters aliceParameters = aliceGenerator.GenerateParameters();

            var aliceKGP = new DHKeyGenerationParameters(new SecureRandom(), aliceParameters);

            aliceKeyGen.Init(aliceKGP);

            AsymmetricCipherKeyPair aliceKeyPair = aliceKeyGen.GenerateKeyPair();
            var aliceKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            aliceKeyAgree.Init(aliceKeyPair.Private);
            //END SETUP ALICE

            /////AT THIS POINT, Alice's Public Key, Alice's Parameter P and Alice's Parameter G are sent unsecure to BOB

            //BEGIN SETUP BOB
            var          bobKeyGen     = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
            DHParameters bobParameters = new DHParameters(aliceParameters.P, aliceParameters.G);

            KeyGenerationParameters bobKGP = new DHKeyGenerationParameters(new SecureRandom(), bobParameters);

            bobKeyGen.Init(bobKGP);

            AsymmetricCipherKeyPair bobKeyPair  = bobKeyGen.GenerateKeyPair();
            IBasicAgreement         bobKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            bobKeyAgree.Init(bobKeyPair.Private);
            //END SETUP BOB

            BigInteger aliceAgree = aliceKeyAgree.CalculateAgreement(bobKeyPair.Public);
            BigInteger bobAgree   = bobKeyAgree.CalculateAgreement(aliceKeyPair.Public);

            if (!aliceAgree.Equals(bobAgree))
            {
                throw new Exception("Keys do not match.");
            }

            byte[] nonSecretMessage = GetBytes("HeaderMessageForASDF");
            byte[] secretMessage    = GetBytes("Secret message contents");
            byte[] decNonSecretBytes;

            KeyParameter sharedKey = new KeyParameter(aliceAgree.ToByteArrayUnsigned());

            var encMessage = EncryptMessage(sharedKey, nonSecretMessage, secretMessage);
            var decMessage = DecryptMessage(sharedKey, encMessage, out decNonSecretBytes);

            var decNonSecretMessage = GetString(decNonSecretBytes);
            var decSecretMessage    = GetString(decMessage);

            Debug.WriteLine(decNonSecretMessage + " - " + decSecretMessage);

            return;
        }
Exemplo n.º 7
0
 public IesEngine(IBasicAgreement agree, IDerivationFunction kdf, IMac mac, BufferedBlockCipher cipher)
 {
     this.agree  = agree;
     this.kdf    = kdf;
     this.mac    = mac;
     macBuf      = new byte[mac.GetMacSize()];
     this.cipher = cipher;
 }
 /**
 * set up for use in conjunction with a block cipher to handle the
 * message.
 *
 * @param agree the key agreement used as the basis for the encryption
 * @param kdf the key derivation function used for byte generation
 * @param mac the message authentication code generator for the message
 * @param cipher the cipher to used for encrypting the message
 */
 public IesEngine(IBasicAgreement agree, IDerivationFunction kdf, IMac mac, BufferedBlockCipher cipher)
 {
     _agree = agree;
     _kdf = kdf;
     _mac = mac;
     _macBuf = new byte[mac.GetMacSize()];
     _cipher = cipher;
 }
 /**
 * set up for use with stream mode, where the key derivation function
 * is used to provide a stream of bytes to xor with the message.
 *
 * @param agree the key agreement used as the basis for the encryption
 * @param kdf the key derivation function used for byte generation
 * @param mac the message authentication code generator for the message
 */
 public IesEngine(IBasicAgreement agree, IDerivationFunction kdf, IMac mac)
 {
     _agree = agree;
     _kdf = kdf;
     _mac = mac;
     _macBuf = new byte[mac.GetMacSize()];
     //            this.cipher = null;
 }
Exemplo n.º 10
0
            internal AgreementCalculator(AgreementParameters parameters, IKey ecPrivateKey)
            {
                this.agreement = CDH_PROVIDER.CreateEngine(EngineUsage.GENERAL);

                agreement.Init(GetPrivateKeyParameters((AsymmetricECPrivateKey)ecPrivateKey));

                this.parameters = parameters;
            }
Exemplo n.º 11
0
 /**
  * set up for use with stream mode, where the key derivation function
  * is used to provide a stream of bytes to xor with the message.
  *
  * @param agree the key agreement used as the basis for the encryption
  * @param kdf the key derivation function used for byte generation
  * @param mac the message authentication code generator for the message
  */
 public IesEngine(IBasicAgreement agree, IDerivationFunction kdf, IMac mac)
 {
     _agree  = agree;
     _kdf    = kdf;
     _mac    = mac;
     _macBuf = new byte[mac.GetMacSize()];
     //            this.cipher = null;
 }
Exemplo n.º 12
0
        public static void ECDHKeyExchangeExample()
        {
            /*NOTE: this should represent an example of ECDH. As there are no mechanisms used in order to ensure if Alice is Alice and Bob is Bob as now
             * certificate is used in this example. */

            /* Define used key exchange algorithm. In our case this is elliptic curve diffie hellmann. */
            const string Algorithm = "ECDH";

            /* ALICE starts the key exchange. She sends the the X and Y coordinates of her public key as well as the used curve to BOB */

            const string Alicebase16strpubX = "0x14CC3B7FBEF441E21DE27CA72F5E2BB60EFEA474A5973028589016D36DB11E267A1F49FD2DC1F42553E0A6BB4E66CA9E8C2667074A7EABAD1A10545626B53F4ECC9";
            const string Alicebase16strY    = "0x190E33894B32DD6FDFDF8E560630B2419CC45A7FF770530CD564354A5D4D7E76DB1F4A1C0DC9E7D5720F257C5A8D2D908C342217300ACD78D258D00EEDDB2C441F5";
            const string curve = "P-521";//"SECP521R1";

            /****************************************************************************/

            /* BOB starts the actions. Bob uses the public public key coordinates as well as the curve to generate an ephemeral key
             * pair on his side.
             */

            X9ECParameters ecP = NistNamedCurves.GetByName(curve);

            FpCurve c = (FpCurve)ecP.Curve;

            ECFieldElement x = c.FromBigInteger(new BigInteger(System.Numerics.BigInteger.Parse(Alicebase16strpubX, NumberStyles.HexNumber).ToString()));
            ECFieldElement y = c.FromBigInteger(new BigInteger(System.Numerics.BigInteger.Parse(Alicebase16strY, NumberStyles.HexNumber).ToString()));

            Org.BouncyCastle.Math.EC.ECPoint q    = new FpPoint(c, x, y);
            ECPublicKeyParameters            xxpk = new ECPublicKeyParameters("ECDH", q, SecObjectIdentifiers.SecP521r1);

            IAsymmetricCipherKeyPairGenerator KeyGen       = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
            KeyGenerationParameters           keygenParams = new ECKeyGenerationParameters(new ECDomainParameters(ecP.Curve, ecP.G, ecP.N), new SecureRandom());

            KeyGen.Init(keygenParams);

            AsymmetricCipherKeyPair KeyPair  = KeyGen.GenerateKeyPair();
            IBasicAgreement         KeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            /*****************************************************************************/

            /* BOB calculates the SHARED SECRET */
            KeyAgree.Init(KeyPair.Private);
            BigInteger Agree = KeyAgree.CalculateAgreement(xxpk);
            /*****************************************************************************/

            /*BOB encrypts his secret message. Using the Encryption helper method with AES 256 CBC. The helper method is using the last
             * 16 bytes of the generated secret and a generated initial vector of 16 byte to encrypt*/
            string ciphertext             = Encryption.EncryptString("Hallo Alice, this is an important message to you.", Agree.ToByteArray());
            ECPublicKeyParameters params2 = (ECPublicKeyParameters)KeyPair.Public;

            /*****************************************************************************/

            /*BOB is sending the x and y coordinates of his public key and the encrypted message to Alice on a public (not secured) channel*/
            Console.WriteLine("PublicKeyX Base(16): " + params2.Q.XCoord.ToBigInteger().ToString(16).ToUpper());
            Console.WriteLine("PublicKeyY Base(16): " + params2.Q.YCoord.ToBigInteger().ToString(16).ToUpper());
            Console.WriteLine("Ciphertext: " + ciphertext);
            /*****************************************************************************/
        }
Exemplo n.º 13
0
    private static string DoECDH(byte[] dataPrv, byte[] dataPub)
    {
        IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("ECDH");

        agreement.Init(LoadPrivateKey(dataPrv));
        Org.BouncyCastle.Math.BigInteger sharedSecret = agreement.CalculateAgreement(LoadPublicKey(dataPub));
        byte[] secret = sharedSecret.ToByteArray();
        return(BytesToHex(secret));
    }
Exemplo n.º 14
0
 /**
  * set up for use with stream mode, where the key derivation function
  * is used to provide a stream of bytes to xor with the message.
  *
  * @param agree the key agreement used as the basis for the encryption
  * @param kdf the key derivation function used for byte generation
  * @param mac the message authentication code generator for the message
  */
 public CustomIesEngine(
     IBasicAgreement agree,
     IDerivationFunction kdf,
     IMac mac)
 {
     Agree  = agree;
     Kdf    = kdf;
     Mac    = mac;
     Cipher = null;
 }
Exemplo n.º 15
0
 /**
  * set up for use in conjunction with a block cipher to handle the
  * message.
  *
  * @param agree the key agreement used as the basis for the encryption
  * @param kdf the key derivation function used for byte generation
  * @param mac the message authentication code generator for the message
  * @param cipher the cipher to used for encrypting the message
  */
 public CustomIesEngine(
     IBasicAgreement agree,
     IDerivationFunction kdf,
     IMac mac,
     BufferedBlockCipher cipher)
 {
     Agree  = agree;
     Kdf    = kdf;
     Mac    = mac;
     Cipher = cipher;
 }
Exemplo n.º 16
0
 /**
  * set up for use with stream mode, where the key derivation function
  * is used to provide a stream of bytes to xor with the message.
  *  @param agree the key agreement used as the basis for the encryption
  * @param kdf    the key derivation function used for byte generation
  * @param mac    the message authentication code generator for the message
  * @param hash   hash ing function
  * @param cipher the actual cipher
  */
 public OldEthereumIesEngine(
     IBasicAgreement agreement,
     IMac mac,
     IDigest hash,
     BufferedBlockCipher cipher)
 {
     _agreement = agreement;
     Mac        = mac;
     _hash      = hash;
     Cipher     = cipher;
 }
Exemplo n.º 17
0
        private void doTestDesAndDesEde(
            IBigInteger g,
            IBigInteger p)
        {
            DHParameters dhParams = new DHParameters(p, g, null, 256);

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");

            keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), dhParams));

            IAsymmetricCipherKeyPair kp = keyGen.GenerateKeyPair();

            IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreement("DH");

            keyAgreement.Init(kp.Private);
            IBigInteger agreed = keyAgreement.CalculateAgreement(kp.Public);

            byte[] agreedBytes = agreed.ToByteArrayUnsigned();

            // TODO Figure out where the magic happens of choosing the right
            // bytes from 'agreedBytes' for each key type - need C# equivalent?
            // (see JCEDHKeyAgreement.engineGenerateSecret)

//			SecretKey key = keyAgreement.generateSecret("DES");
//
//			if (key.getEncoded().length != 8)
//			{
//				Fail("DES length wrong");
//			}
//
//			if (!DESKeySpec.isParityAdjusted(key.getEncoded(), 0))
//			{
//				Fail("DES parity wrong");
//			}
//
//			key = keyAgreement.generateSecret("DESEDE");
//
//			if (key.getEncoded().length != 24)
//			{
//				Fail("DESEDE length wrong");
//			}
//
//			if (!DESedeKeySpec.isParityAdjusted(key.getEncoded(), 0))
//			{
//				Fail("DESEDE parity wrong");
//			}
//
//			key = keyAgreement.generateSecret("Blowfish");
//
//			if (key.getEncoded().length != 16)
//			{
//				Fail("Blowfish length wrong");
//			}
        }
Exemplo n.º 18
0
        public ServerAuthority(DHParameters parameters)
        {
            this.parameters = parameters;

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");
            KeyGenerationParameters kgp = new DHKeyGenerationParameters(new SecureRandom(), parameters);

            keyGen.Init(kgp);
            kp = keyGen.GenerateKeyPair();
            agreement = AgreementUtilities.GetBasicAgreement("DH");
            agreement.Init(kp.Private);
        }
Exemplo n.º 19
0
        public ServerAuthority(DHParameters parameters)
        {
            this.parameters = parameters;

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");
            KeyGenerationParameters           kgp    = new DHKeyGenerationParameters(new SecureRandom(), parameters);

            keyGen.Init(kgp);
            kp        = keyGen.GenerateKeyPair();
            agreement = AgreementUtilities.GetBasicAgreement("DH");
            agreement.Init(kp.Private);
        }
Exemplo n.º 20
0
        public void run()
        {
            AsymmetricCipherKeyPair aKeyPair       = _keyGen.GenerateKeyPair();
            IBasicAgreement         aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgreeBasic.Init(aKeyPair.Private);
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();

            IPAddress  ip     = IPAddress.Parse("192.168.1.117");
            IPEndPoint ipe    = new IPEndPoint(ip, 8899);
            Socket     socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(ipe);
            //byte[] bs = Encoding.ASCII.GetBytes("Windows Test");
            socket.Send(pubEnc, pubEnc.Length, 0);

            byte[] recvBytes = new byte[1024];
            int    bytes     = socket.Receive(recvBytes, recvBytes.Length, 0);

            socket.Close();

            byte[] bPub = new byte[bytes];
            for (int i = 0; i < bytes; i++)
            {
                bPub[i] = recvBytes[i];
            }
            ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(bPub);
            BigInteger            k      = aKeyAgreeBasic.CalculateAgreement(pubKey);

            byte[] keyBytes = k.ToByteArray();
            //Console.WriteLine(keybytes.Length);
            if (keyBytes.Length > 24)
            {
                byte[] fixedKeybytes = new byte[24];
                for (int i = 0; i < 24; i++)
                {
                    fixedKeybytes[i] = keyBytes[i + keyBytes.Length - 24];
                }
                keyBytes = fixedKeybytes;
            }
            Console.WriteLine(Hex.ToHexString(keyBytes));

            IDigest digest = new MD5Digest();

            digest.BlockUpdate(keyBytes, 0, keyBytes.Length);
            byte[] idBytes = new byte[digest.GetDigestSize()];
            digest.DoFinal(idBytes, 0);
            _id = Hex.ToHexString(idBytes);
            Console.WriteLine(_id);
            _trivium = new Trivium();
            _trivium.setKIV(keyBytes);
            _trivium.initProcess();
        }
Exemplo n.º 21
0
        private void doTestExplicitWrapping(
            int size,
            int privateValueSize,
            IBigInteger g,
            IBigInteger p)
        {
            DHParameters dhParams = new DHParameters(p, g, null, privateValueSize);

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");

            keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), dhParams));

            //
            // a side
            //
            IAsymmetricCipherKeyPair aKeyPair = keyGen.GenerateKeyPair();

            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("DH");

            checkKeySize(privateValueSize, aKeyPair);

            aKeyAgree.Init(aKeyPair.Private);

            //
            // b side
            //
            IAsymmetricCipherKeyPair bKeyPair = keyGen.GenerateKeyPair();

            IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement("DH");

            checkKeySize(privateValueSize, bKeyPair);

            bKeyAgree.Init(bKeyPair.Private);

            //
            // agreement
            //
//			aKeyAgree.doPhase(bKeyPair.Public, true);
//			bKeyAgree.doPhase(aKeyPair.Public, true);
//
//			SecretKey k1 = aKeyAgree.generateSecret(PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id);
//			SecretKey k2 = bKeyAgree.generateSecret(PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id);

            // TODO Does this really test the same thing as the above code?
            IBigInteger b1 = aKeyAgree.CalculateAgreement(bKeyPair.Public);
            IBigInteger b2 = bKeyAgree.CalculateAgreement(aKeyPair.Public);

            if (!b1.Equals(b2))
            {
                Fail("Explicit wrapping test failed");
            }
        }
Exemplo n.º 22
0
        public byte[] FinalizeKeyExchange(byte[] peer_pk)
        {
            PemReader pem = new PemReader(new StringReader(Encoding.UTF8.GetString(peer_pk)));

            ECPublicKeyParameters  peer_ecdh_pk = (ECPublicKeyParameters)pem.ReadObject();
            ECPrivateKeyParameters self_priv    = ECDHEPair.Private as ECPrivateKeyParameters;

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("ECDH");

            agreement.Init(self_priv);

            return(agreement.CalculateAgreement(peer_ecdh_pk).ToByteArray());
        }
Exemplo n.º 23
0
        private string GeneratePassword()
        {
            DHPublicKeyParameters publicKey = new DHPublicKeyParameters(
                ((DHPublicKeyParameters)PublicKeyFactory.CreateKey(encodedPublicKey)).Y, sharedParameters);

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("DH");

            agreement.Init(keyPair.Private);

            BigInteger agreementValue = agreement.CalculateAgreement(publicKey);

            return(agreementValue.ToString(16));
        }
Exemplo n.º 24
0
        public static string ViettelEncryption(string inputText, string viettelPublicKey, string customerPrivateKey)
        {
            string encryptedSMSText = "";

            try
            {
                //string privateKeyConek = @"MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQg1OGD/UuZ3FO9u6e60TmOJne47RWWYGqH7FIzRvxxhruhRANCAAQKJjarvVgOWJz6eg5ncv5WucbRBR2/qJqXpe5Yo9a9NQ7gzOgRBvejgj2q2NFNo9lgZgeFXl4fuoqOiLCGawaO";
                //string publicKeyViettel = @"MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEe9YVVfiuEbTC8MLFcmettM9z6i1bh49kM97NZJ0yLCZcDQtWhuQ230W/nackSySWO8tErAzDWiMdvEACaHevaA==";

                //PublicKey Viettel
                var base64PubKeyStr = viettelPublicKey; // "MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEe9YVVfiuEbTC8MLFcmettM9z6i1bh49kM97NZJ0yLCZcDQtWhuQ230W/nackSySWO8tErAzDWiMdvEACaHevaA==";
                var publicKeyBytes  = Convert.FromBase64String(base64PubKeyStr);
                ECPublicKeyParameters otherPartyPublicKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(publicKeyBytes);
                Console.WriteLine(otherPartyPublicKey.ToString());

                //PrivateKey
                var base64PrivateKeyStr           = customerPrivateKey; // "MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgnFkCkg26s2pwWa1oV0cYFUUqU0sCDeYP2wRpUQcu74WhRANCAASDBA7GheF0EFqZY8xhQSXhYog6pEEtOBIo64eFBT2JZsPZysxk5i+PQXfVhkvib/tTLag6MuNiL451+u9qPbg5";
                var privateKeyBytes               = Convert.FromBase64String(base64PrivateKeyStr);
                ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privateKeyBytes);
                Console.WriteLine(privateKey.ToString());

                //Make share key
                IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");
                aKeyAgree.Init(privateKey);
                BigInteger sharedSecret      = aKeyAgree.CalculateAgreement(otherPartyPublicKey);
                byte[]     sharedSecretBytes = sharedSecret.ToByteArrayUnsigned();
                var        keyparam          = ParameterUtilities.CreateKeyParameter("AES", sharedSecretBytes);

                var    plainText     = inputText; // "Hello! This is an banksms message!";
                byte[] plainTextByte = Encoding.UTF8.GetBytes(plainText);
                var    bankSmsIv     = "Banksms@Viettel!";
                byte[] iv            = Encoding.UTF8.GetBytes(bankSmsIv);

                var parametersWithIV = new ParametersWithIV(keyparam, iv);
                Console.WriteLine(Encoding.ASCII.GetString(parametersWithIV.GetIV()));
                Console.WriteLine(parametersWithIV.ToString());

                var cipher = CipherUtilities.GetCipher("AES/CBC/PKCS5Padding");
                cipher.Init(true, parametersWithIV);
                byte[] output = cipher.DoFinal(plainTextByte);

                Console.WriteLine(string.Concat(output.Select(b => b.ToString("X2"))));
                encryptedSMSText = string.Concat(output.Select(b => b.ToString("X2")));  // Nội dung sau khi được mã hóa
            } catch (Exception ex)
            {
                Console.WriteLine("Exception ex = " + ex.Message);
            }


            return(encryptedSMSText);
        }
Exemplo n.º 25
0
        public void TestECMqv()
        {
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECMQV");

            X9ECParameters     x9     = ECNamedCurveTable.GetByName("prime239v1");
            ECDomainParameters ecSpec = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H);

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

            //
            // U side
            //
            AsymmetricCipherKeyPair U1 = g.GenerateKeyPair();
            AsymmetricCipherKeyPair U2 = g.GenerateKeyPair();

            IBasicAgreement uAgree = AgreementUtilities.GetBasicAgreement("ECMQV");

            uAgree.Init(new MqvPrivateParameters(
                            (ECPrivateKeyParameters)U1.Private,
                            (ECPrivateKeyParameters)U2.Private,
                            (ECPublicKeyParameters)U2.Public));

            //
            // V side
            //
            AsymmetricCipherKeyPair V1 = g.GenerateKeyPair();
            AsymmetricCipherKeyPair V2 = g.GenerateKeyPair();

            IBasicAgreement vAgree = AgreementUtilities.GetBasicAgreement("ECMQV");

            vAgree.Init(new MqvPrivateParameters(
                            (ECPrivateKeyParameters)V1.Private,
                            (ECPrivateKeyParameters)V2.Private,
                            (ECPublicKeyParameters)V2.Public));

            //
            // agreement
            //
            BigInteger ux = uAgree.CalculateAgreement(new MqvPublicParameters(
                                                          (ECPublicKeyParameters)V1.Public,
                                                          (ECPublicKeyParameters)V2.Public));
            BigInteger vx = vAgree.CalculateAgreement(new MqvPublicParameters(
                                                          (ECPublicKeyParameters)U1.Public,
                                                          (ECPublicKeyParameters)U2.Public));

            if (!ux.Equals(vx))
            {
                Fail("Agreement failed");
            }
        }
Exemplo n.º 26
0
 /**
  * set up for use with stream mode, where the key derivation function
  * is used to provide a stream of bytes to xor with the message.
  *  @param agree the key agreement used as the basis for the encryption
  * @param kdf    the key derivation function used for byte generation
  * @param mac    the message authentication code generator for the message
  * @param hash   hash ing function
  * @param cipher the actual cipher
  */
 public EthereumIesEngine(
     IBasicAgreement agreement,
     IDerivationFunction kdf,
     IMac mac,
     IDigest hash,
     BufferedBlockCipher cipher)
 {
     _agreement = agreement;
     _kdf       = kdf;
     Mac        = mac;
     _hash      = hash;
     _macBuf    = new byte[mac.GetMacSize()];
     Cipher     = cipher;
 }
        private static byte[] GetKeyingMaterial(PushSubscription subscription, AsymmetricKeyParameter applicationServerPrivateKey, byte[] applicationServerPublicKey)
        {
            IBasicAgreement ecdhAgreement = AgreementUtilities.GetBasicAgreement("ECDH");

            ecdhAgreement.Init(applicationServerPrivateKey);

            byte[] userAgentPublicKey   = UrlBase64Converter.FromUrlBase64String(subscription.GetKey(PushEncryptionKeyName.P256DH));
            byte[] authenticationSecret = UrlBase64Converter.FromUrlBase64String(subscription.GetKey(PushEncryptionKeyName.Auth));
            byte[] sharedSecret         = ecdhAgreement.CalculateAgreement(ECKeyHelper.GetECPublicKeyParameters(userAgentPublicKey)).ToByteArrayUnsigned();
            byte[] sharedSecretHash     = HmacSha256(authenticationSecret, sharedSecret);
            byte[] infoParameter        = GetKeyingMaterialInfoParameter(userAgentPublicKey, applicationServerPublicKey);
            byte[] keyingMaterial       = HmacSha256(sharedSecretHash, infoParameter);

            return(keyingMaterial);
        }
Exemplo n.º 28
0
        /**
         * Add a key agreement based recipient.
         *
         * @param agreementAlgorithm key agreement algorithm to use.
         * @param senderPrivateKey private key to initialise sender side of agreement with.
         * @param senderPublicKey sender public key to include with message.
         * @param recipientCert recipient's public key certificate.
         * @param cekWrapAlgorithm OID for key wrapping algorithm to use.
         * @exception SecurityUtilityException if the algorithm requested cannot be found
         * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
         */
        public void AddKeyAgreementRecipient(
            string agreementAlgorithm,
            AsymmetricKeyParameter senderPrivateKey,
            AsymmetricKeyParameter senderPublicKey,
            X509Certificate recipientCert,
            string cekWrapAlgorithm)
        {
            if (!senderPrivateKey.IsPrivate)
            {
                throw new ArgumentException("Expected private key", "senderPrivateKey");
            }
            if (senderPublicKey.IsPrivate)
            {
                throw new ArgumentException("Expected public key", "senderPublicKey");
            }

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                agreementAlgorithm, cekWrapAlgorithm);

            agreement.Init(new ParametersWithRandom(senderPrivateKey, rand));

            BigInteger secretNum = agreement.CalculateAgreement(recipientCert.GetPublicKey());

            try
            {
                SubjectPublicKeyInfo oPubKeyInfo =
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(senderPublicKey);

                OriginatorIdentifierOrKey originator = new OriginatorIdentifierOrKey(
                    new OriginatorPublicKey(
                        new AlgorithmIdentifier(oPubKeyInfo.AlgorithmID.ObjectID, DerNull.Instance),
                        oPubKeyInfo.PublicKeyData.GetBytes()));

                // TODO Fix the way bytes are derived from the secret
                byte[]       secretBytes = secretNum.ToByteArrayUnsigned();
                KeyParameter secret      = ParameterUtilities.CreateKeyParameter(
                    cekWrapAlgorithm, secretBytes);

                recipientInfs.Add(
                    new RecipientInf(cekWrapAlgorithm, secret, agreementAlgorithm,
                                     cekWrapAlgorithm, originator, recipientCert));
            }
            catch (IOException e)
            {
                throw new InvalidKeyException("cannot extract originator public key: " + e);
            }
        }
Exemplo n.º 29
0
        private byte[] GenerateAESKey(ECPublicKeyParameters bobPublicKey, AsymmetricKeyParameter alicePrivateKey)
        {
            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgree.Init(alicePrivateKey);
            BigInteger sharedSecret = aKeyAgree.CalculateAgreement(bobPublicKey);

            byte[] sharedSecretBytes = sharedSecret.ToByteArray();

            IDigest digest = new Sha256Digest();

            byte[] symmetricKey = new byte[digest.GetDigestSize()];
            digest.BlockUpdate(sharedSecretBytes, 0, sharedSecretBytes.Length);
            digest.DoFinal(symmetricKey, 0);

            return(symmetricKey);
        }
Exemplo n.º 30
0
        private void GetShardSecret()
        {
            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgree.Init(this.merchantPrivateKey);
            BigInteger SharedSecret = aKeyAgree.CalculateAgreement(this.ephemeralPublicKey);

            byte[] tmpSharedSecret = SharedSecret.ToByteArray();

            if (tmpSharedSecret.Length > 32)
            {
                this.sharedSecret = new byte[tmpSharedSecret.Length - 1];
                Array.Copy(tmpSharedSecret, 1, this.sharedSecret, 0, tmpSharedSecret.Length - 1);
            }
            else
            {
                this.sharedSecret = tmpSharedSecret;
            }
        }
Exemplo n.º 31
0
        public void TestSubgroupConfinement()
        {
            DHParameters parameters = Ike2048();
            BigInteger   p = parameters.P, g = parameters.G;

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");

            //keyGen.initialize(params);
            keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), parameters));

            AsymmetricCipherKeyPair kp               = keyGen.GenerateKeyPair();
            AsymmetricKeyParameter  priv             = kp.Private;

            IBasicAgreement ka = AgreementUtilities.GetBasicAgreement("DH");

            BigInteger[] weakPublicKeys = { BigInteger.Zero,       BigInteger.One, p.Subtract(BigInteger.One), p,
                                            p.Add(BigInteger.One), BigInteger.One.Negate() };

            foreach (BigInteger weakKey in weakPublicKeys)
            {
                try
                {
                    new DHPublicKeyParameters(weakKey, parameters);
                    Fail("Generated weak public key");
                }
                catch (ArgumentException ex)
                {
                    IsTrue("wrong message (constructor)", ex.Message.StartsWith("invalid DH public key"));
                }

                ka.Init(priv);

                try
                {
                    ka.CalculateAgreement(new DHWeakPubKey(weakKey, parameters));
                    Fail("Generated secrets with weak public key");
                }
                catch (ArgumentException ex)
                {
                    IsTrue("wrong message (CalculateAgreement)", "Diffie-Hellman public key is weak".Equals(ex.Message));
                }
            }
        }
Exemplo n.º 32
0
        public void TestExceptions()
        {
            DHParameters dhParams = new DHParameters(p512, g512);

            try
            {
                IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement("DH");

//				aKeyAgreeBasic.generateSecret("DES");
                aKeyAgreeBasic.CalculateAgreement(null);
            }
            catch (InvalidOperationException)
            {
                // okay
            }
            catch (Exception e)
            {
                Fail("Unexpected exception: " + e, e);
            }
        }
Exemplo n.º 33
0
        public static BigInteger CalculateSharedKey(BigInteger BIx, BigInteger BIy, ECPrivateKeyParameters privateKey)
        {
            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgree.Init(privateKey);

            X9ECParameters     ecP    = NistNamedCurves.GetByName("P-521");
            ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());

            FpCurve c = (FpCurve)ecSpec.Curve;

            ECFieldElement x = new FpFieldElement(c.Q, BIx);
            ECFieldElement y = new FpFieldElement(c.Q, BIy);
            ECPoint        q = new FpPoint(ecP.Curve, x, y);

            ECPublicKeyParameters publicKey = new ECPublicKeyParameters("ECDH", q, SecObjectIdentifiers.SecP521r1);

            BigInteger k1 = aKeyAgree.CalculateAgreement(publicKey);

            return(k1);
        }
 public DefaultTlsAgreementCredentials(Certificate certificate, AsymmetricKeyParameter privateKey)
 {
     //IL_000e: Unknown result type (might be due to invalid IL or missing references)
     //IL_0026: Unknown result type (might be due to invalid IL or missing references)
     //IL_0034: Unknown result type (might be due to invalid IL or missing references)
     //IL_004c: Unknown result type (might be due to invalid IL or missing references)
     //IL_009f: Unknown result type (might be due to invalid IL or missing references)
     if (certificate == null)
     {
         throw new ArgumentNullException("certificate");
     }
     if (certificate.IsEmpty)
     {
         throw new ArgumentException("cannot be empty", "certificate");
     }
     if (privateKey == null)
     {
         throw new ArgumentNullException("privateKey");
     }
     if (!privateKey.IsPrivate)
     {
         throw new ArgumentException("must be private", "privateKey");
     }
     if (privateKey is DHPrivateKeyParameters)
     {
         mBasicAgreement    = new DHBasicAgreement();
         mTruncateAgreement = true;
     }
     else
     {
         if (!(privateKey is ECPrivateKeyParameters))
         {
             throw new ArgumentException("type not supported: " + Platform.GetTypeName(privateKey), "privateKey");
         }
         mBasicAgreement    = new ECDHBasicAgreement();
         mTruncateAgreement = false;
     }
     mCertificate = certificate;
     mPrivateKey  = privateKey;
 }
        public DefaultTlsAgreementCredentials(Certificate clientCertificate, AsymmetricKeyParameter clientPrivateKey)
        {
            if (clientCertificate == null)
            {
                throw new ArgumentNullException("clientCertificate");
            }
            if (clientCertificate.Length == 0)
            {
                throw new ArgumentException("cannot be empty", "clientCertificate");
            }
            if (clientPrivateKey == null)
            {
                throw new ArgumentNullException("clientPrivateKey");
            }
            if (!clientPrivateKey.IsPrivate)
            {
                throw new ArgumentException("must be private", "clientPrivateKey");
            }

            if (clientPrivateKey is DHPrivateKeyParameters)
            {
                basicAgreement = new DHBasicAgreement();
                truncateAgreement = true;
            }
            else if (clientPrivateKey is ECPrivateKeyParameters)
            {
                basicAgreement = new ECDHBasicAgreement();
                truncateAgreement = false;
            }
            else
            {
                throw new ArgumentException("type not supported: "
                    + clientPrivateKey.GetType().FullName, "clientPrivateKey");
            }

            this.clientCert = clientCertificate;
            this.clientPrivateKey = clientPrivateKey;
        }
Exemplo n.º 36
0
 public IesEngine(IBasicAgreement agree)
 {
     _agree = agree;
 }