/// <summary> /// Initializes a new instance of the <see cref="KeyGenerator"/> class /// with the specified key size. /// </summary> /// <remarks>Following key sizes are supported: /// - 192 /// - 224 /// - 239 /// - 256 (default) /// - 384 /// - 521</remarks> /// <param name="keySize">The key size.</param> public KeyGenerator(int keySize) { var secureRandom = SecureRandom.GetInstance("SHA256PRNG"); var keyParams = new KeyGenerationParameters(secureRandom, keySize); keyGenerator = new ECKeyPairGenerator(); keyGenerator.Init(keyParams); }
public KeyAgreement() { _curve = new FpCurve( new BigInteger("BDB6F4FE3E8B1D9E0DA8C0D46F4C318CEFE4AFE3B6B8551F", 16), // q new BigInteger("BB8E5E8FBC115E139FE6A814FE48AAA6F0ADA1AA5DF91985", 16), // a new BigInteger("1854BEBDC31B21B7AEFC80AB0ECD10D5B1B3308E6DBF11C1", 16) // b ); _ecSpec = new ECDomainParameters( _curve, new FpPoint(_curve, new FpFieldElement( _curve.Q, new BigInteger("4AD5F7048DE709AD51236DE65E4D4B482C836DC6E4106640", 16) ), new FpFieldElement( _curve.Q, new BigInteger("02BB3A02D4AAADACAE24817A4CA3A1B014B5270432DB27D2", 16)) ), // G new BigInteger("BDB6F4FE3E8B1D9E0DA8C0D40FC962195DFAE76F56564677", 16), // n BigInteger.One// h ); _keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH"); _keyGen.Init(new ECKeyGenerationParameters(_ecSpec, new SecureRandom())); }
static TspTestUtil() { rand = new SecureRandom(); kpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpg.Init(new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), rand, 1024, 25)); desede128kg = GeneratorUtilities.GetKeyGenerator("DESEDE"); desede128kg.Init(new KeyGenerationParameters(rand, 112)); desede192kg = GeneratorUtilities.GetKeyGenerator("DESEDE"); desede192kg.Init(new KeyGenerationParameters(rand, 168)); rc240kg = GeneratorUtilities.GetKeyGenerator("RC2"); rc240kg.Init(new KeyGenerationParameters(rand, 40)); rc264kg = GeneratorUtilities.GetKeyGenerator("RC2"); rc264kg.Init(new KeyGenerationParameters(rand, 64)); rc2128kg = GeneratorUtilities.GetKeyGenerator("RC2"); rc2128kg.Init(new KeyGenerationParameters(rand, 128)); serialNumber = BigInteger.One; }
/// <summary> /// Generate a key pair. /// </summary> /// <param name="keygen">an instance of IAsymmetricCipherKeyPairGenerator</param> /// <param name="keySize">iKeySize Key size of key pair</param> /// <param name="random">an instance of IRandomGenerator</param> /// <returns>A key pair</returns> public static AsymmetricCipherKeyPair GenerateKeyPair(IAsymmetricCipherKeyPairGenerator keygen, int keySize, IRandomGenerator random) { // Create a SecureRandom var rand = new SecureRandom(random); // Initialize key pair generator with key strength and a randomness keygen.Init(new KeyGenerationParameters(rand, keySize)); // Generate and return the key pair return keygen.GenerateKeyPair(); }
static OcspTestUtil() { rand = new SecureRandom(); // kpg = KeyPairGenerator.GetInstance("RSA"); // kpg.initialize(1024, rand); kpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpg.Init(new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), rand, 1024, 25)); serialNumber = BigInteger.One; ecKpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); ecKpg.Init(new KeyGenerationParameters(rand, 192)); }
public void TestGeneration() { ISigner s = SignerUtilities.GetSigner("DSA"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; SecureRandom rand = new SecureRandom(); // KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA"); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA"); // test exception // doTestBadStrength(513); doTestBadStrength(510); doTestBadStrength(1025); //g.initialize(512, rand); { DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, rand); g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters())); } IAsymmetricCipherKeyPair p = g.GenerateKeyPair(); IAsymmetricKeyParameter sKey = p.Private; IAsymmetricKeyParameter vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); byte[] sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("DSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("DSA verification failed"); } // // ECDSA Fp generation test // s = SignerUtilities.GetSigner("ECDSA"); ECCurve curve = new FPCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecSpec = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); g.Init(new ECKeyGenerationParameters(ecSpec, rand)); p = g.GenerateKeyPair(); sKey = p.Private; vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("ECDSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("ECDSA verification failed"); } // // ECDSA F2m generation test // s = SignerUtilities.GetSigner("ECDSA"); curve = new F2MCurve( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ecSpec = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.ValueOf(4)); // h g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); g.Init(new ECKeyGenerationParameters(ecSpec, rand)); p = g.GenerateKeyPair(); sKey = p.Private; vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("ECDSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("ECDSA verification failed"); } }
public void doTest( IAsymmetricCipherKeyPairGenerator g, IBufferedCipher c1, IBufferedCipher c2) { // // a side // IAsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); IAsymmetricKeyParameter aPub = aKeyPair.Public; IAsymmetricKeyParameter aPriv = aKeyPair.Private; // // b side // IAsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); IAsymmetricKeyParameter bPub = bKeyPair.Public; IAsymmetricKeyParameter bPriv = bKeyPair.Private; // TODO Put back in // // // // stream test // // // IEKeySpec c1Key = new IEKeySpec(aPriv, bPub); // IEKeySpec c2Key = new IEKeySpec(bPriv, aPub); // // byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; // byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; // // IESParameterSpec param = new IESParameterSpec(d, e, 128); // // c1.Init(true, c1Key, param); // // c2.Init(false, c2Key, param); // // byte[] message = Hex.Decode("1234567890abcdef"); // // byte[] out1 = c1.DoFinal(message, 0, message.Length); // // byte[] out2 = c2.DoFinal(out1, 0, out1.Length); // // if (!AreEqual(out2, message)) // { // Fail("stream cipher test failed"); // } }
public void doDefTest( IAsymmetricCipherKeyPairGenerator g, IBufferedCipher c1, IBufferedCipher c2) { // // a side // AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); AsymmetricKeyParameter aPub = aKeyPair.Public; AsymmetricKeyParameter aPriv = aKeyPair.Private; // // b side // AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); AsymmetricKeyParameter bPub = bKeyPair.Public; AsymmetricKeyParameter bPriv = bKeyPair.Private; // TODO Put back in // // // // stream test // // // IEKeySpec c1Key = new IEKeySpec(aPriv, bPub); // IEKeySpec c2Key = new IEKeySpec(bPriv, aPub); // // c1.Init(true, c1Key); // // AlgorithmParameters param = c1.getParameters(); // // c2.Init(false, c2Key, param); // // byte[] message = Hex.Decode("1234567890abcdef"); // // byte[] out1 = c1.DoFinal(message, 0, message.Length); // // byte[] out2 = c2.DoFinal(out1, 0, out1.Length); // // if (!AreEqual(out2, message)) // { // Fail("stream cipher test failed"); // } // // // // // int DoFinal // // // int len1 = c1.DoFinal(message, 0, message.Length, out1, 0); // // if (len1 != out1.Length) // { // Fail("encryption length wrong"); // } // // int len2 = c2.DoFinal(out1, 0, out1.Length, out2, 0); // // if (len2 != out2.Length) // { // Fail("decryption length wrong"); // } // // if (!AreEqual(out2, message)) // { // Fail("stream cipher test failed"); // } // // // // // int DoFinal with update // // // len1 = c1.ProcessBytes(message, 0, 2, out1, 0); // // len1 += c1.DoFinal(message, 2, message.Length - 2, out1, len1); // // if (len1 != out1.Length) // { // Fail("update encryption length wrong"); // } // // len2 = c2.ProcessBytes(out1, 0, 2, out2, 0); // // len2 += c2.DoFinal(out1, 2, out1.Length - 2, out2, len2); // // if (len2 != out2.Length) // { // Fail("update decryption length wrong"); // } // // if (!AreEqual(out2, message)) // { // Fail("update stream cipher test failed"); // } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); const string Algorithm = "ECDH"; //What do you think about the other algorithms? const int KeyBitSize = 2056; const int NonceBitSize = 128; const int MacBitSize = 128; const int DefaultPrimeProbability = 30; //BEGIN SETUP ALICE IAsymmetricCipherKeyPairGenerator aliceKeyGen = GeneratorUtilities.GetKeyPairGenerator(Algorithm); DHParametersGenerator aliceGenerator = new DHParametersGenerator(); aliceGenerator.Init(KeyBitSize, DefaultPrimeProbability, new SecureRandom()); DHParameters aliceParameters = aliceGenerator.GenerateParameters(); KeyGenerationParameters aliceKGP = new DHKeyGenerationParameters(new SecureRandom(), aliceParameters); aliceKeyGen.Init(aliceKGP); AsymmetricCipherKeyPair aliceKeyPair = aliceKeyGen.GenerateKeyPair(); IBasicAgreement aliceKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm); aliceKeyAgree.Init(aliceKeyPair.Private); Button a1b = FindViewById <Button>(Resource.Id.a1b); TextView AliceRandomText = FindViewById <TextView>(Resource.Id.a1t); Button a2b = FindViewById <Button>(Resource.Id.a2b); TextView AlicePrivateKeyText = FindViewById <TextView>(Resource.Id.a2t); Button a3b = FindViewById <Button>(Resource.Id.a3b); TextView AlicePublicKeyText = FindViewById <TextView>(Resource.Id.a3t); Button b1b = FindViewById <Button>(Resource.Id.b1b); TextView BobRandomText = FindViewById <TextView>(Resource.Id.b1t); Button b2b = FindViewById <Button>(Resource.Id.b2b); TextView BobPrivateKeyText = FindViewById <TextView>(Resource.Id.b2t); Button b3b = FindViewById <Button>(Resource.Id.b3b); TextView BobPublicKeyText = FindViewById <TextView>(Resource.Id.b3t); Button a4b = FindViewById <Button>(Resource.Id.a4b); TextView AliceBobSharedKeyText = FindViewById <TextView>(Resource.Id.a4t); Button b4b = FindViewById <Button>(Resource.Id.b4b); TextView BobAliceSharedKeyText = FindViewById <TextView>(Resource.Id.b4t); // what Alice does byte[] aliceRandomBytes = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(aliceRandomBytes); byte[] alicePrivate = Curve25519.(aliceRandomBytes); byte[] alicePublic = Curve25519.GetPublicKey(alicePrivate); // what Bob does byte[] bobRandomBytes = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(bobRandomBytes); byte[] bobPrivate = Curve25519.ClampPrivateKey(bobRandomBytes); byte[] bobPublic = Curve25519.GetPublicKey(bobPrivate); // what Alice does with Bob's public key byte[] aliceShared = Curve25519.GetSharedSecret(alicePrivate, bobPublic); // what Bob does with Alice' public key byte[] bobShared = Curve25519.GetSharedSecret(bobPrivate, alicePublic); // aliceShared == bobShared a1b.Click += delegate { alicePrivateBytes = null; AlicePrivateKeyText.Text = ""; alicePublicBytes = null; AlicePublicKeyText.Text = ""; aliceBobSharedBytes = null; bobAliceSharedBytes = null; AliceBobSharedKeyText.Text = ""; BobAliceSharedKeyText.Text = ""; aliceRandomBytes = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(aliceRandomBytes); AliceRandomText.Text = BitConverter.ToString(aliceRandomBytes).Replace("-", ""); }; a2b.Click += delegate { if (aliceRandomBytes != null) { alicePrivateBytes = Curve25519.Create(aliceRandomBytes); AlicePrivateKeyText.Text = BitConverter.ToString(alicePrivateBytes).Replace("-", ""); } }; a3b.Click += delegate { if (alicePrivateBytes != null) { alicePublicBytes = Curve25519.GetPublicKey(alicePrivateBytes); AlicePublicKeyText.Text = BitConverter.ToString(alicePublicBytes).Replace("-", ""); } }; b1b.Click += delegate { bobPrivateBytes = null; BobPrivateKeyText.Text = ""; // Reset bobPublicBytes = null; BobPublicKeyText.Text = ""; // Reset aliceBobSharedBytes = null; bobAliceSharedBytes = null; AliceBobSharedKeyText.Text = ""; BobAliceSharedKeyText.Text = ""; bobRandomBytes = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(bobRandomBytes); BobRandomText.Text = BitConverter.ToString(bobRandomBytes).Replace("-", ""); }; b2b.Click += delegate { if (bobRandomBytes != null) { bobPrivateBytes = Curve25519.ClampPrivateKey(bobRandomBytes); BobPrivateKeyText.Text = BitConverter.ToString(bobPrivateBytes).Replace("-", ""); } }; b3b.Click += delegate { if (bobPrivateBytes != null) { bobPublicBytes = Curve25519.GetPublicKey(bobPrivateBytes); BobPublicKeyText.Text = BitConverter.ToString(bobPublicBytes).Replace("-", ""); } }; a4b.Click += delegate { if ((alicePrivateBytes != null) && (bobPublicBytes != null)) { aliceBobSharedBytes = Curve25519.GetSharedSecret(alicePrivateBytes, bobPublicBytes); AliceBobSharedKeyText.Text = BitConverter.ToString(aliceBobSharedBytes).Replace("-", ""); } }; b4b.Click += delegate { if ((bobPrivateBytes != null) && (alicePublicBytes != null)) { bobAliceSharedBytes = Curve25519.GetSharedSecret(bobPrivateBytes, alicePublicBytes); BobAliceSharedKeyText.Text = BitConverter.ToString(bobAliceSharedBytes).Replace("-", ""); } }; }
private byte[] EncryptSessionInfo(byte[] sessionInfo, SecureRandom random) { if (pubKey.Algorithm != PublicKeyAlgorithmTag.ECDH) { IBufferedCipher c; switch (pubKey.Algorithm) { case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaGeneral: c = CipherUtilities.GetCipher("RSA//PKCS1Padding"); break; case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: c = CipherUtilities.GetCipher("ElGamal/ECB/PKCS1Padding"); break; case PublicKeyAlgorithmTag.Dsa: throw new PgpException("Can't use DSA for encryption."); case PublicKeyAlgorithmTag.ECDsa: throw new PgpException("Can't use ECDSA for encryption."); default: throw new PgpException("unknown asymmetric algorithm: " + pubKey.Algorithm); } AsymmetricKeyParameter akp = pubKey.GetKey(); c.Init(true, new ParametersWithRandom(akp, random)); return(c.DoFinal(sessionInfo)); } ECDHPublicBcpgKey ecKey = (ECDHPublicBcpgKey)pubKey.PublicKeyPacket.Key; // Generate the ephemeral key pair IAsymmetricCipherKeyPairGenerator gen = GeneratorUtilities.GetKeyPairGenerator("ECDH"); gen.Init(new ECKeyGenerationParameters(ecKey.CurveOid, random)); AsymmetricCipherKeyPair ephKp = gen.GenerateKeyPair(); ECPrivateKeyParameters ephPriv = (ECPrivateKeyParameters)ephKp.Private; ECPublicKeyParameters ephPub = (ECPublicKeyParameters)ephKp.Public; ECPublicKeyParameters pub = (ECPublicKeyParameters)pubKey.GetKey(); ECPoint S = pub.Q.Multiply(ephPriv.D).Normalize(); KeyParameter key = new KeyParameter(Rfc6637Utilities.CreateKey(pubKey.PublicKeyPacket, S)); IWrapper w = PgpUtilities.CreateWrapper(ecKey.SymmetricKeyAlgorithm); w.Init(true, new ParametersWithRandom(key, random)); byte[] paddedSessionData = PgpPad.PadSessionData(sessionInfo); byte[] C = w.Wrap(paddedSessionData, 0, paddedSessionData.Length); byte[] VB = new MPInteger(new BigInteger(1, ephPub.Q.GetEncoded(false))).GetEncoded(); byte[] rv = new byte[VB.Length + 1 + C.Length]; Array.Copy(VB, 0, rv, 0, VB.Length); rv[VB.Length] = (byte)C.Length; Array.Copy(C, 0, rv, VB.Length + 1, C.Length); return(rv); }
public void doTestECGost( string name) { // ECGenParameterSpec ecSpec = new ECGenParameterSpec(name); ECDomainParameters ecSpec = GetCurveParameters(name); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410"); // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); ISigner sgr = SignerUtilities.GetSigner("ECGOST3410"); AsymmetricCipherKeyPair pair = g.GenerateKeyPair(); AsymmetricKeyParameter sKey = pair.Private; AsymmetricKeyParameter vKey = pair.Public; sgr.Init(true, sKey); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.BlockUpdate(message, 0, message.Length); byte[] sigBytes = sgr.GenerateSignature(); sgr.Init(false, vKey); sgr.BlockUpdate(message, 0, message.Length); if (!sgr.VerifySignature(sigBytes)) { Fail(name + " verification failed"); } // TODO Get this working? // // // // public key encoding test // // //// byte[] pubEnc = vKey.getEncoded(); // byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded(); // //// KeyFactory keyFac = KeyFactory.getInstance("ECGOST3410"); //// X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); //// ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509); // ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc); // //// if (!pubKey.getW().equals(((ECPublicKey)vKey).getW())) // if (!pubKey.Q.Equals(((ECPublicKeyParameters)vKey).Q)) // { // Fail("public key encoding (Q test) failed"); // } // TODO Put back in? // if (!(pubKey.Parameters is ECNamedCurveSpec)) // { // Fail("public key encoding not named curve"); // } // TODO Get this working? // // // // private key encoding test // // //// byte[] privEnc = sKey.getEncoded(); // byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded(); // //// PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); //// ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8); // ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc); // //// if (!privKey.getS().Equals(((ECPrivateKey)sKey).getS())) // if (!privKey.D.Equals(((ECPrivateKeyParameters)sKey).D)) // { // Fail("GOST private key encoding (D test) failed"); // } // TODO Put back in? // if (!(privKey.Parameters is ECNamedCurveSpec)) // { // Fail("GOST private key encoding not named curve"); // } // // ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams(); // if (!privSpec.getName().equalsIgnoreCase(name) // && !privSpec.getName().equalsIgnoreCase((String)CURVE_ALIASES[name])) // { // Fail("GOST private key encoding wrong named curve. Expected: " + name + " got " + privSpec.getName()); // } }
private void GenerateAndSign() { SecureRandom random = SecureRandom.GetInstance("SHA1PRNG"); IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random)); AsymmetricCipherKeyPair kpSign = keyGen.GenerateKeyPair(); PgpKeyPair ecdsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDsa, kpSign, DateTime.UtcNow); byte[] msg = Encoding.ASCII.GetBytes("hello world!"); // // try a signature // PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256); signGen.InitSign(PgpSignature.BinaryDocument, ecdsaKeyPair.PrivateKey); signGen.Update(msg); PgpSignature sig = signGen.Generate(); sig.InitVerify(ecdsaKeyPair.PublicKey); sig.Update(msg); if (!sig.Verify()) { Fail("signature failed to verify!"); } // // generate a key ring // char[] passPhrase = "test".ToCharArray(); PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, ecdsaKeyPair, "*****@*****.**", SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, random); PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing(); PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing(); PgpPublicKeyRing pubRingEnc = new PgpPublicKeyRing(pubRing.GetEncoded()); if (!Arrays.AreEqual(pubRing.GetEncoded(), pubRingEnc.GetEncoded())) { Fail("public key ring encoding failed"); } PgpSecretKeyRing secRingEnc = new PgpSecretKeyRing(secRing.GetEncoded()); if (!Arrays.AreEqual(secRing.GetEncoded(), secRingEnc.GetEncoded())) { Fail("secret key ring encoding failed"); } // // try a signature using encoded key // signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256); signGen.InitSign(PgpSignature.BinaryDocument, secRing.GetSecretKey().ExtractPrivateKey(passPhrase)); signGen.Update(msg); sig = signGen.Generate(); sig.InitVerify(secRing.GetSecretKey().PublicKey); sig.Update(msg); if (!sig.Verify()) { Fail("re-encoded signature failed to verify!"); } }
private void doTestGP( string algName, int size, int privateValueSize, BigInteger g, BigInteger p) { IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator(algName); DHParameters dhParams = new DHParameters(p, g, null, privateValueSize); KeyGenerationParameters kgp = new DHKeyGenerationParameters(new SecureRandom(), dhParams); keyGen.Init(kgp); // // a side // AsymmetricCipherKeyPair aKeyPair = keyGen.GenerateKeyPair(); IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName); checkKeySize(privateValueSize, aKeyPair); aKeyAgreeBasic.Init(aKeyPair.Private); // // b side // AsymmetricCipherKeyPair bKeyPair = keyGen.GenerateKeyPair(); IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName); checkKeySize(privateValueSize, bKeyPair); bKeyAgreeBasic.Init(bKeyPair.Private); // // agreement // // aKeyAgreeBasic.doPhase(bKeyPair.Public, true); // bKeyAgreeBasic.doPhase(aKeyPair.Public, true); // // BigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret()); // BigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret()); BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public); BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public); if (!k1.Equals(k2)) { Fail(size + " bit 2-way test failed"); } // // public key encoding test // // byte[] pubEnc = aKeyPair.Public.GetEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.getInstance(algName); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // DHPublicKey pubKey = (DHPublicKey)keyFac.generatePublic(pubX509); DHPublicKeyParameters pubKey = (DHPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc); // DHParameterSpec spec = pubKey.Parameters; DHParameters spec = pubKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit public key encoding/decoding test failed on parameters"); } if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y)) { Fail(size + " bit public key encoding/decoding test failed on y value"); } // // public key serialisation test // // TODO Put back in // MemoryStream bOut = new MemoryStream(); // ObjectOutputStream oOut = new ObjectOutputStream(bOut); // // oOut.WriteObject(aKeyPair.Public); // // MemoryStream bIn = new MemoryStream(bOut.ToArray(), false); // ObjectInputStream oIn = new ObjectInputStream(bIn); // // pubKey = (DHPublicKeyParameters)oIn.ReadObject(); spec = pubKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit public key serialisation test failed on parameters"); } if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y)) { Fail(size + " bit public key serialisation test failed on y value"); } // // private key encoding test // // byte[] privEnc = aKeyPair.Private.GetEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // DHPrivateKeyParameters privKey = (DHPrivateKey)keyFac.generatePrivate(privPKCS8); DHPrivateKeyParameters privKey = (DHPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc); spec = privKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit private key encoding/decoding test failed on parameters"); } if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X)) { Fail(size + " bit private key encoding/decoding test failed on y value"); } // // private key serialisation test // // TODO Put back in // bOut = new MemoryStream(); // oOut = new ObjectOutputStream(bOut); // // oOut.WriteObject(aKeyPair.Private); // // bIn = new MemoryStream(bOut.ToArray(), false); // oIn = new ObjectInputStream(bIn); // // privKey = (DHPrivateKeyParameters)oIn.ReadObject(); spec = privKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit private key serialisation test failed on parameters"); } if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X)) { Fail(size + " bit private key serialisation test failed on y value"); } // // three party test // IAsymmetricCipherKeyPairGenerator aPairGen = GeneratorUtilities.GetKeyPairGenerator(algName); aPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec)); AsymmetricCipherKeyPair aPair = aPairGen.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator bPairGen = GeneratorUtilities.GetKeyPairGenerator(algName); bPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec)); AsymmetricCipherKeyPair bPair = bPairGen.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator cPairGen = GeneratorUtilities.GetKeyPairGenerator(algName); cPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec)); AsymmetricCipherKeyPair cPair = cPairGen.GenerateKeyPair(); IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement(algName); aKeyAgree.Init(aPair.Private); IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement(algName); bKeyAgree.Init(bPair.Private); IBasicAgreement cKeyAgree = AgreementUtilities.GetBasicAgreement(algName); cKeyAgree.Init(cPair.Private); // Key ac = aKeyAgree.doPhase(cPair.Public, false); // Key ba = bKeyAgree.doPhase(aPair.Public, false); // Key cb = cKeyAgree.doPhase(bPair.Public, false); // // aKeyAgree.doPhase(cb, true); // bKeyAgree.doPhase(ac, true); // cKeyAgree.doPhase(ba, true); // // BigInteger aShared = new BigInteger(aKeyAgree.generateSecret()); // BigInteger bShared = new BigInteger(bKeyAgree.generateSecret()); // BigInteger cShared = new BigInteger(cKeyAgree.generateSecret()); DHPublicKeyParameters ac = new DHPublicKeyParameters(aKeyAgree.CalculateAgreement(cPair.Public), spec); DHPublicKeyParameters ba = new DHPublicKeyParameters(bKeyAgree.CalculateAgreement(aPair.Public), spec); DHPublicKeyParameters cb = new DHPublicKeyParameters(cKeyAgree.CalculateAgreement(bPair.Public), spec); BigInteger aShared = aKeyAgree.CalculateAgreement(cb); BigInteger bShared = bKeyAgree.CalculateAgreement(ac); BigInteger cShared = cKeyAgree.CalculateAgreement(ba); if (!aShared.Equals(bShared)) { Fail(size + " bit 3-way test failed (a and b differ)"); } if (!cShared.Equals(bShared)) { Fail(size + " bit 3-way test failed (c and b differ)"); } }
private void doTestECDH( string algorithm) { IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator(algorithm); // EllipticCurve curve = new EllipticCurve( // new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q // new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a // new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecSpec = new ECDomainParameters( curve, // ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n BigInteger.One); //1); // h // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); // // a side // AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm); aKeyAgreeBasic.Init(aKeyPair.Private); // // b side // AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm); bKeyAgreeBasic.Init(bKeyPair.Private); // // agreement // // aKeyAgreeBasic.doPhase(bKeyPair.Public, true); // bKeyAgreeBasic.doPhase(aKeyPair.Public, true); // // BigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret()); // BigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret()); BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public); BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public); if (!k1.Equals(k2)) { Fail(algorithm + " 2-way test failed"); } // // public key encoding test // // byte[] pubEnc = aKeyPair.Public.GetEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.getInstance(algorithm); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509); ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc); ECDomainParameters ecDP = pubKey.Parameters; // if (!pubKey.getW().Equals(((ECPublicKeyParameters)aKeyPair.Public).getW())) ECPoint pq1 = pubKey.Q.Normalize(), pq2 = ((ECPublicKeyParameters)aKeyPair.Public).Q.Normalize(); if (!pq1.Equals(pq2)) { // Console.WriteLine(" expected " + pubKey.getW().getAffineX() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineX()); // Console.WriteLine(" expected " + pubKey.getW().getAffineY() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineY()); // Fail(algorithm + " public key encoding (W test) failed"); Console.WriteLine(" expected " + pq1.AffineXCoord.ToBigInteger() + " got " + pq2.AffineXCoord.ToBigInteger()); Console.WriteLine(" expected " + pq1.AffineYCoord.ToBigInteger() + " got " + pq2.AffineYCoord.ToBigInteger()); Fail(algorithm + " public key encoding (Q test) failed"); } // if (!pubKey.Parameters.getGenerator().Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.getGenerator())) if (!pubKey.Parameters.G.Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.G)) { Fail(algorithm + " public key encoding (G test) failed"); } // // private key encoding test // // byte[] privEnc = aKeyPair.Private.GetEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8); ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc); // if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS())) if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D)) { // Fail(algorithm + " private key encoding (S test) failed"); Fail(algorithm + " private key encoding (D test) failed"); } // if (!privKey.Parameters.getGenerator().Equals(((ECPrivateKey)aKeyPair.Private).Parameters.getGenerator())) if (!privKey.Parameters.G.Equals(((ECPrivateKeyParameters)aKeyPair.Private).Parameters.G)) { Fail(algorithm + " private key encoding (G test) failed"); } }
/// <summary> /// Generates a <see cref="PgpKeyRingGenerator"/> /// </summary> /// <param name="identity"> /// The name of the identity. /// </param> /// <param name="password"> /// The passphrase used to protect the keyring.</param> /// <returns> /// A <see cref="PgpKeyRingGenerator"/>. /// </returns> public static PgpKeyRingGenerator GenerateKeyRingGenerator(string identity, string password) { var rsaParams = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 2048, 12); var symmetricAlgorithms = new SymmetricKeyAlgorithmTag[] { SymmetricKeyAlgorithmTag.Aes256, SymmetricKeyAlgorithmTag.Aes192, SymmetricKeyAlgorithmTag.Aes128 }.Select(a => (int)a).ToArray(); var hashAlgorithms = new HashAlgorithmTag[] { HashAlgorithmTag.Sha256, HashAlgorithmTag.Sha1, HashAlgorithmTag.Sha384, HashAlgorithmTag.Sha512, HashAlgorithmTag.Sha224, }.Select(a => (int)a).ToArray(); IAsymmetricCipherKeyPairGenerator generator = GeneratorUtilities.GetKeyPairGenerator("RSA"); generator.Init(rsaParams); // Create the master (signing-only) key. PgpKeyPair masterKeyPair = new PgpKeyPair( PublicKeyAlgorithmTag.RsaSign, generator.GenerateKeyPair(), DateTime.UtcNow); PgpSignatureSubpacketGenerator masterSubpckGen = new PgpSignatureSubpacketGenerator(); masterSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanSign | PgpKeyFlags.CanCertify); masterSubpckGen.SetPreferredSymmetricAlgorithms(false, symmetricAlgorithms); masterSubpckGen.SetPreferredHashAlgorithms(false, hashAlgorithms); // Create a signing and encryption key for daily use. PgpKeyPair encKeyPair = new PgpKeyPair( PublicKeyAlgorithmTag.RsaGeneral, generator.GenerateKeyPair(), DateTime.UtcNow); PgpSignatureSubpacketGenerator encSubpckGen = new PgpSignatureSubpacketGenerator(); encSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage); masterSubpckGen.SetPreferredSymmetricAlgorithms(false, symmetricAlgorithms); masterSubpckGen.SetPreferredHashAlgorithms(false, hashAlgorithms); // Create the key ring. PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator( PgpSignature.DefaultCertification, masterKeyPair, identity, SymmetricKeyAlgorithmTag.Aes128, password.ToCharArray(), true, masterSubpckGen.Generate(), null, new SecureRandom()); // Add encryption subkey. keyRingGen.AddSubKey(encKeyPair, encSubpckGen.Generate(), null); return(keyRingGen); }
public override void PerformTest() { PgpPublicKey pubKey = null; // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); pubKey = pgpPub.GetPublicKey(); // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKey); PgpSecretKey secretKey = sKey.GetSecretKey(); PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass); // // test signature message // PgpObjectFactory pgpFact = new PgpObjectFactory(sig1); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } // // signature generation // GenerateTest(sKey, pubKey, pgpPrivKey); // // signature generation - canonical text // 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.CanonicalTextDocument, 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.Text, "_CONSOLE", dataBytes.Length, testDateTime); while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); // // verify Generated signature - canconical text // pgpFact = new PgpObjectFactory(bOut.ToArray()); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } dIn = p2.GetInputStream(); ops.InitVerify(pubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } // // Read the public key with user attributes // pgpPub = new PgpPublicKeyRing(testPubWithUserAttr); pubKey = pgpPub.GetPublicKey(); int count = 0; foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes()) { int sigCount = 0; foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes)) { if (sigs == null) { Fail("null signature found"); } sigCount++; } if (sigCount != 1) { Fail("Failed user attributes signature check"); } count++; } if (count != 1) { Fail("Failed user attributes check"); } byte[] pgpPubBytes = pgpPub.GetEncoded(); pgpPub = new PgpPublicKeyRing(pgpPubBytes); pubKey = pgpPub.GetPublicKey(); count = 0; foreach (object ua in pubKey.GetUserAttributes()) { if (ua == null) { Fail("null user attribute found"); } count++; } if (count != 1) { Fail("Failed user attributes reread"); } // // reading test extra data - key with edge condition for DSA key password. // char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; sKey = new PgpSecretKeyRing(testPrivKey2); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase); // // reading test - aes256 encrypted passphrase. // sKey = new PgpSecretKeyRing(aesSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // reading test - twofish encrypted passphrase. // sKey = new PgpSecretKeyRing(twofishSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // use of PgpKeyPair // DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay? DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); kpg.Init(kgp); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; }
public void TestAlgorithms() { // // RSA parameters // BigInteger rsaMod = new BigInteger("a7295693155b1813bb84877fb45343556e0568043de5910872a3a518cc11e23e2db74eaf4545068c4e3d258a2718fbacdcc3eafa457695b957e88fbf110aed049a992d9c430232d02f3529c67a3419935ea9b569f85b1bcd37de6b899cd62697e843130ff0529d09c97d813cb15f293751ff56f943fbdabb63971cc7f4f6d5bff1594416b1f5907bde5a84a44f9802ef29b43bda1960f948f8afb8766c1ab80d32eec88ed66d0b65aebe44a6d0b3c5e0ab051aaa1b912fbcc17b8e751ddecc5365b6db6dab0020c3057db4013a51213a5798a3aab67985b0f4d88627a54a0f3f0285fbcb4afdfeb65cb153af66825656d43238b75503231500753f4e421e3c57", 16); BigInteger rsaPubExp = new BigInteger("10001", 16); BigInteger rsaPrivExp = new BigInteger("65dad56ac7df7abb434e4cb5eeadb16093aa6da7f0033aad3815289b04757d32bfee6ade7749c8e4a323b5050a2fb9e2a99e23469e1ed4ba5bab54336af20a5bfccb8b3424cc6923db2ffca5787ed87aa87aa614cd04cedaebc8f623a2d2063017910f436dff18bb06f01758610787f8b258f0a8efd8bd7de30007c47b2a1031696c7d6523bc191d4d918927a7e0b09584ed205bd2ff4fc4382678df82353f7532b3bbb81d69e3f39070aed3fb64fce032a089e8e64955afa5213a6eb241231bd98d702fba725a9b205952fda186412d9e0d9344d2998c455ad8c2bae85ee672751466d5288304032b5b7e02f7e558c7af82c7fbf58eea0bb4ef0f001e6cd0a9", 16); BigInteger rsaPrivP = new BigInteger("d4fd9ac3474fb83aaf832470643609659e511b322632b239b688f3cd2aad87527d6cf652fb9c9ca67940e84789444f2e99b0cb0cfabbd4de95396106c865f38e2fb7b82b231260a94df0e01756bf73ce0386868d9c41645560a81af2f53c18e4f7cdf3d51d80267372e6e0216afbf67f655c9450769cca494e4f6631b239ce1b", 16); BigInteger rsaPrivQ = new BigInteger("c8eaa0e2a1b3a4412a702bccda93f4d150da60d736c99c7c566fdea4dd1b401cbc0d8c063daaf0b579953d36343aa18b33dbf8b9eae94452490cc905245f8f7b9e29b1a288bc66731a29e1dd1a45c9fd7f8238ff727adc49fff73991d0dc096206b9d3a08f61e7462e2b804d78cb8c5eccdb9b7fbd2ad6a8fea46c1053e1be75", 16); BigInteger rsaPrivDP = new BigInteger("10edcb544421c0f9e123624d1099feeb35c72a8b34e008ac6fa6b90210a7543f293af4e5299c8c12eb464e70092805c7256e18e5823455ba0f504d36f5ccacac1b7cd5c58ff710f9c3f92646949d88fdd1e7ea5fed1081820bb9b0d2a8cd4b093fecfdb96dabd6e28c3a6f8c186dc86cddc89afd3e403e0fcf8a9e0bcb27af0b", 16); BigInteger rsaPrivDQ = new BigInteger("97fc25484b5a415eaa63c03e6efa8dafe9a1c8b004d9ee6e80548fefd6f2ce44ee5cb117e77e70285798f57d137566ce8ea4503b13e0f1b5ed5ca6942537c4aa96b2a395782a4cb5b58d0936e0b0fa63b1192954d39ced176d71ef32c6f42c84e2e19f9d4dd999c2151b032b97bd22aa73fd8c5bcd15a2dca4046d5acc997021", 16); BigInteger rsaPrivQinv = new BigInteger("4bb8064e1eff7e9efc3c4578fcedb59ca4aef0993a8312dfdcb1b3decf458aa6650d3d0866f143cbf0d3825e9381181170a0a1651eefcd7def786b8eb356555d9fa07c85b5f5cbdd74382f1129b5e36b4166b6cc9157923699708648212c484958351fdc9cf14f218dbe7fbf7cbd93a209a4681fe23ceb44bab67d66f45d1c9d", 16); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaMod, rsaPubExp); RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters( rsaMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv); // // ECDSA parameters // BigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv")); BigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R")); BigInteger ECParraH = new BigInteger(Base64.Decode("AQ==")); BigInteger ECParraN = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L")); BigInteger ECPubQX = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l")); BigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx")); BigInteger ECPrivD = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo")); FpCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecDomain = new ECDomainParameters(curve, new FpPoint(curve, curve.FromBigInteger(ECParraGX), curve.FromBigInteger(ECParraGY)), ECParraN); ECPublicKeyParameters ecPub = new ECPublicKeyParameters( new FpPoint(curve, curve.FromBigInteger(ECPubQX), curve.FromBigInteger(ECPubQY)), ecDomain); ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters(ECPrivD, ecDomain); // // DSA parameters // BigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM=")); BigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs=")); BigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx")); BigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw==")); BigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A=")); DsaParameters para = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG); DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para); DsaPublicKeyParameters dsaPub = new DsaPublicKeyParameters(DSAPublicY, para); // // ECGOST3410 parameters // IAsymmetricCipherKeyPairGenerator ecGostKpg = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410"); ecGostKpg.Init( new ECKeyGenerationParameters( CryptoProObjectIdentifiers.GostR3410x2001CryptoProA, new SecureRandom())); AsymmetricCipherKeyPair ecGostPair = ecGostKpg.GenerateKeyPair(); // // GOST3410 parameters // IAsymmetricCipherKeyPairGenerator gostKpg = GeneratorUtilities.GetKeyPairGenerator("GOST3410"); gostKpg.Init( new Gost3410KeyGenerationParameters( new SecureRandom(), CryptoProObjectIdentifiers.GostR3410x94CryptoProA)); AsymmetricCipherKeyPair gostPair = gostKpg.GenerateKeyPair(); // // signer loop // byte[] shortMsg = new byte[] { 1, 4, 5, 6, 8, 8, 4, 2, 1, 3 }; byte[] longMsg = new byte[100]; new SecureRandom().NextBytes(longMsg); foreach (string algorithm in SignerUtilities.Algorithms) { ISigner signer = SignerUtilities.GetSigner(algorithm); string upper = algorithm.ToUpperInvariant(); int withPos = upper.LastIndexOf("WITH"); string cipherName = withPos < 0 ? upper : upper.Substring(withPos + "WITH".Length); ICipherParameters signParams = null, verifyParams = null; if (cipherName == "RSA" || cipherName == "RSAANDMGF1") { signParams = rsaPrivate; verifyParams = rsaPublic; } else if (cipherName == "ECDSA") { signParams = ecPriv; verifyParams = ecPub; } else if (cipherName == "DSA") { signParams = dsaPriv; verifyParams = dsaPub; } else if (cipherName == "ECGOST3410") { signParams = ecGostPair.Private; verifyParams = ecGostPair.Public; } else if (cipherName == "GOST3410") { signParams = gostPair.Private; verifyParams = gostPair.Public; } else { Assert.Fail("Unknown algorithm encountered: " + cipherName); } signer.Init(true, signParams); foreach (byte b in shortMsg) { signer.Update(b); } signer.BlockUpdate(longMsg, 0, longMsg.Length); byte[] sig = signer.GenerateSignature(); signer.Init(false, verifyParams); foreach (byte b in shortMsg) { signer.Update(b); } signer.BlockUpdate(longMsg, 0, longMsg.Length); Assert.IsTrue(signer.VerifySignature(sig), cipherName + " signer " + algorithm + " failed."); } }
public override void PerformTest() { generationTest(512, "RSA", "SHA1withRSA"); generationTest(512, "GOST3410", "GOST3411withGOST3410"); // if (Security.getProvider("SunRsaSign") != null) // { // generationTest(512, "RSA", "SHA1withRSA", "SunRsaSign"); // } // elliptic curve GOST A parameter set Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(gost3410EC_A); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_A."); } // elliptic curve GOST B parameter set req = new Pkcs10CertificationRequest(gost3410EC_B); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_B."); } // elliptic curve GOST C parameter set req = new Pkcs10CertificationRequest(gost3410EC_C); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_C."); } // elliptic curve GOST ExA parameter set req = new Pkcs10CertificationRequest(gost3410EC_ExA); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_ExA."); } // elliptic curve GOST ExB parameter set req = new Pkcs10CertificationRequest(gost3410EC_ExB); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_ExA."); } // elliptic curve openSSL IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); ECCurve curve = x9.Curve; ECDomainParameters ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H); // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); AsymmetricCipherKeyPair kp = g.GenerateKeyPair(); req = new Pkcs10CertificationRequest( "ECDSAWITHSHA1", new X509Name("CN=XXX"), kp.Public, null, kp.Private); if (!req.Verify()) { Fail("Failed Verify check EC."); } createECRequest("SHA1withECDSA", X9ObjectIdentifiers.ECDsaWithSha1); createECRequest("SHA224withECDSA", X9ObjectIdentifiers.ECDsaWithSha224); createECRequest("SHA256withECDSA", X9ObjectIdentifiers.ECDsaWithSha256); createECRequest("SHA384withECDSA", X9ObjectIdentifiers.ECDsaWithSha384); createECRequest("SHA512withECDSA", X9ObjectIdentifiers.ECDsaWithSha512); createECGostRequest(); // TODO The setting of parameters for MGF algorithms is not implemented // createPssTest("SHA1withRSAandMGF1"); // createPssTest("SHA224withRSAandMGF1"); // createPssTest("SHA256withRSAandMGF1"); // createPssTest("SHA384withRSAandMGF1"); nullPointerTest(); }
public override void PerformTest() { ISigner sig = SignerUtilities.GetSigner("SHA1WithRSAEncryption"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; IAsymmetricCipherKeyPairGenerator fact = GeneratorUtilities.GetKeyPairGenerator("RSA"); fact.Init( new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 768, 25)); AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair(); AsymmetricKeyParameter signingKey = keyPair.Private; AsymmetricKeyParameter verifyKey = keyPair.Public; doTestBadSig(signingKey, verifyKey); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); byte[] sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("SHA1 verification failed"); } sig = SignerUtilities.GetSigner("MD2WithRSAEncryption"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("MD2 verification failed"); } sig = SignerUtilities.GetSigner("MD5WithRSAEncryption"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("MD5 verification failed"); } sig = SignerUtilities.GetSigner("RIPEMD160WithRSAEncryption"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("RIPEMD160 verification failed"); } // // RIPEMD-128 // sig = SignerUtilities.GetSigner("RIPEMD128WithRSAEncryption"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("RIPEMD128 verification failed"); } // // RIPEMD256 // sig = SignerUtilities.GetSigner("RIPEMD256WithRSAEncryption"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("RIPEMD256 verification failed"); } // // SHA-224 // sig = SignerUtilities.GetSigner("SHA224WithRSAEncryption"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("SHA224 verification failed"); } // // SHA-256 // sig = SignerUtilities.GetSigner("SHA256WithRSAEncryption"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("SHA256 verification failed"); } // // SHA-384 // sig = SignerUtilities.GetSigner("SHA384WithRSAEncryption"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("SHA384 verification failed"); } // // SHA-512 // sig = SignerUtilities.GetSigner("SHA512WithRSAEncryption"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("SHA512 verification failed"); } // // ISO Sigs. // sig = SignerUtilities.GetSigner("MD5WithRSA/ISO9796-2"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("MD5/ISO verification failed"); } sig = SignerUtilities.GetSigner("SHA1WithRSA/ISO9796-2"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("SHA1/ISO verification failed"); } sig = SignerUtilities.GetSigner("RIPEMD160WithRSA/ISO9796-2"); sig.Init(true, signingKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); sig.Init(false, verifyKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("RIPEMD160/ISO verification failed"); } // // standard vector test - B.1.3 RIPEMD160, implicit. // BigInteger mod = new BigInteger("ffffffff78f6c55506c59785e871211ee120b0b5dd644aa796d82413a47b24573f1be5745b5cd9950f6b389b52350d4e01e90009669a8720bf265a2865994190a661dea3c7828e2e7ca1b19651adc2d5", 16); BigInteger pub = new BigInteger("03", 16); BigInteger pri = new BigInteger("2aaaaaaa942920e38120ee965168302fd0301d73a4e60c7143ceb0adf0bf30b9352f50e8b9e4ceedd65343b2179005b2f099915e4b0c37e41314bb0821ad8330d23cba7f589e0f129b04c46b67dfce9d", 16); // KeyFactory f = KeyFactory.getInstance("RSA"); // AsymmetricKeyParameter privKey = f.generatePrivate(new RSAPrivateKeySpec(mod, pri)); // AsymmetricKeyParameter pubKey = f.generatePublic(new RSAPublicKeySpec(mod, pub)); AsymmetricKeyParameter privKey = new RsaKeyParameters(true, mod, pri); AsymmetricKeyParameter pubKey = new RsaKeyParameters(false, mod, pub); byte[] testSig = Hex.Decode("5cf9a01854dbacaec83aae8efc563d74538192e95466babacd361d7c86000fe42dcb4581e48e4feb862d04698da9203b1803b262105104d510b365ee9c660857ba1c001aa57abfd1c8de92e47c275cae"); data = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"); sig = SignerUtilities.GetSigner("RIPEMD160WithRSA/ISO9796-2"); sig.Init(true, privKey); sig.BlockUpdate(data, 0, data.Length); sigBytes = sig.GenerateSignature(); if (!AreEqual(testSig, sigBytes)) { Fail("SigTest: failed ISO9796-2 generation Test"); } sig.Init(false, pubKey); sig.BlockUpdate(data, 0, data.Length); if (!sig.VerifySignature(sigBytes)) { Fail("RIPEMD160/ISO verification failed"); } }
private void generationTest() { byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; ISigner s = SignerUtilities.GetSigner("GOST3410"); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410"); g.Init( new Gost3410KeyGenerationParameters( new SecureRandom(), CryptoProObjectIdentifiers.GostR3410x94CryptoProA)); AsymmetricCipherKeyPair p = g.GenerateKeyPair(); AsymmetricKeyParameter sKey = p.Private; AsymmetricKeyParameter vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); byte[] sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("GOST3410"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("GOST3410 verification failed"); } // // default initialisation test // s = SignerUtilities.GetSigner("GOST3410"); g = GeneratorUtilities.GetKeyPairGenerator("GOST3410"); // TODO This is supposed to be a 'default initialisation' test, but don't have a factory // These values are defaults from JCE provider g.Init( new Gost3410KeyGenerationParameters( new SecureRandom(), CryptoProObjectIdentifiers.GostR3410x94CryptoProA)); p = g.GenerateKeyPair(); sKey = p.Private; vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("GOST3410"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("GOST3410 verification failed"); } // // encoded test // //KeyFactory f = KeyFactory.getInstance("GOST3410"); //X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.GetEncoded()); //Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)f.generatePublic(x509s); byte[] vKeyEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded(); Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters) PublicKeyFactory.CreateKey(vKeyEnc); if (!k1.Y.Equals(((Gost3410PublicKeyParameters)vKey).Y)) { Fail("public number not decoded properly"); } //PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.GetEncoded()); //Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)f.generatePrivate(pkcs8); byte[] sKeyEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded(); Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters) PrivateKeyFactory.CreateKey(sKeyEnc); if (!k2.X.Equals(((Gost3410PrivateKeyParameters)sKey).X)) { Fail("private number not decoded properly"); } // // ECGOST3410 generation test // s = SignerUtilities.GetSigner("ECGOST3410"); g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410"); BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p ECCurve curve = new FpCurve( mod_p, // p new BigInteger("7"), // a new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b ECDomainParameters ecSpec = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("2"), new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")), new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); p = g.GenerateKeyPair(); sKey = p.Private; vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("ECGOST3410"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("ECGOST3410 verification failed"); } }
public void TestECMqv() { IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECMQV"); // EllipticCurve curve = new EllipticCurve( // new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q // new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a // new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecSpec = new ECDomainParameters( curve, // ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n BigInteger.One); //1); // h // g.initialize(ecSpec, new SecureRandom()); 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"); } }
private void doTestParams( byte[] ecParameterEncoded, bool compress) { // string keyStorePass = "******"; Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(ecParameterEncoded); X9ECParameters x9 = new X9ECParameters(seq); AsymmetricCipherKeyPair kp = null; bool success = false; while (!success) { IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); // kpg.Init(new ECParameterSpec(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed())); ECDomainParameters ecParams = new ECDomainParameters( x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); kpg.Init(new ECKeyGenerationParameters(ecParams, new SecureRandom())); kp = kpg.GenerateKeyPair(); // The very old Problem... we need a certificate chain to // save a private key... ECPublicKeyParameters pubKey = (ECPublicKeyParameters)kp.Public; if (!compress) { //pubKey.setPointFormat("UNCOMPRESSED"); pubKey = SetPublicUncompressed(pubKey); } byte[] x = pubKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned(); byte[] y = pubKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned(); if (x.Length == y.Length) { success = true; } } // The very old Problem... we need a certificate chain to // save a private key... X509CertificateEntry[] chain = new X509CertificateEntry[] { new X509CertificateEntry(GenerateSelfSignedSoftECCert(kp, compress)) }; // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(null, keyStorePass.ToCharArray()); Pkcs12Store keyStore = new Pkcs12StoreBuilder().Build(); keyStore.SetCertificateEntry("ECCert", chain[0]); ECPrivateKeyParameters privateECKey = (ECPrivateKeyParameters)kp.Private; keyStore.SetKeyEntry("ECPrivKey", new AsymmetricKeyEntry(privateECKey), chain); // Test ec sign / verify ECPublicKeyParameters pub = (ECPublicKeyParameters)kp.Public; // string oldPrivateKey = new string(Hex.encode(privateECKey.getEncoded())); byte[] oldPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateECKey).GetDerEncoded(); string oldPrivateKey = Hex.ToHexString(oldPrivateKeyBytes); // string oldPublicKey = new string(Hex.encode(pub.getEncoded())); byte[] oldPublicKeyBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub).GetDerEncoded(); string oldPublicKey = Hex.ToHexString(oldPublicKeyBytes); ECPrivateKeyParameters newKey = (ECPrivateKeyParameters) keyStore.GetKey("ECPrivKey").Key; ECPublicKeyParameters newPubKey = (ECPublicKeyParameters) keyStore.GetCertificate("ECCert").Certificate.GetPublicKey(); if (!compress) { // TODO Private key compression? //newKey.setPointFormat("UNCOMPRESSED"); //newPubKey.setPointFormat("UNCOMPRESSED"); newPubKey = SetPublicUncompressed(newPubKey); } // string newPrivateKey = new string(Hex.encode(newKey.getEncoded())); byte[] newPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(newKey).GetDerEncoded(); string newPrivateKey = Hex.ToHexString(newPrivateKeyBytes); // string newPublicKey = new string(Hex.encode(newPubKey.getEncoded())); byte[] newPublicKeyBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(newPubKey).GetDerEncoded(); string newPublicKey = Hex.ToHexString(newPublicKeyBytes); if (!oldPrivateKey.Equals(newPrivateKey)) // if (!privateECKey.Equals(newKey)) { Fail("failed private key comparison"); } if (!oldPublicKey.Equals(newPublicKey)) // if (!pub.Equals(newPubKey)) { Fail("failed public key comparison"); } }
public EphemeralKeyPairGenerator(IAsymmetricCipherKeyPairGenerator gen, KeyEncoder keyEncoder) { _gen = gen; _keyEncoder = keyEncoder; }
public void doTestCurve( string name) { // ECGenParameterSpec ecSpec = new ECGenParameterSpec(name); ECDomainParameters ecSpec = GetCurveParameters(name); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDH"); // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); // // a side // AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); // KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDHC"); IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDHC"); aKeyAgree.Init(aKeyPair.Private); // // b side // AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); // KeyAgreement bKeyAgree = KeyAgreement.getInstance("ECDHC"); IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement("ECDHC"); bKeyAgree.Init(bKeyPair.Private); // // agreement // // aKeyAgree.doPhase(bKeyPair.Public, true); // bKeyAgree.doPhase(aKeyPair.Public, true); // // BigInteger k1 = new BigInteger(aKeyAgree.generateSecret()); // BigInteger k2 = new BigInteger(bKeyAgree.generateSecret()); BigInteger k1 = aKeyAgree.CalculateAgreement(bKeyPair.Public); BigInteger k2 = bKeyAgree.CalculateAgreement(aKeyPair.Public); if (!k1.Equals(k2)) { Fail("2-way test failed"); } // // public key encoding test // // byte[] pubEnc = aKeyPair.Public.getEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.getInstance("ECDH"); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509); ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc); // if (!pubKey.getW().Equals(((ECPublicKey)aKeyPair.Public).getW())) if (!pubKey.Q.Equals(((ECPublicKeyParameters)aKeyPair.Public).Q)) { Fail("public key encoding (Q test) failed"); } // TODO Put back in? // if (!(pubKey.getParams() is ECNamedCurveSpec)) // { // Fail("public key encoding not named curve"); // } // // private key encoding test // // byte[] privEnc = aKeyPair.Private.getEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8); ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc); // if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS())) if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D)) { Fail("private key encoding (S test) failed"); } // TODO Put back in? // if (!(privKey.getParams() is ECNamedCurveSpec)) // { // Fail("private key encoding not named curve"); // } // // ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams(); // if (!(privSpec.GetName().Equals(name) || privSpec.GetName().Equals(CurveNames.get(name)))) // { // Fail("private key encoding wrong named curve. Expected: " // + CurveNames[name] + " got " + privSpec.GetName()); // } }
public void TestGeneration() { ISigner s = SignerUtilities.GetSigner("DSA"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; SecureRandom rand = new SecureRandom(); // KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA"); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA"); // test exception // doTestBadStrength(513); doTestBadStrength(510); doTestBadStrength(1025); //g.initialize(512, rand); { DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, rand); g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters())); } AsymmetricCipherKeyPair p = g.GenerateKeyPair(); AsymmetricKeyParameter sKey = p.Private; AsymmetricKeyParameter vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); byte[] sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("DSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("DSA verification failed"); } // // ECDSA Fp generation test // s = SignerUtilities.GetSigner("ECDSA"); X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); ECCurve curve = x9.Curve; ECDomainParameters ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H); g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); g.Init(new ECKeyGenerationParameters(ecSpec, rand)); p = g.GenerateKeyPair(); sKey = p.Private; vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("ECDSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("ECDSA verification failed"); } // // ECDSA F2m generation test // s = SignerUtilities.GetSigner("ECDSA"); x9 = ECNamedCurveTable.GetByName("c2tnb239v1"); curve = x9.Curve; ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H); g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); g.Init(new ECKeyGenerationParameters(ecSpec, rand)); p = g.GenerateKeyPair(); sKey = p.Private; vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("ECDSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("ECDSA verification failed"); } }
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."); // } } } }
public void TestParameters() { // AlgorithmParameterGenerator a = AlgorithmParameterGenerator.GetInstance("DSA"); // a.init(512, random); DsaParametersGenerator a = new DsaParametersGenerator(); a.Init(512, 20, random); // AlgorithmParameters parameters = a.generateParameters(); DsaParameters p = a.GenerateParameters(); // byte[] encodeParams = parameters.GetEncoded(); byte[] encodeParams = new DsaParameter(p.P, p.Q, p.G).GetDerEncoded(); // AlgorithmParameters a2 = AlgorithmParameters.GetInstance("DSA"); // a2.init(encodeParams); DsaParameter dsaP = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams)); DsaParameters p2 = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G); // a and a2 should be equivalent! // byte[] encodeParams_2 = a2.GetEncoded(); byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded(); if (!AreEqual(encodeParams, encodeParams_2)) { Fail("encode/Decode parameters failed"); } // DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(typeof(DSAParameterSpec)); // KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA"); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA"); // g.initialize(dsaP, new SecureRandom()); g.Init(new DsaKeyGenerationParameters(new SecureRandom(), p)); // KeyPair p = g.generateKeyPair(); AsymmetricCipherKeyPair pair = g.GenerateKeyPair(); // PrivateKey sKey = p.Private; // PublicKey vKey = p.Public; AsymmetricKeyParameter sKey = pair.Private; AsymmetricKeyParameter vKey = pair.Public; ISigner s = SignerUtilities.GetSigner("DSA"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); byte[] sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("DSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("DSA verification failed"); } }
/* * Creates a key ring generator and returns to caller */ public static PgpKeyRingGenerator GetKeyRingGenerator( ApplicationContext context, Node args, string identity, string password, DateTime expires, int strength, long publicExponent, int certainty) { // Creating a secure random generator to use when creating keypairs, seeding with all sorts of different unique values var sr = CreateNewSecureRandom(context, args); // Creating our generator IAsymmetricCipherKeyPairGenerator generator = GeneratorUtilities.GetKeyPairGenerator("RSA"); generator.Init( new RsaKeyGenerationParameters( BigInteger.ValueOf(publicExponent), sr, strength, certainty)); // Creates the master key (signing-only key) PgpKeyPair masterKeyPair = new PgpKeyPair( PublicKeyAlgorithmTag.RsaGeneral, generator.GenerateKeyPair(), DateTime.UtcNow); PgpSignatureSubpacketGenerator masterSubPacketGenerator = new PgpSignatureSubpacketGenerator(); masterSubPacketGenerator.SetKeyFlags(false, PgpKeyFlags.CanSign | PgpKeyFlags.CanCertify); masterSubPacketGenerator.SetPreferredSymmetricAlgorithms(false, new SymmetricKeyAlgorithmTag[] { SymmetricKeyAlgorithmTag.Aes256, SymmetricKeyAlgorithmTag.Aes192, SymmetricKeyAlgorithmTag.Aes128 }.Select(ix => (int)ix).ToArray()); masterSubPacketGenerator.SetPreferredHashAlgorithms(false, new HashAlgorithmTag [] { HashAlgorithmTag.Sha256, HashAlgorithmTag.Sha1, HashAlgorithmTag.Sha384, HashAlgorithmTag.Sha512, HashAlgorithmTag.Sha224, }.Select(ix => (int)ix).ToArray()); masterSubPacketGenerator.SetKeyExpirationTime(false, (long)(expires - DateTime.Now).TotalSeconds); // Creating a new secure random generator to use when creating keypairs, seeding with all sorts of different unique values sr = CreateNewSecureRandom(context, args); // Create signing and encryption key, for daily use PgpKeyPair encryptionKeyPair = new PgpKeyPair( PublicKeyAlgorithmTag.RsaGeneral, generator.GenerateKeyPair(), DateTime.UtcNow); PgpSignatureSubpacketGenerator encryptionSubPacketGenerator = new PgpSignatureSubpacketGenerator(); encryptionSubPacketGenerator.SetKeyFlags(false, PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage | PgpKeyFlags.CanSign); encryptionSubPacketGenerator.SetKeyExpirationTime(false, (long)(expires - DateTime.Now).TotalSeconds); // Creating keyring PgpKeyRingGenerator keyRingGenerator = new PgpKeyRingGenerator( PgpSignature.DefaultCertification, masterKeyPair, identity, SymmetricKeyAlgorithmTag.Aes256, password.ToCharArray(), true, masterSubPacketGenerator.Generate(), null, sr); // Add encryption subkey keyRingGenerator.AddSubKey(encryptionKeyPair, encryptionSubPacketGenerator.Generate(), null); // Returning keyring to caller return(keyRingGenerator); }
public void TestDsa2Parameters() { byte[] seed = Hex.Decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); //AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); //a.init(2048, new DSATestSecureRandom(seed)); DsaParametersGenerator a = new DsaParametersGenerator(new Sha256Digest()); a.Init(new DsaParameterGenerationParameters(2048, 256, 80, new DsaTestSecureRandom(seed))); //AlgorithmParameters parameters = a.generateParameters(); //DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(DSAParameterSpec.class); DsaParameters dsaP = a.GenerateParameters(); if (!dsaP.Q.Equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { Fail("Q incorrect"); } if (!dsaP.P.Equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { Fail("P incorrect"); } if (!dsaP.G.Equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { Fail("G incorrect"); } //KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA"); //g.initialize(dsaP, FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C"))); g.Init(new DsaKeyGenerationParameters(FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")), dsaP)); //KeyPair p = g.generateKeyPair(); AsymmetricCipherKeyPair p = g.GenerateKeyPair(); //DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate(); //DSAPublicKey vKey = (DSAPublicKey)p.getPublic(); DsaPrivateKeyParameters sKey = (DsaPrivateKeyParameters)p.Private; DsaPublicKeyParameters vKey = (DsaPublicKeyParameters)p.Public; if (!vKey.Y.Equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { Fail("Y value incorrect"); } if (!sKey.X.Equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { Fail("X value incorrect"); } //byte[] encodeParams = parameters.getEncoded(); byte[] encodeParams = new DsaParameter(dsaP.P, dsaP.Q, dsaP.G).GetDerEncoded(); //AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); //a2.init(encodeParams); DsaParameter dsaP2 = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams)); DsaParameters p2 = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G); // a and a2 should be equivalent! //byte[] encodeParams_2 = a2.GetEncoded(); byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded(); if (!AreEqual(encodeParams, encodeParams_2)) { Fail("encode/decode parameters failed"); } ISigner s = SignerUtilities.GetSigner("DSA"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); byte[] sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("DSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("DSA verification failed"); } }
public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random) { byte[] keyBytes = contentEncryptionKey.GetKey(); AsymmetricKeyParameter senderPublicKey = senderKeyPair.Public; ICipherParameters senderPrivateParams = senderKeyPair.Private; OriginatorIdentifierOrKey originator; try { originator = new OriginatorIdentifierOrKey( CreateOriginatorPublicKey(senderPublicKey)); } catch (IOException e) { throw new InvalidKeyException("cannot extract originator public key: " + e); } Asn1OctetString ukm = null; if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf)) { try { IAsymmetricCipherKeyPairGenerator ephemKPG = GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID); ephemKPG.Init( ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random)); AsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair(); ukm = new DerOctetString( new MQVuserKeyingMaterial( CreateOriginatorPublicKey(ephemKP.Public), null)); senderPrivateParams = new MqvPrivateParameters( (ECPrivateKeyParameters)senderPrivateParams, (ECPrivateKeyParameters)ephemKP.Private, (ECPublicKeyParameters)ephemKP.Public); } catch (IOException e) { throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e); } catch (SecurityUtilityException e) { throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e); } } DerSequence paramSeq = new DerSequence( keyEncryptionOID, DerNull.Instance); AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq); Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector(); foreach (X509Certificate recipientCert in recipientCerts) { TbsCertificateStructure tbsCert; try { tbsCert = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(recipientCert.GetTbsCertificate())); } catch (Exception) { throw new ArgumentException("can't extract TBS structure from certificate"); } // TODO Should there be a SubjectKeyIdentifier-based alternative? IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber( tbsCert.Issuer, tbsCert.SerialNumber.Value); KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial); ICipherParameters recipientPublicParams = recipientCert.GetPublicKey(); if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf)) { recipientPublicParams = new MqvPublicParameters( (ECPublicKeyParameters)recipientPublicParams, (ECPublicKeyParameters)recipientPublicParams); } // Use key agreement to choose a wrap key for this recipient IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf( keyAgreementOID, keyEncryptionOID.Id); keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random)); BigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams); int keyEncryptionKeySize = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8; byte[] keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize); KeyParameter keyEncryptionKey = ParameterUtilities.CreateKeyParameter( keyEncryptionOID, keyEncryptionKeyBytes); // Wrap the content encryption key with the agreement key IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id); keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random)); byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length); Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes); recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey)); } return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg, new DerSequence(recipientEncryptedKeys)))); }
private void EncryptDecryptTest() { SecureRandom random = SecureRandom.GetInstance("SHA1PRNG"); byte[] text = Encoding.ASCII.GetBytes("hello world!"); IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH"); keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random)); AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair(); PgpKeyPair ecdhKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDH, kpEnc, DateTime.UtcNow); PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); MemoryStream ldOut = new MemoryStream(); Stream pOut = lData.Open(ldOut, PgpLiteralDataGenerator.Utf8, PgpLiteralData.Console, text.Length, DateTime.UtcNow); pOut.Write(text, 0, text.Length); pOut.Close(); byte[] data = ldOut.ToArray(); MemoryStream cbOut = new MemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random); cPk.AddMethod(ecdhKeyPair.PublicKey); Stream cOut = cPk.Open(new UncloseableStream(cbOut), data.Length); cOut.Write(data, 0, data.Length); cOut.Close(); PgpObjectFactory pgpF = new PgpObjectFactory(cbOut.ToArray()); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; Stream clear = encP.GetDataStream(ecdhKeyPair.PrivateKey); pgpF = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData)pgpF.NextPgpObject(); clear = ld.GetInputStream(); MemoryStream bOut = new MemoryStream(); int ch; while ((ch = clear.ReadByte()) >= 0) { bOut.WriteByte((byte)ch); } byte[] output = bOut.ToArray(); if (!AreEqual(output, text)) { Fail("wrong plain text in Generated packet"); } }
public void doDefTest( IAsymmetricCipherKeyPairGenerator g, IBufferedCipher c1, IBufferedCipher c2) { // // a side // IAsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); IAsymmetricKeyParameter aPub = aKeyPair.Public; IAsymmetricKeyParameter aPriv = aKeyPair.Private; // // b side // IAsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); IAsymmetricKeyParameter bPub = bKeyPair.Public; IAsymmetricKeyParameter bPriv = bKeyPair.Private; // TODO Put back in // // // // stream test // // // IEKeySpec c1Key = new IEKeySpec(aPriv, bPub); // IEKeySpec c2Key = new IEKeySpec(bPriv, aPub); // // c1.Init(true, c1Key); // // AlgorithmParameters param = c1.getParameters(); // // c2.Init(false, c2Key, param); // // byte[] message = Hex.Decode("1234567890abcdef"); // // byte[] out1 = c1.DoFinal(message, 0, message.Length); // // byte[] out2 = c2.DoFinal(out1, 0, out1.Length); // // if (!AreEqual(out2, message)) // { // Fail("stream cipher test failed"); // } // // // // // int DoFinal // // // int len1 = c1.DoFinal(message, 0, message.Length, out1, 0); // // if (len1 != out1.Length) // { // Fail("encryption length wrong"); // } // // int len2 = c2.DoFinal(out1, 0, out1.Length, out2, 0); // // if (len2 != out2.Length) // { // Fail("decryption length wrong"); // } // // if (!AreEqual(out2, message)) // { // Fail("stream cipher test failed"); // } // // // // // int DoFinal with update // // // len1 = c1.ProcessBytes(message, 0, 2, out1, 0); // // len1 += c1.DoFinal(message, 2, message.Length - 2, out1, len1); // // if (len1 != out1.Length) // { // Fail("update encryption length wrong"); // } // // len2 = c2.ProcessBytes(out1, 0, 2, out2, 0); // // len2 += c2.DoFinal(out1, 2, out1.Length - 2, out2, len2); // // if (len2 != out2.Length) // { // Fail("update decryption length wrong"); // } // // if (!AreEqual(out2, message)) // { // Fail("update stream cipher test failed"); // } }
public static PgpKeyRingGenerator GenerateKeyRingGenerator(string identity, string password) { KeyRingParams keyRingParams = new KeyRingParams(); keyRingParams.Password = password; keyRingParams.Identity = identity; keyRingParams.PrivateKeyEncryptionAlgorithm = SymmetricKeyAlgorithmTag.Aes128; keyRingParams.SymmetricAlgorithms = new SymmetricKeyAlgorithmTag[] { SymmetricKeyAlgorithmTag.Aes256, SymmetricKeyAlgorithmTag.Aes192, SymmetricKeyAlgorithmTag.Aes128 }; keyRingParams.HashAlgorithms = new HashAlgorithmTag[] { HashAlgorithmTag.Sha256, HashAlgorithmTag.Sha1, HashAlgorithmTag.Sha384, HashAlgorithmTag.Sha512, HashAlgorithmTag.Sha224, }; IAsymmetricCipherKeyPairGenerator generator = GeneratorUtilities.GetKeyPairGenerator("RSA"); generator.Init(keyRingParams.RsaParams); /* Create the master (signing-only) key. */ PgpKeyPair masterKeyPair = new PgpKeyPair( PublicKeyAlgorithmTag.RsaSign, generator.GenerateKeyPair(), DateTime.UtcNow); PgpSignatureSubpacketGenerator masterSubpckGen = new PgpSignatureSubpacketGenerator(); masterSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanSign | PgpKeyFlags.CanCertify); masterSubpckGen.SetPreferredSymmetricAlgorithms(false, (from a in keyRingParams.SymmetricAlgorithms select(int) a).ToArray()); masterSubpckGen.SetPreferredHashAlgorithms(false, (from a in keyRingParams.HashAlgorithms select(int) a).ToArray()); /* Create a signing and encryption key for daily use. */ PgpKeyPair encKeyPair = new PgpKeyPair( PublicKeyAlgorithmTag.RsaGeneral, generator.GenerateKeyPair(), DateTime.UtcNow); PgpSignatureSubpacketGenerator encSubpckGen = new PgpSignatureSubpacketGenerator(); encSubpckGen.SetKeyFlags(false, PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage); masterSubpckGen.SetPreferredSymmetricAlgorithms(false, (from a in keyRingParams.SymmetricAlgorithms select(int) a).ToArray()); masterSubpckGen.SetPreferredHashAlgorithms(false, (from a in keyRingParams.HashAlgorithms select(int) a).ToArray()); /* Create the key ring. */ PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator( PgpSignature.DefaultCertification, masterKeyPair, keyRingParams.Identity, keyRingParams.PrivateKeyEncryptionAlgorithm.Value, keyRingParams.GetPassword(), true, masterSubpckGen.Generate(), null, new SecureRandom()); /* Add encryption subkey. */ keyRingGen.AddSubKey(encKeyPair, encSubpckGen.Generate(), null); return(keyRingGen); }
public override void PerformTest() { byte[] input = new byte[] { (byte)0x54, (byte)0x85, (byte)0x9b, (byte)0x34, (byte)0x2c, (byte)0x49, (byte)0xea, (byte)0x2a }; byte[][] output = new byte[][] { Hex.Decode("8b427f781a2e59dd9def386f1956b996ee07f48c96880e65a368055ed8c0a8831669ef7250b40918b2b1d488547e72c84540e42bd07b03f14e226f04fbc2d929"), Hex.Decode("2ec6e1a1711b6c7b8cd3f6a25db21ab8bb0a5f1d6df2ef375fa708a43997730ffc7c98856dbbe36edddcdd1b2d2a53867d8355af94fea3aeec128da908e08f4c"), Hex.Decode("0850ac4e5a8118323200c8ed1e5aaa3d5e635172553ccac66a8e4153d35c79305c4440f11034ab147fccce21f18a50cf1c0099c08a577eb68237a91042278965"), Hex.Decode("1c9649bdccb51056751fe43837f4eb43bada472accf26f65231666d5de7d11950d8379b3596dfdf75c6234274896fa8d18ad0865d3be2ac4d6687151abdf01e93941dcef18fa63186c9351d1506c89d09733c5ff4304208c812bdd21a50f56fde115e629e0e973721c9fcc87e89295a79853dee613962a0b2f2fc57163fd99057a3c776f13c20c26407eb8863998d7e53b543ba8d0a295a9a68d1a149833078c9809ad6a6dad7fc22a95ad615a73138c54c018f40d99bf8eeecd45f5be526f2d6b01aeb56381991c1ab31a2e756f15e052b9cd5638b2eff799795c5bae493307d5eb9f8c21d438de131fe505a4e7432547ab19224094f9e4be1968bd0793b79d"), Hex.Decode("4c4afc0c24dddaedd4f9a3b23be30d35d8e005ffd36b3defc5d18acc830c3ed388ce20f43a00e614fd087c814197bc9fc2eff9ad4cc474a7a2ef3ed9c0f0a55eb23371e41ee8f2e2ed93ea3a06ca482589ab87e0d61dcffda5eea1241408e43ea1108726cdb87cc3aa5e9eaaa9f72507ca1352ac54a53920c94dccc768147933d8c50aefd9d1da10522a40133cd33dbc0524669e70f771a88d65c4716d471cd22b08b9f01f24e4e9fc7ffbcfa0e0a7aed47b345826399b26a73be112eb9c5e06fc6742fc3d0ef53d43896403c5105109cfc12e6deeaf4a48ba308e039774b9bdb31a9b9e133c81c321630cf0b4b2d1f90717b24c3268e1fea681ea9cdc709342"), Hex.Decode("06b5b26bd13515f799e5e37ca43cace15cd82fd4bf36b25d285a6f0998d97c8cb0755a28f0ae66618b1cd03e27ac95eaaa4882bc6dc0078cd457d4f7de4154173a9c7a838cfc2ac2f74875df462aae0cfd341645dc51d9a01da9bdb01507f140fa8a016534379d838cc3b2a53ac33150af1b242fc88013cb8d914e66c8182864ee6de88ce2879d4c05dd125409620a96797c55c832fb2fb31d4310c190b8ed2c95fdfda2ed87f785002faaec3f35ec05cf70a3774ce185e4882df35719d582dd55ac31257344a9cba95189dcbea16e8c6cb7a235a0384bc83b6183ca8547e670fe33b1b91725ae0c250c9eca7b5ba78bd77145b70270bf8ac31653006c02ca9c"), Hex.Decode("135f1be3d045526235bf9d5e43499d4ee1bfdf93370769ae56e85dbc339bc5b7ea3bee49717497ee8ac3f7cd6adb6fc0f17812390dcd65ac7b87fef7970d9ff9"), Hex.Decode("03c05add1e030178c352face07cafc9447c8f369b8f95125c0d311c16b6da48ca2067104cce6cd21ae7b163cd18ffc13001aecebdc2eb02b9e92681f84033a98"), Hex.Decode("00319bb9becb49f3ed1bca26d0fcf09b0b0a508e4d0bd43b350f959b72cd25b3af47d608fdcd248eada74fbe19990dbeb9bf0da4b4e1200243a14e5cab3f7e610c") }; SecureRandom rand = new MyFixedSecureRandom(); // KeyFactory fact = KeyFactory.GetInstance("RSA"); // // PrivateKey privKey = fact.generatePrivate(privKeySpec); // PublicKey pubKey = fact.generatePublic(pubKeySpec); AsymmetricKeyParameter privKey = privKeySpec; AsymmetricKeyParameter pubKey = pubKeySpec; // PrivateKey priv2048Key = fact.generatePrivate(priv2048KeySpec); // PublicKey pub2048Key = fact.generatePublic(pub2048KeySpec); AsymmetricKeyParameter priv2048Key = priv2048KeySpec; AsymmetricKeyParameter pub2048Key = pub2048KeySpec; // // No Padding // // Cipher c = Cipher.GetInstance("RSA"); IBufferedCipher c = CipherUtilities.GetCipher("RSA"); // c.init(Cipher.ENCRYPT_MODE, pubKey, rand); c.Init(true, pubKey); // new ParametersWithRandom(pubKey, rand)); byte[] outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[0])) { Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes)); } // c.init(Cipher.DECRYPT_MODE, privKey); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // No Padding - incremental // // c = Cipher.GetInstance("RSA"); c = CipherUtilities.GetCipher("RSA"); // c.init(Cipher.ENCRYPT_MODE, pubKey, rand); c.Init(true, pubKey); // new ParametersWithRandom(pubKey, rand)); c.ProcessBytes(input); outBytes = c.DoFinal(); if (!AreEqual(outBytes, output[0])) { Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes)); } // c.init(Cipher.DECRYPT_MODE, privKey); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // No Padding - incremental - explicit use of NONE in mode. // c = CipherUtilities.GetCipher("RSA/NONE/NoPadding"); // c.init(Cipher.ENCRYPT_MODE, pubKey, rand); c.Init(true, pubKey); // new ParametersWithRandom(pubKey, rand)); c.ProcessBytes(input); outBytes = c.DoFinal(); if (!AreEqual(outBytes, output[0])) { Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes)); } // c.init(Cipher.DECRYPT_MODE, privKey); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // No Padding - maximum.Length // c = CipherUtilities.GetCipher("RSA"); byte[] modBytes = ((RsaKeyParameters)pubKey).Modulus.ToByteArray(); byte[] maxInput = new byte[modBytes.Length - 1]; maxInput[0] |= 0x7f; c.Init(true, pubKey); // new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(maxInput); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, maxInput)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(maxInput) + " got " + Hex.ToHexString(outBytes)); } // // PKCS1 V 1.5 // c = CipherUtilities.GetCipher("RSA//PKCS1Padding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[1])) { Fail("PKCS1 test failed on encrypt expected " + Hex.ToHexString(output[1]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("PKCS1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // PKCS1 V 1.5 - NONE // c = CipherUtilities.GetCipher("RSA/NONE/PKCS1Padding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[1])) { Fail("PKCS1 test failed on encrypt expected " + Hex.ToHexString(output[1]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("PKCS1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // OAEP - SHA1 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[2])) { Fail("OAEP test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding"); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // TODO // AlgorithmParameters oaepP = c.getParameters(); byte[] rop = new RsaesOaepParameters( new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded())) // { // Fail("OAEP test failed default sha-1 parameters"); // } // // OAEP - SHA224 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA224AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pub2048Key, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[3])) { Fail("OAEP SHA-224 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, priv2048Key); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP SHA-224 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default sha-224 parameters"); // } // // OAEP - SHA 256 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA256AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pub2048Key, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[4])) { Fail("OAEP SHA-256 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, priv2048Key); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP SHA-256 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default sha-256 parameters"); // } // // OAEP - SHA 384 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA384AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pub2048Key, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[5])) { Fail("OAEP SHA-384 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, priv2048Key); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP SHA-384 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default sha-384 parameters"); // } // // OAEP - MD5 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithMD5AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[6])) { Fail("OAEP MD5 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP MD5 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default md5 parameters"); // } // // OAEP - SHA1 with default parameters // c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding"); // TODO // c.init(Cipher.ENCRYPT_MODE, pubKey, OAEPParameterSpec.DEFAULT, rand); // // outBytes = c.DoFinal(input); // // if (!AreEqual(outBytes, output[2])) // { // Fail("OAEP test failed on encrypt expected " + Encoding.ASCII.GetString(Hex.Encode(output[2])) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } // // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding"); // // c.Init(false, privKey); // // outBytes = c.DoFinal(outBytes); // // if (!AreEqual(outBytes, input)) // { // Fail("OAEP test failed on decrypt expected " + Encoding.ASCII.GetString(Hex.Encode(input)) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } // // oaepP = c.getParameters(); // // if (!AreEqual(oaepP.getEncoded(), new byte[] { 0x30, 0x00 })) // { // Fail("OAEP test failed default parameters"); // } // // OAEP - SHA1 with specified string // c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding"); // TODO // c.init(Cipher.ENCRYPT_MODE, pubKey, new OAEPParameterSpec("SHA1", "MGF1", new MGF1ParameterSpec("SHA1"), new PSource.PSpecified(new byte[] { 1, 2, 3, 4, 5 })), rand); // // outBytes = c.DoFinal(input); // // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[] { 1, 2, 3, 4, 5 }))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded()) // { // Fail("OAEP test failed changed sha-1 parameters"); // } // // if (!AreEqual(outBytes, output[7])) // { // Fail("OAEP test failed on encrypt expected " + Encoding.ASCII.GetString(Hex.Encode(output[2])) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding"); // TODO // c.init(Cipher.DECRYPT_MODE, privKey, oaepP); // // outBytes = c.DoFinal(outBytes); // // if (!AreEqual(outBytes, input)) // { // Fail("OAEP test failed on decrypt expected " + Encoding.ASCII.GetString(Hex.Encode(input)) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } // // iso9796-1 // byte[] isoInput = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"); // PrivateKey isoPrivKey = fact.generatePrivate(isoPrivKeySpec); // PublicKey isoPubKey = fact.generatePublic(isoPubKeySpec); AsymmetricKeyParameter isoPrivKey = isoPrivKeySpec; AsymmetricKeyParameter isoPubKey = isoPubKeySpec; c = CipherUtilities.GetCipher("RSA/NONE/ISO9796-1Padding"); c.Init(true, isoPrivKey); outBytes = c.DoFinal(isoInput); if (!AreEqual(outBytes, output[8])) { Fail("ISO9796-1 test failed on encrypt expected " + Hex.ToHexString(output[3]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, isoPubKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, isoInput)) { Fail("ISO9796-1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // // generation with parameters test. // IAsymmetricCipherKeyPairGenerator keyPairGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); // // 768 bit RSA with e = 2^16-1 // keyPairGen.Init( new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 768, 25)); AsymmetricCipherKeyPair kp = keyPairGen.GenerateKeyPair(); pubKey = kp.Public; privKey = kp.Private; c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("key generation test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // comparison check // // KeyFactory keyFact = KeyFactory.GetInstance("RSA"); // // RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey)keyFact.translateKey(privKey); RsaPrivateCrtKeyParameters crtKey = (RsaPrivateCrtKeyParameters)privKey; if (!privKey.Equals(crtKey)) { Fail("private key equality check failed"); } // RSAPublicKey copyKey = (RSAPublicKey)keyFact.translateKey(pubKey); RsaKeyParameters copyKey = (RsaKeyParameters)pubKey; if (!pubKey.Equals(copyKey)) { Fail("public key equality check failed"); } SecureRandom random = new SecureRandom(); rawModeTest("SHA1withRSA", X509ObjectIdentifiers.IdSha1, priv2048Key, pub2048Key, random); rawModeTest("MD5withRSA", PkcsObjectIdentifiers.MD5, priv2048Key, pub2048Key, random); rawModeTest("RIPEMD128withRSA", TeleTrusTObjectIdentifiers.RipeMD128, priv2048Key, pub2048Key, random); }
public override void PerformTest() { IPasswordFinder pGet = new Password("secret".ToCharArray()); PemReader pemRd = OpenPemResource("test.pem", pGet); AsymmetricCipherKeyPair pair; object o; while ((o = pemRd.ReadObject()) != null) { // if (o is AsymmetricCipherKeyPair) // { // ackp = (AsymmetricCipherKeyPair)o; // // Console.WriteLine(ackp.Public); // Console.WriteLine(ackp.Private); // } // else // { // Console.WriteLine(o.ToString()); // } } // // pkcs 7 data // pemRd = OpenPemResource("pkcs7.pem", null); ContentInfo d = (ContentInfo)pemRd.ReadObject(); if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData)) { Fail("failed envelopedData check"); } /* * { * // * // ECKey * // * pemRd = OpenPemResource("eckey.pem", null); * * // TODO Resolve return type issue with EC keys and fix PemReader to return parameters * // ECNamedCurveParameterSpec spec = (ECNamedCurveParameterSpec)pemRd.ReadObject(); * * pair = (AsymmetricCipherKeyPair)pemRd.ReadObject(); * ISigner sgr = SignerUtilities.GetSigner("ECDSA"); * * sgr.Init(true, pair.Private); * * byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; * * sgr.BlockUpdate(message, 0, message.Length); * * byte[] sigBytes = sgr.GenerateSignature(); * * sgr.Init(false, pair.Public); * * sgr.BlockUpdate(message, 0, message.Length); * * if (!sgr.VerifySignature(sigBytes)) * { * Fail("EC verification failed"); * } * * // TODO Resolve this issue with the algorithm name, study Java version * // if (!((ECPublicKeyParameters) pair.Public).AlgorithmName.Equals("ECDSA")) * // { * // Fail("wrong algorithm name on public got: " + ((ECPublicKeyParameters) pair.Public).AlgorithmName); * // } * // * // if (!((ECPrivateKeyParameters) pair.Private).AlgorithmName.Equals("ECDSA")) * // { * // Fail("wrong algorithm name on private got: " + ((ECPrivateKeyParameters) pair.Private).AlgorithmName); * // } * } */ // // writer/parser test // IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpGen.Init( new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 768, 25)); pair = kpGen.GenerateKeyPair(); keyPairTest("RSA", pair); // kpGen = KeyPairGenerator.getInstance("DSA"); // kpGen.initialize(512, new SecureRandom()); DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); kpGen = GeneratorUtilities.GetKeyPairGenerator("DSA"); kpGen.Init( new DsaKeyGenerationParameters( new SecureRandom(), pGen.GenerateParameters())); pair = kpGen.GenerateKeyPair(); keyPairTest("DSA", pair); // // PKCS7 // MemoryStream bOut = new MemoryStream(); PemWriter pWrt = new PemWriter(new StreamWriter(bOut)); pWrt.WriteObject(d); pWrt.Writer.Close(); pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))); d = (ContentInfo)pemRd.ReadObject(); if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData)) { Fail("failed envelopedData recode check"); } // OpenSSL test cases (as embedded resources) doOpenSslDsaTest("unencrypted"); doOpenSslRsaTest("unencrypted"); doOpenSslTests("aes128"); doOpenSslTests("aes192"); doOpenSslTests("aes256"); doOpenSslTests("blowfish"); doOpenSslTests("des1"); doOpenSslTests("des2"); doOpenSslTests("des3"); doOpenSslTests("rc2_128"); doOpenSslDsaTest("rc2_40_cbc"); doOpenSslRsaTest("rc2_40_cbc"); doOpenSslDsaTest("rc2_64_cbc"); doOpenSslRsaTest("rc2_64_cbc"); // TODO Figure out why exceptions differ for commented out cases doDudPasswordTest("7fd98", 0, "Corrupted stream - out of bounds length found"); doDudPasswordTest("ef677", 1, "Corrupted stream - out of bounds length found"); // doDudPasswordTest("800ce", 2, "cannot recognise object in stream"); doDudPasswordTest("b6cd8", 3, "DEF length 81 object truncated by 56"); doDudPasswordTest("28ce09", 4, "DEF length 110 object truncated by 28"); doDudPasswordTest("2ac3b9", 5, "DER length more than 4 bytes: 11"); doDudPasswordTest("2cba96", 6, "DEF length 100 object truncated by 35"); doDudPasswordTest("2e3354", 7, "DEF length 42 object truncated by 9"); doDudPasswordTest("2f4142", 8, "DER length more than 4 bytes: 14"); doDudPasswordTest("2fe9bb", 9, "DER length more than 4 bytes: 65"); doDudPasswordTest("3ee7a8", 10, "DER length more than 4 bytes: 57"); doDudPasswordTest("41af75", 11, "malformed sequence in DSA private key"); doDudPasswordTest("1704a5", 12, "corrupted stream detected"); // doDudPasswordTest("1c5822", 13, "corrupted stream detected"); // doDudPasswordTest("5a3d16", 14, "corrupted stream detected"); doDudPasswordTest("8d0c97", 15, "corrupted stream detected"); doDudPasswordTest("bc0daf", 16, "corrupted stream detected"); doDudPasswordTest("aaf9c4d", 17, "Corrupted stream - out of bounds length found"); // encrypted private key test pGet = new Password("password".ToCharArray()); pemRd = OpenPemResource("enckey.pem", pGet); RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject(); if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16))) { Fail("decryption of private key data check failed"); } // general PKCS8 test pGet = new Password("password".ToCharArray()); pemRd = OpenPemResource("pkcs8test.pem", pGet); while ((privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject()) != null) { if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16))) { Fail("decryption of private key data check failed"); } } }
private void DoTestGp( int size, int privateValueSize, IBigInteger g, IBigInteger 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); IAsymmetricCipherKeyPair 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"); * } */ }
private void DoTestECDH(string algorithm) { IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator(algorithm); X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); ECDomainParameters ecSpec = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); // // a side // AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm); aKeyAgreeBasic.Init(aKeyPair.Private); // // b side // AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm); bKeyAgreeBasic.Init(bKeyPair.Private); // // agreement // BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public); BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public); if (!k1.Equals(k2)) { Fail(algorithm + " 2-way test failed"); } // // public key encoding test // // byte[] pubEnc = aKeyPair.Public.GetEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.getInstance(algorithm); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509); ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc); ECDomainParameters ecDP = pubKey.Parameters; // if (!pubKey.getW().Equals(((ECPublicKeyParameters)aKeyPair.Public).getW())) ECPoint pq1 = pubKey.Q.Normalize(), pq2 = ((ECPublicKeyParameters)aKeyPair.Public).Q.Normalize(); if (!pq1.Equals(pq2)) { // Console.WriteLine(" expected " + pubKey.getW().getAffineX() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineX()); // Console.WriteLine(" expected " + pubKey.getW().getAffineY() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineY()); // Fail(algorithm + " public key encoding (W test) failed"); Console.WriteLine(" expected " + pq1.AffineXCoord.ToBigInteger() + " got " + pq2.AffineXCoord.ToBigInteger()); Console.WriteLine(" expected " + pq1.AffineYCoord.ToBigInteger() + " got " + pq2.AffineYCoord.ToBigInteger()); Fail(algorithm + " public key encoding (Q test) failed"); } // if (!pubKey.Parameters.getGenerator().Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.getGenerator())) if (!pubKey.Parameters.G.Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.G)) { Fail(algorithm + " public key encoding (G test) failed"); } // // private key encoding test // // byte[] privEnc = aKeyPair.Private.GetEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8); ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc); // if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS())) if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D)) { // Fail(algorithm + " private key encoding (S test) failed"); Fail(algorithm + " private key encoding (D test) failed"); } // if (!privKey.Parameters.getGenerator().Equals(((ECPrivateKey)aKeyPair.Private).Parameters.getGenerator())) if (!privKey.Parameters.G.Equals(((ECPrivateKeyParameters)aKeyPair.Private).Parameters.G)) { Fail(algorithm + " private key encoding (G test) failed"); } }