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 virtual byte[] GenerateAgreement(AsymmetricKeyParameter serverPublicKey) { basicAgreement.Init(clientPrivateKey); BigInteger agreementValue = basicAgreement.CalculateAgreement(serverPublicKey); return(BigIntegers.AsUnsignedByteArray(agreementValue)); }
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()); }
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; }
internal AgreementCalculator(AgreementParameters parameters, IKey ecPrivateKey) { this.agreement = CDH_PROVIDER.CreateEngine(EngineUsage.GENERAL); agreement.Init(GetPrivateKeyParameters((AsymmetricECPrivateKey)ecPrivateKey)); this.parameters = parameters; }
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); /*****************************************************************************/ }
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)); }
public override byte[] GenerateAgreement(AsymmetricKeyParameter peerPublicKey) { mBasicAgreement.Init(mPrivateKey); BigInteger n = mBasicAgreement.CalculateAgreement(peerPublicKey); if (mTruncateAgreement) { return(BigIntegers.AsUnsignedByteArray(n)); } return(BigIntegers.AsUnsignedByteArray(mBasicAgreement.GetFieldSize(), n)); }
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"); // } }
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); }
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(); }
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"); } }
public byte[] ProcessBlock(byte[] input, int inOff, int inLen) { _agree.Init(_privParam); var z = _agree.CalculateAgreement(_pubParam); // TODO Check that this is right (...Unsigned? Check length?) var zBytes = z.ToByteArray(); return(this.IsForEncryption ? EncryptBlock(input, inOff, inLen, zBytes) : DecryptBlock(input, inOff, inLen, zBytes)); }
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()); }
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)); }
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); }
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"); } }
public byte[] ProcessBlock( byte[] input, int inOff, int inLen) { agree.Init(privParam); BigInteger z = agree.CalculateAgreement(pubParam); byte[] zBytes = BigIntegers.AsUnsignedByteArray(agree.GetFieldSize(), z); return(forEncryption ? EncryptBlock(input, inOff, inLen, zBytes) : DecryptBlock(input, inOff, inLen, zBytes)); }
public virtual byte[] ProcessBlock(byte[] input, int inOff, int inLen) { agree.Init(privParam); BigInteger n = agree.CalculateAgreement(pubParam); byte[] array = BigIntegers.AsUnsignedByteArray(agree.GetFieldSize(), n); try { return(forEncryption ? EncryptBlock(input, inOff, inLen, array) : DecryptBlock(input, inOff, inLen, array)); } finally { Array.Clear(array, 0, array.Length); } }
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); }
public byte[] ProcessBlock( byte[] input, int inOff, int inLen) { agree.Init(privParam); BigInteger z = agree.CalculateAgreement(pubParam); // TODO Check that this is right (...Unsigned? Check length?) byte[] zBytes = z.ToByteArray(); return(forEncryption ? EncryptBlock(input, inOff, inLen, zBytes) : DecryptBlock(input, inOff, inLen, zBytes)); }
public byte[] ProcessBlock( byte[] input, int inOff, int inLen) { agree.Init(privParam); BigInteger z = agree.CalculateAgreement(pubParam); // TODO Is a fixed length result expected? byte[] zBytes = z.ToByteArrayUnsigned(); return(forEncryption ? EncryptBlock(input, inOff, inLen, zBytes) : DecryptBlock(input, inOff, inLen, zBytes)); }
/** * 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); } }
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); }
public byte[] ProcessBlock( byte[] input, int inOff, int inLen, byte[] macData) { // Compute the common value and convert to byte array. _agreement.Init(_privParam); BigInteger zAsInteger = _agreement.CalculateAgreement(_pubParam); byte[] z = BigIntegers.AsUnsignedByteArray(_agreement.GetFieldSize(), zAsInteger); _kdfKey = _optimizedKdf.Derive(z); return(_forEncryption ? EncryptBlock(input, inOff, inLen, macData) : DecryptBlock(input, inOff, inLen, macData)); }
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)); } } }
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; } }
public byte[] ProcessBlock( byte[] input, int inOff, int inLen) //throws InvalidCipherTextException { agree.Init(privParam); BigInteger z = agree.CalculateAgreement(pubParam); if (forEncryption) { return(EncryptBlock(input, inOff, inLen, z.ToByteArray())); } else { return(DecryptBlock(input, inOff, inLen, z.ToByteArray())); } }
public byte[] ProcessBlock( byte[] input, int inOff, int inLen, byte[] macData) { // Compute the common value and convert to byte array. _agreement.Init(_privParam); BigInteger zAsInteger = _agreement.CalculateAgreement(_pubParam); byte[] z = BigIntegers.AsUnsignedByteArray(_agreement.GetFieldSize(), zAsInteger); // Create input to KDF. byte[] vz; // if (V.Length != 0) // { // VZ = new byte[V.Length + Z.Length]; // Array.Copy(V, 0, VZ, 0, V.Length); // Array.Copy(Z, 0, VZ, V.Length, Z.Length); // } // else { vz = z; } // Initialise the KDF. IDerivationParameters kdfParam; if (_kdf is Mgf1BytesGenerator) { kdfParam = new MgfParameters(vz); } else { kdfParam = new KdfParameters(vz, _iesParameters.GetDerivationV()); } _kdf.Init(kdfParam); return(_forEncryption ? EncryptBlock(input, inOff, inLen, macData) : DecryptBlock(input, inOff, inLen, macData)); }
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); }