public ElGamalKeyGenerationParameters( SecureRandom random, ElGamalParameters parameters) : base(random, parameters.P.BitLength) { this.parameters = parameters; }
public ElGamalKeyGenerationParameters( SecureRandom random, ElGamalParameters parameters) : base(random, GetStrength(parameters)) { this.parameters = parameters; }
protected bool Equals(ElGamalParameters other) { if (p.Equals(other.p) && g.Equals(other.g)) { return(l == other.l); } return(false); }
protected ElGamalKeyParameters( bool isPrivate, ElGamalParameters parameters) : base(isPrivate) { // TODO Should we allow 'parameters' to be null? this.parameters = parameters; }
internal static int GetStrength(ElGamalParameters parameters) { if (parameters.L == 0) { return(parameters.P.BitLength); } return(parameters.L); }
public ElGamalPrivateKeyParameters(BigInteger x, ElGamalParameters parameters) : base(true, parameters) { if (x == null) { throw new ArgumentNullException("x"); } this.x = x; }
public ElGamalPublicKeyParameters(BigInteger y, ElGamalParameters parameters) : base(false, parameters) { if (y == null) { throw new ArgumentNullException("y"); } this.y = y; }
public ElGamalPublicKeyParameters(IBigInteger y, ElGamalParameters parameters) : base(false, parameters) { if (y == null) throw new ArgumentNullException("y"); _y = y; }
public ElGamalPrivateKeyParameters(BigInteger x, ElGamalParameters parameters) : base(isPrivate: true, parameters) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (x == null) { throw new ArgumentNullException("x"); } this.x = x; }
public override bool Equals(object obj) { if (obj == this) { return(true); } ElGamalParameters elGamalParameters = obj as ElGamalParameters; return(elGamalParameters != null && this.Equals(elGamalParameters)); }
public ElGamalPublicKeyParameters(BigInteger y, ElGamalParameters parameters) : base(isPrivate: false, parameters) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (y == null) { throw new ArgumentNullException("y"); } this.y = y; }
public ElGamalPrivateKeyParameters( BigInteger x, ElGamalParameters parameters) : base(true, parameters) { if (x == null) throw new ArgumentNullException("x"); this.x = x; }
public override bool Equals(object obj) { if (obj == this) { return(true); } ElGamalParameters other = obj as ElGamalParameters; if (other == null) { return(false); } return(this.Equals(other)); }
public override bool Equals(object obj) { if (obj == this) { return(true); } ElGamalParameters elGamalParameters = obj as ElGamalParameters; if (elGamalParameters == null) { return(false); } return(Equals(elGamalParameters)); }
internal static int GetStrength( ElGamalParameters parameters) { return parameters.L != 0 ? parameters.L : parameters.P.BitLength; }
public void TestElGamal() { BigInteger ELGamalParaG = new BigInteger(Base64.Decode("QAZPRcsH8kHVKS5065R1Xy6QtsPvDkmDZtPuq18EJkvLrCIZivE/m5puQp3/VKJrG7dKgz4NBGpONp3HT+Cn/g==")); BigInteger ELGamalParaP = new BigInteger(Base64.Decode("AKXmAwgkudDLI/Yxk6wk3APn+mSjX5QSyDwpchmegSIi1ZNC0Jb+IbxjroKNhRTBKjtv4/JTXtJS6IqaZv9uKes=")); BigInteger ELGamalPubY = new BigInteger(Base64.Decode("AJ/gXuZuCA2X044otNkzs8FI36XuFu1L/YHg5cEmDvICTigycRN2E1DnhP+CTqxEqgEqX8rBe5tuGDlkTLwgNqM=")); BigInteger ELGamalPriv = new BigInteger(Base64.Decode("CqVr+K0TpuJKQnc76MjKhxrJzGr93jnuE3mTpth486Meymt8uWEVAQj1tGc9DTt14F9aV9WIT2oYYbvLJRcwow==")); ElGamalParameters elPara = new ElGamalParameters(ELGamalParaP, ELGamalParaG); ElGamalPrivateKeyParameters elPriv = new ElGamalPrivateKeyParameters(ELGamalPriv, elPara); ElGamalPublicKeyParameters elPub = new ElGamalPublicKeyParameters(ELGamalPubY, elPara); SubjectPublicKeyInfo subInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(elPub); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(elPriv); ElGamalPrivateKeyParameters telPriv = (ElGamalPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo); ElGamalPublicKeyParameters telPub = (ElGamalPublicKeyParameters)PublicKeyFactory.CreateKey(subInfo); // Console.WriteLine(telPriv.Equals(elPriv)); Assert.IsTrue(telPriv.Equals(elPriv), "ELGamal Private key to into back to private key."); Assert.IsTrue(telPub.Equals(elPub), "ELGamal Public key to into back to private key."); Assert.IsTrue(true, "ELGamal Test worked."); }
/// <summary> /// Extract a <c>PgpPrivateKey</c> from this secret key's encrypted contents. /// </summary> /// <param name="passPhrase"></param> /// <returns></returns> /// <exception cref="PgpException"> /// unknown public key algorithm encountered /// or /// Exception constructing key /// </exception> public IPgpPrivateKey ExtractPrivateKey(char[] passPhrase) { var secKeyData = _secret.GetSecretKeyData(); if (secKeyData == null || secKeyData.Length < 1) return null; var pubPk = _secret.PublicKeyPacket; try { var data = ExtractKeyData(passPhrase); using (var memory = new MemoryStream(data, false)) { using (var bcpgIn = BcpgInputStream.Wrap(memory)) { IAsymmetricKeyParameter privateKey; switch (pubPk.Algorithm) { case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaGeneral: case PublicKeyAlgorithmTag.RsaSign: var rsaPub = (RsaPublicBcpgKey)pubPk.Key; var rsaPriv = new RsaSecretBcpgKey(bcpgIn); var rsaPrivSpec = new RsaPrivateCrtKeyParameters( rsaPriv.Modulus, rsaPub.PublicExponent, rsaPriv.PrivateExponent, rsaPriv.PrimeP, rsaPriv.PrimeQ, rsaPriv.PrimeExponentP, rsaPriv.PrimeExponentQ, rsaPriv.CrtCoefficient); privateKey = rsaPrivSpec; break; case PublicKeyAlgorithmTag.Dsa: var dsaPub = (DsaPublicBcpgKey)pubPk.Key; var dsaPriv = new DsaSecretBcpgKey(bcpgIn); var dsaParams = new DsaParameters(dsaPub.P, dsaPub.Q, dsaPub.G); privateKey = new DsaPrivateKeyParameters(dsaPriv.X, dsaParams); break; case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: var elPub = (ElGamalPublicBcpgKey)pubPk.Key; var elPriv = new ElGamalSecretBcpgKey(bcpgIn); var elParams = new ElGamalParameters(elPub.P, elPub.G); privateKey = new ElGamalPrivateKeyParameters(elPriv.X, elParams); break; case PublicKeyAlgorithmTag.Ecdh: var ecdhPub = (ECDHPublicBcpgKey)pubPk.Key; var ecdhPriv = new ECSecretBcpgKey(bcpgIn); privateKey = new ECDHPrivateKeyParameters(ecdhPriv.X, new ECDHPublicKeyParameters(ecdhPub.Point, ecdhPub.Oid, ecdhPub.HashAlgorithm, ecdhPub.SymmetricKeyAlgorithm), PgpPublicKey.BuildFingerprint(pubPk)); break; case PublicKeyAlgorithmTag.Ecdsa: var ecdsaPub = (ECPublicBcpgKey)pubPk.Key; var ecdsaPriv = new ECSecretBcpgKey(bcpgIn); privateKey = new ECPrivateKeyParameters(pubPk.Algorithm.ToString(), ecdsaPriv.X, ecdsaPub.Oid); break; default: throw new PgpException("unknown public key algorithm encountered"); } return new PgpPrivateKey(privateKey, KeyId); } } } catch (PgpException) { throw; } catch (Exception e) { throw new PgpException("Exception constructing key", e); } }
protected bool Equals(ElGamalParameters other) { return(this.p.Equals(other.p) && this.g.Equals(other.g) && this.l == other.l); }
protected bool Equals( ElGamalParameters other) { return(p.Equals(other.p) && g.Equals(other.g) && l == other.l); }
protected bool Equals( ElGamalParameters other) { return p.Equals(other.p) && g.Equals(other.g) && l == other.l; }
public override void PerformTest() { PgpPublicKey pubKey = null; // // Read the public key // PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing); PgpPublicKeyRing pgpPub = (PgpPublicKeyRing)pgpFact.NextPgpObject(); pubKey = pgpPub.GetPublicKey(); if (pubKey.BitStrength != 1024) { Fail("failed - key strength reported incorrectly."); } // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKeyRing); PgpSecretKey secretKey = sKey.GetSecretKey(); PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass); // // signature generation // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream( cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte) ch); sGen.Update((byte) ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); // // verify Generated signature // pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed Generated signature check"); } // // test encryption // // // find a key sutiable for encryption // long pgpKeyID = 0; AsymmetricKeyParameter pKey = null; foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys()) { if (pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalEncrypt || pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalGeneral) { pKey = pgpKey.GetKey(); pgpKeyID = pgpKey.KeyId; if (pgpKey.BitStrength != 1024) { Fail("failed - key strength reported incorrectly."); } // // verify the key // } } IBufferedCipher c = CipherUtilities.GetCipher("ElGamal/None/PKCS1Padding"); c.Init(true, pKey); byte[] inBytes = Encoding.ASCII.GetBytes("hello world"); byte[] outBytes = c.DoFinal(inBytes); pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass); c.Init(false, pgpPrivKey.Key); outBytes = c.DoFinal(outBytes); if (!Arrays.AreEqual(inBytes, outBytes)) { Fail("decryption failed."); } // // encrypted message // byte[] text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'!', (byte)'\n' }; PgpObjectFactory pgpF = new PgpObjectFactory(encMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; Stream clear = encP.GetDataStream(pgpPrivKey); pgpFact = new PgpObjectFactory(clear); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); if (!ld.FileName.Equals("test.txt")) { throw new Exception("wrong filename in packet"); } Stream inLd = ld.GetDataStream(); byte[] bytes = Streams.ReadAll(inLd); if (!Arrays.AreEqual(bytes, text)) { Fail("wrong plain text in decrypted packet"); } // // signed and encrypted message // pgpF = new PgpObjectFactory(signedAndEncMessage); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; clear = encP.GetDataStream(pgpPrivKey); pgpFact = new PgpObjectFactory(clear); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; ld = (PgpLiteralData)pgpFact.NextPgpObject(); bOut = new MemoryStream(); if (!ld.FileName.Equals("test.txt")) { throw new Exception("wrong filename in packet"); } inLd = ld.GetDataStream(); // // note: we use the DSA public key here. // ops.InitVerify(pgpPub.GetPublicKey()); while ((ch = inLd.ReadByte()) >= 0) { ops.Update((byte) ch); bOut.WriteByte((byte) ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } if (!Arrays.AreEqual(bOut.ToArray(), text)) { Fail("wrong plain text in decrypted packet"); } // // encrypt // MemoryStream cbOut = new MemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.TripleDes, random); PgpPublicKey puK = sKey.GetSecretKey(pgpKeyID).PublicKey; cPk.AddMethod(puK); Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOut.ToArray().Length); cOut.Write(text, 0, text.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass); clear = encP.GetDataStream(pgpPrivKey); outBytes = Streams.ReadAll(clear); if (!Arrays.AreEqual(outBytes, text)) { Fail("wrong plain text in Generated packet"); } // // use of PgpKeyPair // BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters elParams = new ElGamalParameters(p, g); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); kpg.Init(new ElGamalKeyGenerationParameters(random, elParams)); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalGeneral , kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; // Test bug with ElGamal P size != 0 mod 8 (don't use these sizes at home!) for (int pSize = 257; pSize < 264; ++pSize) { // Generate some parameters of the given size ElGamalParametersGenerator epg = new ElGamalParametersGenerator(); epg.Init(pSize, 2, random); elParams = epg.GenerateParameters(); kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); kpg.Init(new ElGamalKeyGenerationParameters(random, elParams)); // Run a short encrypt/decrypt test with random key for the given parameters kp = kpg.GenerateKeyPair(); PgpKeyPair elGamalKeyPair = new PgpKeyPair( PublicKeyAlgorithmTag.ElGamalGeneral, kp, DateTime.UtcNow); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random); puK = elGamalKeyPair.PublicKey; cPk.AddMethod(puK); cbOut = new MemoryStream(); cOut = cPk.Open(new UncloseableStream(cbOut), text.Length); cOut.Write(text, 0, text.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = elGamalKeyPair.PrivateKey; // Note: This is where an exception would be expected if the P size causes problems clear = encP.GetDataStream(pgpPrivKey); byte[] decText = Streams.ReadAll(clear); if (!Arrays.AreEqual(text, decText)) { Fail("decrypted message incorrect"); } } // check sub key encoding foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys()) { if (!pgpKey.IsMasterKey) { byte[] kEnc = pgpKey.GetEncoded(); PgpObjectFactory objF = new PgpObjectFactory(kEnc); // TODO Make PgpPublicKey a PgpObject or return a PgpPublicKeyRing // PgpPublicKey k = (PgpPublicKey)objF.NextPgpObject(); // // pKey = k.GetKey(); // pgpKeyID = k.KeyId; // if (k.BitStrength != 1024) // { // Fail("failed - key strength reported incorrectly."); // } // // if (objF.NextPgpObject() != null) // { // Fail("failed - stream not fully parsed."); // } } } }
private void doTestEnc( int size, int privateValueSize, BigInteger g, BigInteger p) { ElGamalParameters dhParams = new ElGamalParameters(p, g, privateValueSize); ElGamalKeyGenerationParameters ekgParams = new ElGamalKeyGenerationParameters(new SecureRandom(), dhParams); ElGamalKeyPairGenerator kpGen = new ElGamalKeyPairGenerator(); kpGen.Init(ekgParams); // // generate pair // AsymmetricCipherKeyPair pair = kpGen.GenerateKeyPair(); ElGamalPublicKeyParameters pu = (ElGamalPublicKeyParameters) pair.Public; ElGamalPrivateKeyParameters pv = (ElGamalPrivateKeyParameters) pair.Private; checkKeySize(privateValueSize, pv); ElGamalEngine e = new ElGamalEngine(); e.Init(true, pu); if (e.GetOutputBlockSize() != size / 4) { Fail(size + " GetOutputBlockSize() on encryption failed."); } byte[] message = Hex.Decode("5468697320697320612074657374"); byte[] pText = message; byte[] cText = e.ProcessBlock(pText, 0, pText.Length); e.Init(false, pv); if (e.GetOutputBlockSize() != (size / 8) - 1) { Fail(size + " GetOutputBlockSize() on decryption failed."); } pText = e.ProcessBlock(cText, 0, cText.Length); if (!Arrays.AreEqual(message, pText)) { Fail(size + " bit test failed"); } e.Init(true, pu); byte[] bytes = new byte[e.GetInputBlockSize() + 2]; try { e.ProcessBlock(bytes, 0, bytes.Length); Fail("out of range block not detected"); } catch (DataLengthException) { // expected } try { bytes[0] = (byte)0xff; e.ProcessBlock(bytes, 0, bytes.Length - 1); Fail("out of range block not detected"); } catch (DataLengthException) { // expected } try { bytes[0] = (byte)0x7f; e.ProcessBlock(bytes, 0, bytes.Length - 1); } catch (DataLengthException) { Fail("in range block failed"); } }
private void doTestGP( int size, int privateValueSize, BigInteger g, BigInteger p) { IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ElGamal"); // DHParameterSpec elParams = new DHParameterSpec(p, g); // keyGen.initialize(elParams); ElGamalParameters elParams = new ElGamalParameters(p, g, privateValueSize); ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters( new SecureRandom(), elParams); keyGen.Init(elKgp); AsymmetricCipherKeyPair keyPair = keyGen.GenerateKeyPair(); SecureRandom rand = new SecureRandom(); checkKeySize(privateValueSize, keyPair); IBufferedCipher cipher = CipherUtilities.GetCipher("ElGamal"); cipher.Init(true, new ParametersWithRandom(keyPair.Public, rand)); byte[] inBytes = Encoding.ASCII.GetBytes("This is a test"); if (cipher.GetOutputSize(inBytes.Length) != (size / 8) * 2) { Fail("getOutputSize wrong on encryption"); } byte[] outBytes = cipher.DoFinal(inBytes); cipher.Init(false, keyPair.Private); if (cipher.GetOutputSize(outBytes.Length) != (size / 8) - 1) { Fail("GetOutputSize wrong on decryption"); } // // No Padding - maximum length // byte[] modBytes = ((ElGamalPublicKeyParameters)keyPair.Public).Parameters.P.ToByteArray(); byte[] maxInput = new byte[modBytes.Length - 1]; maxInput[0] |= 0x7f; cipher.Init(true, new ParametersWithRandom(keyPair.Public, rand)); outBytes = cipher.DoFinal(maxInput); cipher.Init(false, keyPair.Private); outBytes = cipher.DoFinal(outBytes); if (!AreEqual(outBytes, maxInput)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(maxInput) + " got " + Hex.ToHexString(outBytes)); } // // encrypt/decrypt // IBufferedCipher c1 = CipherUtilities.GetCipher("ElGamal"); IBufferedCipher c2 = CipherUtilities.GetCipher("ElGamal"); c1.Init(true, new ParametersWithRandom(keyPair.Public, rand)); byte[] out1 = c1.DoFinal(inBytes); c2.Init(false, keyPair.Private); byte[] out2 = c2.DoFinal(out1); if (!AreEqual(inBytes, out2)) { Fail(size + " encrypt test failed"); } // // encrypt/decrypt with update // int outLen = c1.ProcessBytes(inBytes, 0, 2, out1, 0); outLen += c1.DoFinal(inBytes, 2, inBytes.Length - 2, out1, outLen); outLen = c2.ProcessBytes(out1, 0, 2, out2, 0); outLen += c2.DoFinal(out1, 2, out1.Length - 2, out2, outLen); if (!AreEqual(inBytes, out2)) { Fail(size + " encrypt with update test failed"); } // // public key encoding test // // byte[] pubEnc = keyPair.Public.GetEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.GetInstance("ElGamal"); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // DHPublicKeyParameters pubKey = (DHPublicKeyParameters)keyFac.generatePublic(pubX509); ElGamalPublicKeyParameters pubKey = (ElGamalPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc); ElGamalParameters spec = pubKey.Parameters; if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) { Fail(size + " bit public key encoding/decoding test failed on parameters"); } if (!((ElGamalPublicKeyParameters)keyPair.Public).Y.Equals(pubKey.Y)) { Fail(size + " bit public key encoding/decoding test failed on y value"); } /* // // public key serialisation test // // TODO Is there some standard this serialization must conform to? BinaryFormatter formatter = new BinaryFormatter(); MemoryStream bOut = new MemoryStream(); // ObjectOutputStream oOut = new ObjectOutputStream(bOut); // oOut.writeObject(keyPair.Public); formatter.Serialize(bOut, keyPair.Public); MemoryStream bIn = new MemoryStream(bOut.ToArray(), false); // ObjectInputStream oIn = new ObjectInputStream(bIn); // pubKey = (DHPublicKeyParameters)oIn.readObject(); pubKey = (ElGamalPublicKeyParameters) formatter.Deserialize(bIn); spec = pubKey.Parameters; if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) { Fail(size + " bit public key serialisation test failed on parameters"); } if (!((ElGamalPublicKeyParameters )keyPair.Public).Y.Equals(pubKey.Y)) { Fail(size + " bit public key serialisation test failed on y value"); } */ // // private key encoding test // // TODO Keys don't support GetEncoded // byte[] privEnc = keyPair.Private.GetEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // DHPrivateKeyParameters privKey = (DHPrivateKeyParameters)keyFac.generatePrivate(privPKCS8); ElGamalPrivateKeyParameters privKey = (ElGamalPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc); spec = privKey.Parameters; if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) { Fail(size + " bit private key encoding/decoding test failed on parameters"); } if (!((ElGamalPrivateKeyParameters)keyPair.Private).X.Equals(privKey.X)) { Fail(size + " bit private key encoding/decoding test failed on y value"); } /* // // private key serialisation test // bOut = new MemoryStream(); // oOut = new ObjectOutputStream(bOut); // oOut.writeObject(keyPair.Private); formatter.Serialize(bOut, keyPair.Private); bIn = new MemoryStream(bOut.ToArray(), false); // oIn = new ObjectInputStream(bIn); // privKey = (DHPrivateKeyParameters)oIn.readObject(); privKey = (ElGamalPrivateKeyParameters) formatter.Deserialize(bIn); spec = privKey.Parameters; if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) { Fail(size + " bit private key serialisation test failed on parameters"); } if (!((ElGamalPrivateKeyParameters) keyPair.Private).X.Equals(privKey.X)) { Fail(size + " bit private key serialisation test failed on y value"); } */ }
internal PgpPrivateKey DoExtractPrivateKey(byte[] rawPassPhrase, bool clearPassPhrase) { if (IsPrivateKeyEmpty) return null; PublicKeyPacket pubPk = secret.PublicKeyPacket; try { byte[] data = ExtractKeyData(rawPassPhrase, clearPassPhrase); BcpgInputStream bcpgIn = BcpgInputStream.Wrap(new MemoryStream(data, false)); AsymmetricKeyParameter privateKey; switch (pubPk.Algorithm) { case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaGeneral: case PublicKeyAlgorithmTag.RsaSign: RsaPublicBcpgKey rsaPub = (RsaPublicBcpgKey)pubPk.Key; RsaSecretBcpgKey rsaPriv = new RsaSecretBcpgKey(bcpgIn); RsaPrivateCrtKeyParameters rsaPrivSpec = new RsaPrivateCrtKeyParameters( rsaPriv.Modulus, rsaPub.PublicExponent, rsaPriv.PrivateExponent, rsaPriv.PrimeP, rsaPriv.PrimeQ, rsaPriv.PrimeExponentP, rsaPriv.PrimeExponentQ, rsaPriv.CrtCoefficient); privateKey = rsaPrivSpec; break; case PublicKeyAlgorithmTag.Dsa: DsaPublicBcpgKey dsaPub = (DsaPublicBcpgKey)pubPk.Key; DsaSecretBcpgKey dsaPriv = new DsaSecretBcpgKey(bcpgIn); DsaParameters dsaParams = new DsaParameters(dsaPub.P, dsaPub.Q, dsaPub.G); privateKey = new DsaPrivateKeyParameters(dsaPriv.X, dsaParams); break; case PublicKeyAlgorithmTag.ECDH: privateKey = GetECKey("ECDH", bcpgIn); break; case PublicKeyAlgorithmTag.ECDsa: privateKey = GetECKey("ECDSA", bcpgIn); break; case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: ElGamalPublicBcpgKey elPub = (ElGamalPublicBcpgKey)pubPk.Key; ElGamalSecretBcpgKey elPriv = new ElGamalSecretBcpgKey(bcpgIn); ElGamalParameters elParams = new ElGamalParameters(elPub.P, elPub.G); privateKey = new ElGamalPrivateKeyParameters(elPriv.X, elParams); break; default: throw new PgpException("unknown public key algorithm encountered"); } return new PgpPrivateKey(KeyId, pubPk, privateKey); } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception constructing key", e); } }
public void TestInvalidP() { ElGamalParameters dhParams = new ElGamalParameters(pPgpBogusPSamp, gPgpBogusPSamp, lPgpBogusPSamp); ElGamalPublicKeyParameters pu = new ElGamalPublicKeyParameters(yPgpBogusPSamp, dhParams); ElGamalPrivateKeyParameters pv = new ElGamalPrivateKeyParameters(xPgpBogusPSamp, dhParams); ElGamalEngine e = new ElGamalEngine(); e.Init(true, pu); byte[] message = Hex.Decode("5468697320697320612074657374"); byte[] pText = message; byte[] cText = e.ProcessBlock(pText, 0, pText.Length); e.Init(false, pv); pText = e.ProcessBlock(cText, 0, cText.Length); if (Arrays.AreEqual(message, pText)) { Fail("invalid test failed"); } }
public static int Main( string[] args) { if (args.Length < 2) { Console.WriteLine("DsaElGamalKeyRingGenerator [-a] identity passPhrase"); return 0; } IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(1024, 80, new SecureRandom()); DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); dsaKpg.Init(kgp); // // this takes a while as the key generator has to Generate some DSA parameters // before it Generates the key. // AsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters elParams = new ElGamalParameters(p, g); ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams); elgKpg.Init(elKgp); // // this is quicker because we are using preGenerated parameters. // AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair(); Stream out1, out2; if (args[0].Equals("-a")) { if (args.Length < 3) { Console.WriteLine("DSAElGamalKeyRingGenerator [-a] identity passPhrase"); return 0; } out1 = File.Create("secret.asc"); out2 = File.Create("pub.asc"); ExportKeyPair(out1, out2, dsaKp, elgKp, args[1], args[2].ToCharArray(), true); } else { out1 = File.Create("secret.bpg"); out2 = File.Create("pub.bpg"); ExportKeyPair(out1, out2, dsaKp, elgKp, args[0], args[1].ToCharArray(), false); } out1.Close(); out2.Close(); return 0; }
internal static int GetStrength(ElGamalParameters parameters) => ((parameters.L == 0) ? parameters.P.BitLength : parameters.L);
protected bool Equals(ElGamalParameters other) => ((this.p.Equals(other.p) && this.g.Equals(other.g)) && (this.l == other.l));
/// <summary>Extract a <c>PgpPrivateKey</c> from this secret key's encrypted contents.</summary> public PgpPrivateKey ExtractPrivateKey( char[] passPhrase) { byte[] secKeyData = secret.GetSecretKeyData(); if (secKeyData == null || secKeyData.Length < 1) return null; PublicKeyPacket pubPk = secret.PublicKeyPacket; try { byte[] data = ExtractKeyData(passPhrase); BcpgInputStream bcpgIn = BcpgInputStream.Wrap(new MemoryStream(data, false)); AsymmetricKeyParameter privateKey; switch (pubPk.Algorithm) { case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaGeneral: case PublicKeyAlgorithmTag.RsaSign: RsaPublicBcpgKey rsaPub = (RsaPublicBcpgKey)pubPk.Key; RsaSecretBcpgKey rsaPriv = new RsaSecretBcpgKey(bcpgIn); RsaPrivateCrtKeyParameters rsaPrivSpec = new RsaPrivateCrtKeyParameters( rsaPriv.Modulus, rsaPub.PublicExponent, rsaPriv.PrivateExponent, rsaPriv.PrimeP, rsaPriv.PrimeQ, rsaPriv.PrimeExponentP, rsaPriv.PrimeExponentQ, rsaPriv.CrtCoefficient); privateKey = rsaPrivSpec; break; case PublicKeyAlgorithmTag.Dsa: DsaPublicBcpgKey dsaPub = (DsaPublicBcpgKey)pubPk.Key; DsaSecretBcpgKey dsaPriv = new DsaSecretBcpgKey(bcpgIn); DsaParameters dsaParams = new DsaParameters(dsaPub.P, dsaPub.Q, dsaPub.G); privateKey = new DsaPrivateKeyParameters(dsaPriv.X, dsaParams); break; case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: ElGamalPublicBcpgKey elPub = (ElGamalPublicBcpgKey)pubPk.Key; ElGamalSecretBcpgKey elPriv = new ElGamalSecretBcpgKey(bcpgIn); ElGamalParameters elParams = new ElGamalParameters(elPub.P, elPub.G); privateKey = new ElGamalPrivateKeyParameters(elPriv.X, elParams); break; default: throw new PgpException("unknown public key algorithm encountered"); } return new PgpPrivateKey(privateKey, KeyId); } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception constructing key", e); } }
private void doTestRandom( int size) { // AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("ElGamal"); // a.init(size, new SecureRandom()); ElGamalParametersGenerator a = new ElGamalParametersGenerator(); a.Init(size, 20, new SecureRandom()); // AlgorithmParameters parameters = a.generateParameters(); ElGamalParameters p = a.GenerateParameters(); // byte[] encodeParams = parameters.GetEncoded(); byte[] encodeParams = new ElGamalParameter(p.P, p.G).GetDerEncoded(); // AlgorithmParameters a2 = AlgorithmParameters.getInstance("ElGamal"); // a2.init(encodeParams); ElGamalParameter elP = new ElGamalParameter((Asn1Sequence) Asn1Object.FromByteArray(encodeParams)); ElGamalParameters p2 = new ElGamalParameters(elP.P, elP.G); // a and a2 should be equivalent! // byte[] encodeParams_2 = a2.GetEncoded(); byte[] encodeParams_2 = new ElGamalParameter(p2.P, p2.G).GetDerEncoded(); if (!AreEqual(encodeParams, encodeParams_2)) { Fail(this.Name + ": encode/decode parameters failed"); } // DHParameters elP = (DHParameters)parameters.getParameterSpec(typeof(DHParameters)); doTestGP(size, 0, elP.G, elP.P); }
public void TestElGamal() { BigInteger g512 = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); BigInteger p512 = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters dhParams = new ElGamalParameters(p512, g512); ElGamalKeyGenerationParameters parameters = new ElGamalKeyGenerationParameters(new SecureRandom(), dhParams); ElGamalKeyPairGenerator kpGen = new ElGamalKeyPairGenerator(); kpGen.Init(parameters); AsymmetricCipherKeyPair pair = kpGen.GenerateKeyPair(); ElGamalPublicKeyParameters pu1 = (ElGamalPublicKeyParameters)pair.Public; ElGamalPrivateKeyParameters pv1 = (ElGamalPrivateKeyParameters)pair.Private; ElGamalPublicKeyParameters pu2 = new ElGamalPublicKeyParameters(pu1.Y, pu1.Parameters); ElGamalPrivateKeyParameters pv2 = new ElGamalPrivateKeyParameters(pv1.X, pv1.Parameters); ElGamalPublicKeyParameters pu3 = new ElGamalPublicKeyParameters(pv1.X, pu1.Parameters); ElGamalPrivateKeyParameters pv3 = new ElGamalPrivateKeyParameters(pu1.Y, pu1.Parameters); doTest(pu1, pu2, pu3); doTest(pv1, pv2, pv3); ElGamalParameters pr1 = pu1.Parameters; ElGamalParameters pr2 = new ElGamalParameters(pr1.P, pr1.G); ElGamalParameters pr3 = new ElGamalParameters(pr1.G, pr1.P); doTest(pr1, pr2, pr3); pu2 = new ElGamalPublicKeyParameters(pu1.Y, pr2); pv2 = new ElGamalPrivateKeyParameters(pv1.X, pr2); doTest(pu1, pu2, pu3); doTest(pv1, pv2, pv3); ElGamalTestKeyParameters k1 = new ElGamalTestKeyParameters(false, null); ElGamalTestKeyParameters k2 = new ElGamalTestKeyParameters(false, null); ElGamalTestKeyParameters k3 = new ElGamalTestKeyParameters(false, pu1.Parameters); doTest(k1, k2, k3); }
public ElGamalTestKeyParameters( bool isPrivate, ElGamalParameters parameters) : base(isPrivate, parameters) { }
public void GenerateTest() { char[] passPhrase = "hello".ToCharArray(); DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters dsaKgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); dsaKpg.Init(dsaKgp); // // this takes a while as the key generator has to Generate some DSA parameters // before it Generates the key. // AsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters elParams = new ElGamalParameters(p, g); ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams); elgKpg.Init(elKgp); // // this is quicker because we are using preGenerated parameters. // AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair(); PgpKeyPair dsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, dsaKp, DateTime.UtcNow); PgpKeyPair elgKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalEncrypt, elgKp, DateTime.UtcNow); PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, dsaKeyPair, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, new SecureRandom()); keyRingGen.AddSubKey(elgKeyPair); PgpSecretKeyRing keyRing = keyRingGen.GenerateSecretKeyRing(); keyRing.GetSecretKey().ExtractPrivateKey(passPhrase); PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing(); PgpPublicKey vKey = null; PgpPublicKey sKey = null; foreach (PgpPublicKey pk in pubRing.GetPublicKeys()) { if (pk.IsMasterKey) { vKey = pk; } else { sKey = pk; } } foreach (PgpSignature sig in sKey.GetSignatures()) { if (sig.KeyId == vKey.KeyId && sig.SignatureType == PgpSignature.SubkeyBinding) { sig.InitVerify(vKey); if (!sig.VerifyCertification(vKey, sKey)) { Fail("failed to verify sub-key signature."); } } } }
internal static int GetStrength( ElGamalParameters parameters) { return(parameters.L != 0 ? parameters.L : parameters.P.BitLength); }
protected ElGamalKeyParameters(bool isPrivate, ElGamalParameters parameters) : base(isPrivate) { this.parameters = parameters; }