public byte[] ExportPrivateKey( ReadOnlySpan <byte> passwordBytes, S2kParameters s2kParameters) { ElGamalParameters elgamalParameters = new ElGamalParameters(); byte[] secretPart = Array.Empty <byte>(); try { elgamalParameters = elGamal.ExportParameters(true); secretPart = CryptoPool.Rent(MPInteger.GetMPEncodedLength(elgamalParameters.X !)); MPInteger.TryWriteInteger(elgamalParameters.X, secretPart, out var secretSize); int publicKeySize = MPInteger.GetMPEncodedLength(elgamalParameters.P !, elgamalParameters.G !, elgamalParameters.Y !); int encryptedSecretSize = S2kBasedEncryption.GetEncryptedLength(s2kParameters, secretSize); int expectedLength = publicKeySize + encryptedSecretSize; var destination = new byte[expectedLength]; WriteOpenPgpPublicKey(elgamalParameters, destination); S2kBasedEncryption.EncryptSecretKey(passwordBytes, s2kParameters, secretPart.AsSpan(0, secretSize), destination.AsSpan(publicKeySize)); return(destination); } finally { CryptoPool.Return(secretPart); CryptographicOperations.ZeroMemory(elgamalParameters.X); } }
public void TestElGamal() { BigInteger ELGamalParaG = new BigInteger(Base64.Decode("QAZPRcsH8kHVKS5065R1Xy6QtsPvDkmDZtPuq18EJkvLrCIZivE/m5puQp3/VKJrG7dKgz4NBGpONp3HT+Cn/g==")); BigInteger ELGamalParaP = new BigInteger(Base64.Decode("AKXmAwgkudDLI/Yxk6wk3APn+mSjX5QSyDwpchmegSIi1ZNC0Jb+IbxjroKNhRTBKjtv4/JTXtJS6IqaZv9uKes=")); BigInteger ELGamalPubY = new BigInteger(Base64.Decode("AJ/gXuZuCA2X044otNkzs8FI36XuFu1L/YHg5cEmDvICTigycRN2E1DnhP+CTqxEqgEqX8rBe5tuGDlkTLwgNqM=")); BigInteger ELGamalPriv = new BigInteger(Base64.Decode("CqVr+K0TpuJKQnc76MjKhxrJzGr93jnuE3mTpth486Meymt8uWEVAQj1tGc9DTt14F9aV9WIT2oYYbvLJRcwow==")); ElGamalParameters elPara = new ElGamalParameters(ELGamalParaP, ELGamalParaG); ElGamalPrivateKeyParameters elPriv = new ElGamalPrivateKeyParameters(ELGamalPriv, elPara); ElGamalPublicKeyParameters elPub = new ElGamalPublicKeyParameters(ELGamalPubY, elPara); SubjectPublicKeyInfo subInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(elPub); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(elPriv); ElGamalPrivateKeyParameters telPriv = (ElGamalPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo); ElGamalPublicKeyParameters telPub = (ElGamalPublicKeyParameters)PublicKeyFactory.CreateKey(subInfo); // Console.WriteLine(telPriv.Equals(elPriv)); Assert.IsTrue(telPriv.Equals(elPriv), "ELGamal Private key to into back to private key."); Assert.IsTrue(telPub.Equals(elPub), "ELGamal Public key to into back to private key."); Assert.IsTrue(true, "ELGamal Test worked."); }
private void doTestRandom( int size) { // AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("ElGamal"); // a.init(size, new SecureRandom()); ElGamalParametersGenerator a = new ElGamalParametersGenerator(); a.Init(size, 20, new SecureRandom()); // AlgorithmParameters parameters = a.generateParameters(); ElGamalParameters p = a.GenerateParameters(); // byte[] encodeParams = parameters.GetEncoded(); byte[] encodeParams = new ElGamalParameter(p.P, p.G).GetDerEncoded(); // AlgorithmParameters a2 = AlgorithmParameters.getInstance("ElGamal"); // a2.init(encodeParams); ElGamalParameter elP = new ElGamalParameter((Asn1Sequence)Asn1Object.FromByteArray(encodeParams)); ElGamalParameters p2 = new ElGamalParameters(elP.P, elP.G); // a and a2 should be equivalent! // byte[] encodeParams_2 = a2.GetEncoded(); byte[] encodeParams_2 = new ElGamalParameter(p2.P, p2.G).GetDerEncoded(); if (!AreEqual(encodeParams, encodeParams_2)) { Fail(this.Name + ": encode/decode parameters failed"); } // DHParameters elP = (DHParameters)parameters.getParameterSpec(typeof(DHParameters)); doTestGP(size, 0, elP.G, elP.P); }
public override ElGamalParameters ExportParameters(bool include_private_params) { //If there is nothing to export create first a keypair if (NeedToGenerateKey()) { CreateKeyPair(KeySizeValue); } ElGamalParameters elgamal_params = new ElGamalParameters(); // set the public values elgamal_params.P = current_key.P.getBytes(); elgamal_params.G = current_key.G.getBytes(); elgamal_params.Y = current_key.Y.getBytes(); //include the private value, X if (include_private_params) { elgamal_params.X = current_key.X.getBytes(); } else { // ensure that we zero the value elgamal_params.X = new byte[1]; } // return the parameter set return(elgamal_params); }
protected bool Equals(ElGamalParameters other) { if (p.Equals(other.p) && g.Equals(other.g)) { return(l == other.l); } return(false); }
internal static int GetStrength(ElGamalParameters parameters) { if (parameters.L == 0) { return(parameters.P.BitLength); } return(parameters.L); }
public ElGamalPrivateKeyParameters(BigInteger x, ElGamalParameters parameters) : base(isPrivate: true, parameters) { if (x == null) { throw new ArgumentNullException("x"); } this.x = x; }
public ElGamalPublicKeyParameters(BigInteger y, ElGamalParameters parameters) : base(isPrivate: false, parameters) { if (y == null) { throw new ArgumentNullException("y"); } this.y = y; }
public AsymmetricCipherKeyPair GenerateKeyPair() { DHKeyGeneratorHelper instance = DHKeyGeneratorHelper.Instance; ElGamalParameters parameters = this.param.Parameters; DHParameters dhParams = new DHParameters(parameters.P, parameters.G, null, 0, parameters.L); BigInteger x = instance.CalculatePrivate(dhParams, this.param.Random); return(new AsymmetricCipherKeyPair(new ElGamalPublicKeyParameters(instance.CalculatePublic(dhParams, x), parameters), new ElGamalPrivateKeyParameters(x, parameters))); }
/// <summary> /// Generate key pair. /// </summary> /// <returns></returns> public override AsymmetricCipherKeyPair GenerateKeyPair() { ElGamalParametersGenerator generator2 = new ElGamalParametersGenerator(); generator2.Init(_keySize, _certainty, Common.ThreadSecureRandom.Value); ElGamalParameters parameters2 = generator2.GenerateParameters(); KeyGenerationParameters parameters = new ElGamalKeyGenerationParameters(Common.ThreadSecureRandom.Value, parameters2); IAsymmetricCipherKeyPairGenerator generator = new ElGamalKeyPairGenerator(); generator.Init(parameters); return(generator.GenerateKeyPair()); }
private IAsymmetricKey GetModifiedPublicKey(BigInteger modifiedY, ElGamalParameters parameters) { var modifiedParameters = new ElGamalPublicKeyParameters(modifiedY, parameters); byte[] publicKeyContent = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(modifiedParameters) .ToAsn1Object() .GetDerEncoded(); var publicKey = new ElGamalKey(publicKeyContent, AsymmetricKeyType.Public, modifiedParameters.Parameters.P.BitLength); return(publicKey); }
private static ElGamalParameters ReadOpenPgpPublicKey(ReadOnlySpan <byte> source, out int bytesRead) { var elgamalParameters = new ElGamalParameters(); elgamalParameters.P = MPInteger.ReadInteger(source, out int pConsumed).ToArray(); source = source.Slice(pConsumed); elgamalParameters.G = MPInteger.ReadInteger(source, out int gConsumed).ToArray(); source = source.Slice(gConsumed); elgamalParameters.Y = MPInteger.ReadInteger(source, out int yConsumed).ToArray(); bytesRead = pConsumed + gConsumed + yConsumed; return(elgamalParameters); }
public AsymmetricCipherKeyPair GenerateKeyPair() { DHKeyGeneratorHelper helper = DHKeyGeneratorHelper.Instance; ElGamalParameters egp = param.Parameters; DHParameters dhp = new DHParameters(egp.P, egp.G, null, 0, egp.L); BigInteger x = helper.CalculatePrivate(dhp, param.Random); BigInteger y = helper.CalculatePublic(dhp, x); return(new AsymmetricCipherKeyPair( new ElGamalPublicKeyParameters(y, egp), new ElGamalPrivateKeyParameters(x, egp))); }
public override void ImportParameters(ElGamalParameters p_parameters) { current_key.P = new BigInteger(p_parameters.P); current_key.G = new BigInteger(p_parameters.G); current_key.Y = new BigInteger(p_parameters.Y); if (p_parameters.X != null && p_parameters.X.Length > 0) { current_key.X = new BigInteger(p_parameters.X); } // set the length of the key based on the import KeySizeValue = current_key.P.bitCount(); }
public AsymmetricCipherKeyPair GenerateKeyPair() { DHKeyGeneratorHelper helper = DHKeyGeneratorHelper.Instance; ElGamalParameters elParams = param.Parameters; BigInteger p = elParams.P; BigInteger x = helper.CalculatePrivate(p, param.Random, elParams.L); BigInteger y = helper.CalculatePublic(p, elParams.G, x); return(new AsymmetricCipherKeyPair( new ElGamalPublicKeyParameters(y, elParams), new ElGamalPrivateKeyParameters(x, elParams))); }
public override bool Equals(object obj) { if (obj == this) { return(true); } ElGamalParameters elGamalParameters = obj as ElGamalParameters; if (elGamalParameters == null) { return(false); } return(Equals(elGamalParameters)); }
/// <summary> /// Generates an El Gamal Key pair given its bit size. /// </summary> /// <param name="keySize">Bit size for keys of 1024, 2048, 3072 or 4096.</param> /// <returns></returns> public AsymmetricCipherKeyPair ElGamalkeyGen(int keySize) { var secRand = new SecureRandom(); var probPrime = GetMODRFC3526(keySize); var elGenertor = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); var elBaseGenerator = new BigInteger("2", 16); var elGamalParameterSet = new ElGamalParameters(probPrime, elBaseGenerator); var elParams = new ElGamalKeyGenerationParameters(secRand, elGamalParameterSet); elGenertor.Init(elParams); var keypair = elGenertor.GenerateKeyPair(); return(keypair); }
/// <summary> /// Create a PgpPublicKey from the passed in lightweight one. /// </summary> /// <remarks> /// Note: the time passed in affects the value of the key's keyId, so you probably only want /// to do this once for a lightweight key, or make sure you keep track of the time you used. /// </remarks> /// <param name="algorithm">Asymmetric algorithm type representing the public key.</param> /// <param name="pubKey">Actual public key to associate.</param> /// <param name="time">Date of creation.</param> /// <exception cref="ArgumentException">If <c>pubKey</c> is not public.</exception> /// <exception cref="PgpException">On key creation problem.</exception> public PgpPublicKey( PublicKeyAlgorithmTag algorithm, AsymmetricKeyParameter pubKey, DateTime time) { if (pubKey.IsPrivate) { throw new ArgumentException("Expected a public key", "pubKey"); } IBcpgKey bcpgKey; if (pubKey is RsaKeyParameters) { RsaKeyParameters rK = (RsaKeyParameters)pubKey; bcpgKey = new RsaPublicBcpgKey(rK.Modulus, rK.Exponent); } else if (pubKey is DsaPublicKeyParameters) { DsaPublicKeyParameters dK = (DsaPublicKeyParameters)pubKey; DsaParameters dP = dK.Parameters; bcpgKey = new DsaPublicBcpgKey(dP.P, dP.Q, dP.G, dK.Y); } else if (pubKey is ElGamalPublicKeyParameters) { ElGamalPublicKeyParameters eK = (ElGamalPublicKeyParameters)pubKey; ElGamalParameters eS = eK.Parameters; bcpgKey = new ElGamalPublicBcpgKey(eS.P, eS.G, eK.Y); } else { throw new PgpException("unknown key class"); } this.publicPk = new PublicKeyPacket(algorithm, time, bcpgKey); this.ids = Platform.CreateArrayList(); this.idSigs = Platform.CreateArrayList(); try { Init(); } catch (IOException e) { throw new PgpException("exception calculating keyId", e); } }
/** * this test is can take quiet a while * * @param size size of key in bits. */ private void doTestGeneration( int size) { ElGamalParametersGenerator pGen = new ElGamalParametersGenerator(); pGen.Init(size, 10, new SecureRandom()); ElGamalParameters elParams = pGen.GenerateParameters(); if (elParams.L != 0) { Fail("ElGamalParametersGenerator failed to set L to 0 in generated ElGamalParameters"); } ElGamalKeyGenerationParameters ekgParams = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams); ElGamalKeyPairGenerator kpGen = new ElGamalKeyPairGenerator(); kpGen.Init(ekgParams); // // generate first pair // AsymmetricCipherKeyPair pair = kpGen.GenerateKeyPair(); ElGamalPublicKeyParameters pu = (ElGamalPublicKeyParameters)pair.Public; ElGamalPrivateKeyParameters pv = (ElGamalPrivateKeyParameters)pair.Private; ElGamalEngine e = new ElGamalEngine(); e.Init(true, new ParametersWithRandom(pu, new SecureRandom())); byte[] message = Hex.Decode("5468697320697320612074657374"); byte[] pText = message; byte[] cText = e.ProcessBlock(pText, 0, pText.Length); e.Init(false, pv); pText = e.ProcessBlock(cText, 0, cText.Length); if (!Arrays.AreEqual(message, pText)) { Fail("generation test failed"); } }
private void GenerateElGamal(Stream outSecret, Stream outPublic) { // Prepare a strong Secure Random with seed SecureRandom secureRandom = PgpEncryptionUtil.GetSecureRandom(); IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init((int)PublicKeyLength.BITS_1024, 80, new SecureRandom()); // DSA is 1024 even for long 2048+ ElGamal keys DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(secureRandom, dsaParams); dsaKpg.Init(kgp); // // this takes a while as the key generator has to Generate some DSA parameters // before it Generates the key. // AsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); Group elgamalGroup = Precomputed.GetElGamalGroup((int)this.publicKeyLength); if (elgamalGroup == null) { throw new ArgumentException("ElGamal Group not found for key length: " + this.publicKeyLength); } Org.BouncyCastle.Math.BigInteger p = elgamalGroup.GetP(); Org.BouncyCastle.Math.BigInteger g = elgamalGroup.GetG(); secureRandom = PgpEncryptionUtil.GetSecureRandom(); ElGamalParameters elParams = new ElGamalParameters(p, g); ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(secureRandom, elParams); elgKpg.Init(elKgp); // // this is quicker because we are using preGenerated parameters. // AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair(); DsaElGamalKeyGeneratorUtil.ExportKeyPair(outSecret, outPublic, dsaKp, elgKp, identity, passphrase, true); }
static void Main(string[] args) { Parameters = ElGamal.ExportParameters(true); Console.WriteLine("Текст для шифровки: "); var toEncrypt = Console.ReadLine(); Console.Write("Шифрование..."); var encrypted = Encrypt(toEncrypt); Console.WriteLine("Готово!"); File.WriteAllBytes(_toSaveFilePath, encrypted); Console.WriteLine($"Результат: {Encoding.UTF8.GetString(encrypted)}"); Console.Write("Расшифрование..."); var decrypted = Decrypt(encrypted); Console.WriteLine("Готово!"); Console.WriteLine($"Результат: {Encoding.UTF8.GetString(decrypted)}"); Console.ReadKey(); }
//Gets and Sets the details for key public override string ToXmlString(bool _private) { ElGamalParameters elgamal_params = ExportParameters(_private); StringBuilder string_builder = new StringBuilder(); string_builder.Append("<s--------------------KeyValues--------------------------------s>\n\n"); //public elements string_builder.Append("<P> " + Convert.ToBase64String(elgamal_params.P) + " </P>\n\n"); string_builder.Append("<G> " + Convert.ToBase64String(elgamal_params.G) + " </G>\n\n"); string_builder.Append("<Y> " + Convert.ToBase64String(elgamal_params.Y) + " </Y>\n\n"); if (_private) { // include private key string_builder.Append("<X> " + Convert.ToBase64String(elgamal_params.X) + " </X>\n\n"); } string_builder.Append("</s--------------------KeyValues--------------------------------s>"); return(string_builder.ToString()); }
public void TestElGamal() { BigInteger g512 = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); BigInteger p512 = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters dhParams = new ElGamalParameters(p512, g512); ElGamalKeyGenerationParameters parameters = new ElGamalKeyGenerationParameters(new SecureRandom(), dhParams); ElGamalKeyPairGenerator kpGen = new ElGamalKeyPairGenerator(); kpGen.Init(parameters); AsymmetricCipherKeyPair pair = kpGen.GenerateKeyPair(); ElGamalPublicKeyParameters pu1 = (ElGamalPublicKeyParameters)pair.Public; ElGamalPrivateKeyParameters pv1 = (ElGamalPrivateKeyParameters)pair.Private; ElGamalPublicKeyParameters pu2 = new ElGamalPublicKeyParameters(pu1.Y, pu1.Parameters); ElGamalPrivateKeyParameters pv2 = new ElGamalPrivateKeyParameters(pv1.X, pv1.Parameters); ElGamalPublicKeyParameters pu3 = new ElGamalPublicKeyParameters(pv1.X, pu1.Parameters); ElGamalPrivateKeyParameters pv3 = new ElGamalPrivateKeyParameters(pu1.Y, pu1.Parameters); doTest(pu1, pu2, pu3); doTest(pv1, pv2, pv3); ElGamalParameters pr1 = pu1.Parameters; ElGamalParameters pr2 = new ElGamalParameters(pr1.P, pr1.G); ElGamalParameters pr3 = new ElGamalParameters(pr1.G, pr1.P); doTest(pr1, pr2, pr3); pu2 = new ElGamalPublicKeyParameters(pu1.Y, pr2); pv2 = new ElGamalPrivateKeyParameters(pv1.X, pr2); doTest(pu1, pu2, pu3); doTest(pv1, pv2, pv3); ElGamalTestKeyParameters k1 = new ElGamalTestKeyParameters(false, null); ElGamalTestKeyParameters k2 = new ElGamalTestKeyParameters(false, null); ElGamalTestKeyParameters k3 = new ElGamalTestKeyParameters(false, pu1.Parameters); doTest(k1, k2, k3); }
public override void FromXmlString(String _string) { // create parameters ElGamalParameters elgamal_params = new ElGamalParameters(); XmlTextReader xml_text_reader = new XmlTextReader(new System.IO.StringReader(_string)); while (xml_text_reader.Read()) { if (true || xml_text_reader.IsStartElement()) { switch (xml_text_reader.Name) { case "P": // set P elgamal_params.P = Convert.FromBase64String(xml_text_reader.ReadString()); break; case "G": // set G elgamal_params.G = Convert.FromBase64String(xml_text_reader.ReadString()); break; case "Y": // set Y elgamal_params.Y = Convert.FromBase64String(xml_text_reader.ReadString()); break; case "X": // set X elgamal_params.X = Convert.FromBase64String(xml_text_reader.ReadString()); break; } } } ImportParameters(elgamal_params); }
public AsymmetricCipherKeyPair generateKeyPair() { BigInteger p, g, x, y; int qLength = param.getStrength() - 1; ElGamalParameters elParams = param.getParameters(); p = elParams.getP(); g = elParams.getG(); // // calculate the private key // x = new BigInteger(qLength, param.getRandom()); // // calculate the public key. // y = g.modPow(x, p); return(new AsymmetricCipherKeyPair( new ElGamalPublicKeyParameters(y, elParams), new ElGamalPrivateKeyParameters(x, elParams))); }
public AsymmetricCipherKeyPair GenerateElGamalKeyPair(int keySize, BigInteger prime = null, BigInteger generator = null) { ElGamalParameters elGamalParameters; if (prime != null && generator != null) { elGamalParameters = new ElGamalParameters(prime, generator); } else { var elGamalParameterGenerator = new ElGamalParametersGenerator(); elGamalParameterGenerator.Init(keySize, 64, secureRandom.Generator); elGamalParameters = elGamalParameterGenerator.GenerateParameters(); } var keyGenerationParameters = new ElGamalKeyGenerationParameters(secureRandom.Generator, elGamalParameters); var keyPairGenerator = new ElGamalKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); return(keyPairGenerator.GenerateKeyPair()); }
public void TestInvalidP() { ElGamalParameters dhParams = new ElGamalParameters(pPgpBogusPSamp, gPgpBogusPSamp, lPgpBogusPSamp); ElGamalPublicKeyParameters pu = new ElGamalPublicKeyParameters(yPgpBogusPSamp, dhParams); ElGamalPrivateKeyParameters pv = new ElGamalPrivateKeyParameters(xPgpBogusPSamp, dhParams); ElGamalEngine e = new ElGamalEngine(); e.Init(true, pu); byte[] message = Hex.Decode("5468697320697320612074657374"); byte[] pText = message; byte[] cText = e.ProcessBlock(pText, 0, pText.Length); e.Init(false, pv); pText = e.ProcessBlock(cText, 0, cText.Length); if (Arrays.AreEqual(message, pText)) { Fail("invalid test failed"); } }
public ElGamalTestKeyParameters( bool isPrivate, ElGamalParameters parameters) : base(isPrivate, parameters) { }
public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo(AsymmetricKeyParameter key) { if (key == null) { throw new ArgumentNullException("key"); } if (key.IsPrivate) { throw new ArgumentException("Private key passed - public key expected.", "key"); } if (key is ElGamalPublicKeyParameters) { ElGamalPublicKeyParameters elGamalPublicKeyParameters = (ElGamalPublicKeyParameters)key; ElGamalParameters parameters = elGamalPublicKeyParameters.Parameters; return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(OiwObjectIdentifiers.ElGamalAlgorithm, new ElGamalParameter(parameters.P, parameters.G).ToAsn1Object()), new DerInteger(elGamalPublicKeyParameters.Y))); } if (key is DsaPublicKeyParameters) { DsaPublicKeyParameters dsaPublicKeyParameters = (DsaPublicKeyParameters)key; DsaParameters parameters2 = dsaPublicKeyParameters.Parameters; Asn1Encodable parameters3 = (parameters2 == null) ? null : new DsaParameter(parameters2.P, parameters2.Q, parameters2.G).ToAsn1Object(); return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, parameters3), new DerInteger(dsaPublicKeyParameters.Y))); } if (key is DHPublicKeyParameters) { DHPublicKeyParameters dHPublicKeyParameters = (DHPublicKeyParameters)key; DHParameters parameters4 = dHPublicKeyParameters.Parameters; return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(dHPublicKeyParameters.AlgorithmOid, new DHParameter(parameters4.P, parameters4.G, parameters4.L).ToAsn1Object()), new DerInteger(dHPublicKeyParameters.Y))); } if (key is RsaKeyParameters) { RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)key; return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance), new RsaPublicKeyStructure(rsaKeyParameters.Modulus, rsaKeyParameters.Exponent).ToAsn1Object())); } if (key is ECPublicKeyParameters) { ECPublicKeyParameters eCPublicKeyParameters = (ECPublicKeyParameters)key; if (!(eCPublicKeyParameters.AlgorithmName == "ECGOST3410")) { X962Parameters x962Parameters; if (eCPublicKeyParameters.PublicKeyParamSet == null) { ECDomainParameters parameters5 = eCPublicKeyParameters.Parameters; X9ECParameters ecParameters = new X9ECParameters(parameters5.Curve, parameters5.G, parameters5.N, parameters5.H, parameters5.GetSeed()); x962Parameters = new X962Parameters(ecParameters); } else { x962Parameters = new X962Parameters(eCPublicKeyParameters.PublicKeyParamSet); } Asn1OctetString asn1OctetString = (Asn1OctetString) new X9ECPoint(eCPublicKeyParameters.Q).ToAsn1Object(); AlgorithmIdentifier algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962Parameters.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID, asn1OctetString.GetOctets())); } if (eCPublicKeyParameters.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } ECPoint eCPoint = eCPublicKeyParameters.Q.Normalize(); BigInteger bI = eCPoint.AffineXCoord.ToBigInteger(); BigInteger bI2 = eCPoint.AffineYCoord.ToBigInteger(); byte[] array = new byte[64]; SubjectPublicKeyInfoFactory.ExtractBytes(array, 0, bI); SubjectPublicKeyInfoFactory.ExtractBytes(array, 32, bI2); Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters(eCPublicKeyParameters.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); AlgorithmIdentifier algID2 = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x2001, gost3410PublicKeyAlgParameters.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID2, new DerOctetString(array))); } else { if (!(key is Gost3410PublicKeyParameters)) { throw new ArgumentException("Class provided no convertible: " + key.GetType().FullName); } Gost3410PublicKeyParameters gost3410PublicKeyParameters = (Gost3410PublicKeyParameters)key; if (gost3410PublicKeyParameters.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } byte[] array2 = gost3410PublicKeyParameters.Y.ToByteArrayUnsigned(); byte[] array3 = new byte[array2.Length]; for (int num = 0; num != array3.Length; num++) { array3[num] = array2[array2.Length - 1 - num]; } Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters(gost3410PublicKeyParameters.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); AlgorithmIdentifier algID3 = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x94, gost3410PublicKeyAlgParameters2.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID3, new DerOctetString(array3))); } }
/// <summary> /// Create a Subject Public Key Info object for a given public key. /// </summary> /// <param name="key">One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters</param> /// <returns>A subject public key info object.</returns> /// <exception cref="Exception">Throw exception if object provided is not one of the above.</exception> public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo( AsymmetricKeyParameter key) { if (key == null) { throw new ArgumentNullException("key"); } if (key.IsPrivate) { throw new ArgumentException("Private key passed - public key expected.", "key"); } if (key is ElGamalPublicKeyParameters) { ElGamalPublicKeyParameters _key = (ElGamalPublicKeyParameters)key; ElGamalParameters kp = _key.Parameters; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier( OiwObjectIdentifiers.ElGamalAlgorithm, new ElGamalParameter(kp.P, kp.G).ToAsn1Object()), new DerInteger(_key.Y)); return(info); } if (key is DsaPublicKeyParameters) { DsaPublicKeyParameters _key = (DsaPublicKeyParameters)key; DsaParameters kp = _key.Parameters; Asn1Encodable ae = kp == null ? null : new DsaParameter(kp.P, kp.Q, kp.G).ToAsn1Object(); return(new SubjectPublicKeyInfo( new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, ae), new DerInteger(_key.Y))); } if (key is DHPublicKeyParameters) { DHPublicKeyParameters _key = (DHPublicKeyParameters)key; DHParameters kp = _key.Parameters; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier( _key.AlgorithmOid, new DHParameter(kp.P, kp.G, kp.L).ToAsn1Object()), new DerInteger(_key.Y)); return(info); } // End of DH if (key is RsaKeyParameters) { RsaKeyParameters _key = (RsaKeyParameters)key; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance), new RsaPublicKeyStructure(_key.Modulus, _key.Exponent).ToAsn1Object()); return(info); } // End of RSA. if (key is ECPublicKeyParameters) { ECPublicKeyParameters _key = (ECPublicKeyParameters)key; if (_key.AlgorithmName == "ECGOST3410") { if (_key.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } ECPoint q = _key.Q; BigInteger bX = q.X.ToBigInteger(); BigInteger bY = q.Y.ToBigInteger(); byte[] encKey = new byte[64]; ExtractBytes(encKey, 0, bX); ExtractBytes(encKey, 32, bY); Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); AlgorithmIdentifier algID = new AlgorithmIdentifier( CryptoProObjectIdentifiers.GostR3410x2001, gostParams.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID, new DerOctetString(encKey))); } else { X962Parameters x962; if (_key.PublicKeyParamSet == null) { ECDomainParameters kp = _key.Parameters; X9ECParameters ecP = new X9ECParameters(kp.Curve, kp.G, kp.N, kp.H, kp.GetSeed()); x962 = new X962Parameters(ecP); } else { x962 = new X962Parameters(_key.PublicKeyParamSet); } Asn1OctetString p = (Asn1OctetString)(new X9ECPoint(_key.Q).ToAsn1Object()); AlgorithmIdentifier algID = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, x962.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID, p.GetOctets())); } } // End of EC if (key is Gost3410PublicKeyParameters) { Gost3410PublicKeyParameters _key = (Gost3410PublicKeyParameters)key; if (_key.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } byte[] keyEnc = _key.Y.ToByteArrayUnsigned(); byte[] keyBytes = new byte[keyEnc.Length]; for (int i = 0; i != keyBytes.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // must be little endian } Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters( _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); AlgorithmIdentifier algID = new AlgorithmIdentifier( CryptoProObjectIdentifiers.GostR3410x94, algParams.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID, new DerOctetString(keyBytes))); } throw new ArgumentException("Class provided no convertible: " + key.GetType().FullName); }