public DefaultTlsEncryptionCredentials(TlsContext context, Certificate certificate, AsymmetricKeyParameter privateKey) { if (certificate == null) { throw new ArgumentNullException("certificate"); } if (certificate.IsEmpty) { throw new ArgumentException("cannot be empty", "certificate"); } if (privateKey == null) { throw new ArgumentNullException("'privateKey' cannot be null"); } if (!privateKey.IsPrivate) { throw new ArgumentException("must be private", "privateKey"); } if (privateKey is RsaKeyParameters) { } else { throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey"); } this.mContext = context; this.mCertificate = certificate; this.mPrivateKey = privateKey; }
public DefaultTlsAgreementCredentials(Certificate certificate, AsymmetricKeyParameter privateKey) { if (certificate == null) throw new ArgumentNullException("certificate"); if (certificate.IsEmpty) throw new ArgumentException("cannot be empty", "certificate"); if (privateKey == null) throw new ArgumentNullException("privateKey"); if (!privateKey.IsPrivate) throw new ArgumentException("must be private", "privateKey"); if (privateKey is DHPrivateKeyParameters) { mBasicAgreement = new DHBasicAgreement(); mTruncateAgreement = true; } else if (privateKey is ECPrivateKeyParameters) { mBasicAgreement = new ECDHBasicAgreement(); mTruncateAgreement = false; } else { throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey"); } this.mCertificate = certificate; this.mPrivateKey = privateKey; }
private static string GetKeyName(object key) { Debug.Assert(key != null, "key != null"); AsymmetricKeyParameter cspKey = key as AsymmetricKeyParameter; X509Certificate certificate = key as X509Certificate; string keyName = null; if (cspKey != null) { keyName = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", cspKey.GetType().Name); } else if (certificate != null) { keyName = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", certificate.SubjectDN); } else { keyName = key.GetHashCode().ToString("x8", CultureInfo.InvariantCulture); } return(string.Format(CultureInfo.InvariantCulture, "{0}#{1}", key.GetType().Name, keyName)); }
private byte[] EncodePrivateKey( AsymmetricKeyParameter akp, out string keyType) { PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp); DerObjectIdentifier oid = info.AlgorithmID.ObjectID; if (oid.Equals(X9ObjectIdentifiers.IdDsa)) { keyType = "DSA"; DsaParameter p = DsaParameter.GetInstance(info.AlgorithmID.Parameters); BigInteger x = ((DsaPrivateKeyParameters)akp).X; BigInteger y = p.G.ModPow(x, p.P); // TODO Create an ASN1 object somewhere for this? return(new DerSequence( new DerInteger(0), new DerInteger(p.P), new DerInteger(p.Q), new DerInteger(p.G), new DerInteger(y), new DerInteger(x)).GetEncoded()); } if (oid.Equals(PkcsObjectIdentifiers.RsaEncryption)) { keyType = "RSA"; return(info.PrivateKey.GetEncoded()); } throw new ArgumentException("Cannot handle private key of type: " + akp.GetType().FullName, "akp"); }
public DefaultTlsAgreementCredentials(Certificate certificate, AsymmetricKeyParameter privateKey) { if (certificate == null) { throw new ArgumentNullException("certificate"); } if (certificate.IsEmpty) { throw new ArgumentException("cannot be empty", "certificate"); } if (privateKey == null) { throw new ArgumentNullException("privateKey"); } if (!privateKey.IsPrivate) { throw new ArgumentException("must be private", "privateKey"); } if (privateKey is DHPrivateKeyParameters) { this.mBasicAgreement = new DHBasicAgreement(); this.mTruncateAgreement = true; } else { if (!(privateKey is ECPrivateKeyParameters)) { throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey"); } this.mBasicAgreement = new ECDHBasicAgreement(); this.mTruncateAgreement = false; } this.mCertificate = certificate; this.mPrivateKey = privateKey; }
/// <summary> /// Create the key from the Bouncy Castle private key. /// </summary> /// <param name="privateKey"> /// The Bouncy Castle private key. /// </param> public static Key CreatePrivateKey(AsymmetricKeyParameter privateKey) { var key = new Key(); key._privateKey = privateKey; // Get the public key from the private key. if (privateKey is RsaPrivateCrtKeyParameters rsa) { key._publicKey = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent); key._signingAlgorithmName = RsaSigningAlgorithmName; } else if (privateKey is Ed25519PrivateKeyParameters ed) { key._publicKey = ed.GeneratePublicKey(); key._signingAlgorithmName = Ed25519SigningAlgorithmName; } else if (privateKey is ECPrivateKeyParameters ec) { var q = ec.Parameters.G.Multiply(ec.D); key._publicKey = new ECPublicKeyParameters(q, ec.Parameters); key._signingAlgorithmName = EcSigningAlgorithmName; } if (key._publicKey == null) { throw new NotSupportedException($"The key type {privateKey.GetType().Name} is not supported."); } return(key); }
/// <summary> /// Create a key ID for the key. /// </summary> /// <param name="key"></param> /// <returns></returns> /// <remarks> /// The key id is the SHA-256 multihash of its public key. The public key is /// a protobuf encoding containing a type and /// the DER encoding of the PKCS SubjectPublicKeyInfo. /// </remarks> MultiHash CreateKeyId(AsymmetricKeyParameter key) { var spki = SubjectPublicKeyInfoFactory .CreateSubjectPublicKeyInfo(key) .GetDerEncoded(); // Add protobuf cruft. var publicKey = new Proto.PublicKey { Data = spki }; if (key is RsaKeyParameters) { publicKey.Type = Proto.KeyType.RSA; } else if (key is ECPublicKeyParameters) { publicKey.Type = Proto.KeyType.Secp256k1; } else { throw new NotSupportedException($"The key type {key.GetType().Name} is not supported."); } using (var ms = new MemoryStream()) { ProtoBuf.Serializer.Serialize(ms, publicKey); ms.Position = 0; return(MultiHash.ComputeHash(ms, "sha2-256")); } }
AsymmetricCipherKeyPair GetKeyPairFromPrivateKey(AsymmetricKeyParameter privateKey) { AsymmetricCipherKeyPair keyPair = null; if (privateKey is RsaPrivateCrtKeyParameters rsa) { var pub = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent); keyPair = new AsymmetricCipherKeyPair(pub, privateKey); } else if (privateKey is Ed25519PrivateKeyParameters ed) { var pub = ed.GeneratePublicKey(); keyPair = new AsymmetricCipherKeyPair(pub, privateKey); } else if (privateKey is ECPrivateKeyParameters ec) { var q = ec.Parameters.G.Multiply(ec.D); var pub = new ECPublicKeyParameters(ec.AlgorithmName, q, ec.PublicKeyParamSet); keyPair = new AsymmetricCipherKeyPair(pub, ec); } if (keyPair == null) { throw new NotSupportedException($"The key type {privateKey.GetType().Name} is not supported."); } return(keyPair); }
public DefaultTlsSignerCredentials(TlsContext context, Certificate certificate, AsymmetricKeyParameter privateKey, SignatureAndHashAlgorithm signatureAndHashAlgorithm) { if (certificate == null) { throw new ArgumentNullException("certificate"); } if (certificate.IsEmpty) { throw new ArgumentException("cannot be empty", "clientCertificate"); } if (privateKey == null) { throw new ArgumentNullException("privateKey"); } if (!privateKey.IsPrivate) { throw new ArgumentException("must be private", "privateKey"); } if (TlsUtilities.IsTlsV12(context) && signatureAndHashAlgorithm == null) { throw new ArgumentException("cannot be null for (D)TLS 1.2+", "signatureAndHashAlgorithm"); } if (privateKey is RsaKeyParameters) { mSigner = new TlsRsaSigner(); } else if (privateKey is DsaPrivateKeyParameters) { mSigner = new TlsDssSigner(); } else if (privateKey is ECPrivateKeyParameters) { mSigner = new TlsECDsaSigner(); } else { throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey"); } this.mSigner.Init(context); this.mContext = context; this.mCertificate = certificate; this.mPrivateKey = privateKey; this.mSignatureAndHashAlgorithm = signatureAndHashAlgorithm; }
AsymmetricCipherKeyPair GetKeyPairFromPrivateKey(AsymmetricKeyParameter privateKey) { AsymmetricCipherKeyPair keyPair = null; if (privateKey is RsaPrivateCrtKeyParameters rsa) { var pub = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent); keyPair = new AsymmetricCipherKeyPair(pub, privateKey); } if (keyPair == null) { throw new NotSupportedException($"The key type {privateKey.GetType().Name} is not supported."); } return(keyPair); }
/// <summary> /// Create a key ID for the key. /// </summary> /// <param name="key"></param> /// <returns></returns> /// <remarks> /// The key id is the SHA-256 multihash of its public key. The public key is /// a protobuf encoding containing a type and /// the DER encoding of the PKCS SubjectPublicKeyInfo. /// </remarks> MultiHash CreateKeyId(AsymmetricKeyParameter key) { var spki = SubjectPublicKeyInfoFactory .CreateSubjectPublicKeyInfo(key) .GetDerEncoded(); // Add protobuf cruft. var publicKey = new Proto.PublicKey { Data = spki }; if (key is RsaKeyParameters) { publicKey.Type = Proto.KeyType.RSA; } else if (key is ECPublicKeyParameters) { publicKey.Type = Proto.KeyType.Secp256k1; } else if (key is Ed25519PublicKeyParameters) { publicKey.Type = Proto.KeyType.Ed25519; } else { throw new NotSupportedException($"The key type {key.GetType().Name} is not supported."); } using (var ms = new MemoryStream()) { ProtoBuf.Serializer.Serialize(ms, publicKey); // If the length of the serialized bytes <= 42, then we compute the "identity" multihash of // the serialized bytes. The idea here is that if the serialized byte array // is short enough, we can fit it in a multihash verbatim without having to // condense it using a hash function. var alg = (ms.Length <= 48) ? "identity" : "sha2-256"; ms.Position = 0; return(MultiHash.ComputeHash(ms, alg)); } }
public DefaultTlsSignerCredentials(TlsClientContext context, Certificate clientCertificate, AsymmetricKeyParameter clientPrivateKey) { if (clientCertificate == null) { throw new ArgumentNullException("clientCertificate"); } if (clientCertificate.Length == 0) { throw new ArgumentException("cannot be empty", "clientCertificate"); } if (clientPrivateKey == null) { throw new ArgumentNullException("clientPrivateKey"); } if (!clientPrivateKey.IsPrivate) { throw new ArgumentException("must be private", "clientPrivateKey"); } if (clientPrivateKey is RsaKeyParameters) { clientSigner = new TlsRsaSigner(); } else if (clientPrivateKey is DsaPrivateKeyParameters) { clientSigner = new TlsDssSigner(); } else if (clientPrivateKey is ECPrivateKeyParameters) { clientSigner = new TlsECDsaSigner(); } else { throw new ArgumentException("type not supported: " + clientPrivateKey.GetType().FullName, "clientPrivateKey"); } this.context = context; this.clientCert = clientCertificate; this.clientPrivateKey = clientPrivateKey; }
private static bool IsKeyTheCorrectAlgorithm(AsymmetricKeyParameter key, Type expectedType) { Type actualType = key.GetType(); if (actualType == expectedType) { return(true); } // This check exists solely for compatibility with 4.6. Normally, we would expect "expectedType" to be the superclass type and // the actualType to be the subclass. if (expectedType.IsSubclassOf(actualType)) { return(true); } // // "expectedType" comes from the KeyAlgorithm property of a SignatureDescription. The BCL SignatureDescription classes have historically // denoted provider-specific implementations ("RSACryptoServiceProvider") rather than the base class for the algorithm ("RSA"). We could // change those (at the risk of creating other compat problems) but we have no control over third party SignatureDescriptions. // // So, in the absence of a better approach, walk up the parent hierarchy until we find the ancestor that's a direct subclass of // AsymmetricAlgorithm and treat that as the algorithm identifier. // while (expectedType != null && expectedType.BaseType != typeof(System.Security.Cryptography.AsymmetricAlgorithm)) { expectedType = expectedType.BaseType; } if (expectedType == null) { return(false); // SignatureDescription specified something that isn't even a subclass of AsymmetricAlgorithm. For compatibility with 4.6, return false rather throw. } if (actualType.IsSubclassOf(expectedType)) { return(true); } return(false); }
public DefaultTlsSignerCredentials(TlsContext context, Certificate certificate, AsymmetricKeyParameter privateKey, SignatureAndHashAlgorithm signatureAndHashAlgorithm) { if (certificate == null) throw new ArgumentNullException("certificate"); if (certificate.IsEmpty) throw new ArgumentException("cannot be empty", "clientCertificate"); if (privateKey == null) throw new ArgumentNullException("privateKey"); if (!privateKey.IsPrivate) throw new ArgumentException("must be private", "privateKey"); if (TlsUtilities.IsTlsV12(context) && signatureAndHashAlgorithm == null) throw new ArgumentException("cannot be null for (D)TLS 1.2+", "signatureAndHashAlgorithm"); if (privateKey is RsaKeyParameters) { mSigner = new TlsRsaSigner(); } else if (privateKey is DsaPrivateKeyParameters) { mSigner = new TlsDssSigner(); } else if (privateKey is ECPrivateKeyParameters) { mSigner = new TlsECDsaSigner(); } else { throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey"); } this.mSigner.Init(context); this.mContext = context; this.mCertificate = certificate; this.mPrivateKey = privateKey; this.mSignatureAndHashAlgorithm = signatureAndHashAlgorithm; }
public DefaultTlsAgreementCredentials(Certificate clientCertificate, AsymmetricKeyParameter clientPrivateKey) { if (clientCertificate == null) { throw new ArgumentNullException("clientCertificate"); } if (clientCertificate.certs.Length == 0) { throw new ArgumentException("cannot be empty", "clientCertificate"); } if (clientPrivateKey == null) { throw new ArgumentNullException("clientPrivateKey"); } if (!clientPrivateKey.IsPrivate) { throw new ArgumentException("must be private", "clientPrivateKey"); } if (clientPrivateKey is DHPrivateKeyParameters) { basicAgreement = new DHBasicAgreement(); truncateAgreement = true; } else if (clientPrivateKey is ECPrivateKeyParameters) { basicAgreement = new ECDHBasicAgreement(); truncateAgreement = false; } else { throw new ArgumentException("type not supported: " + clientPrivateKey.GetType().FullName, "clientPrivateKey"); } this.clientCert = clientCertificate; this.clientPrivateKey = clientPrivateKey; }
public DefaultTlsAgreementCredentials(Certificate clientCertificate, AsymmetricKeyParameter clientPrivateKey) { if (clientCertificate == null) { throw new ArgumentNullException("clientCertificate"); } if (clientCertificate.Length == 0) { throw new ArgumentException("cannot be empty", "clientCertificate"); } if (clientPrivateKey == null) { throw new ArgumentNullException("clientPrivateKey"); } if (!clientPrivateKey.IsPrivate) { throw new ArgumentException("must be private", "clientPrivateKey"); } if (clientPrivateKey is DHPrivateKeyParameters) { basicAgreement = new DHBasicAgreement(); truncateAgreement = true; } else if (clientPrivateKey is ECPrivateKeyParameters) { basicAgreement = new ECDHBasicAgreement(); truncateAgreement = false; } else { throw new ArgumentException("type not supported: " + clientPrivateKey.GetType().FullName, "clientPrivateKey"); } this.clientCert = clientCertificate; this.clientPrivateKey = clientPrivateKey; }
internal void EnableClientAuthentication(Certificate clientCertificate, AsymmetricKeyParameter clientPrivateKey) { if (clientCertificate == null) { throw new ArgumentNullException("clientCertificate"); } if (clientCertificate.certs.Length == 0) { throw new ArgumentException("cannot be empty", "clientCertificate"); } if (clientPrivateKey == null) { throw new ArgumentNullException("clientPrivateKey"); } if (!clientPrivateKey.IsPrivate) { throw new ArgumentException("must be private", "clientPrivateKey"); } if (clientPrivateKey is RsaKeyParameters) { clientSigner = new TlsRsaSigner(); } else if (clientPrivateKey is DsaPrivateKeyParameters) { clientSigner = new TlsDssSigner(); } else { throw new ArgumentException("type not supported: " + clientPrivateKey.GetType().FullName, "clientPrivateKey"); } this.clientCert = clientCertificate; this.clientPrivateKey = clientPrivateKey; }
public DefaultTlsEncryptionCredentials(TlsContext context, Certificate certificate, AsymmetricKeyParameter privateKey) { if (certificate == null) throw new ArgumentNullException("certificate"); if (certificate.IsEmpty) throw new ArgumentException("cannot be empty", "certificate"); if (privateKey == null) throw new ArgumentNullException("'privateKey' cannot be null"); if (!privateKey.IsPrivate) throw new ArgumentException("must be private", "privateKey"); if (privateKey is RsaKeyParameters) { } else { throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey"); } this.mContext = context; this.mCertificate = certificate; this.mPrivateKey = privateKey; }
public static PrivateKeyInfo CreatePrivateKeyInfo( AsymmetricKeyParameter key) { if (key == null) { throw new ArgumentNullException("key"); } if (!key.IsPrivate) { throw new ArgumentException("Public key passed - private key expected", "key"); } if (key is ElGamalPrivateKeyParameters) { ElGamalPrivateKeyParameters _key = (ElGamalPrivateKeyParameters)key; return(new PrivateKeyInfo( new AlgorithmIdentifier( OiwObjectIdentifiers.ElGamalAlgorithm, new ElGamalParameter( _key.Parameters.P, _key.Parameters.G).ToAsn1Object()), new DerInteger(_key.X))); } if (key is DsaPrivateKeyParameters) { DsaPrivateKeyParameters _key = (DsaPrivateKeyParameters)key; return(new PrivateKeyInfo( new AlgorithmIdentifier( X9ObjectIdentifiers.IdDsa, new DsaParameter( _key.Parameters.P, _key.Parameters.Q, _key.Parameters.G).ToAsn1Object()), new DerInteger(_key.X))); } if (key is DHPrivateKeyParameters) { /* * Process DH private key. * The value for L was set to zero implicitly. * This is the same action as found in JCEDHPrivateKey GetEncoded method. */ DHPrivateKeyParameters _key = (DHPrivateKeyParameters)key; DHParameter withNewL = new DHParameter( _key.Parameters.P, _key.Parameters.G, 0); return(new PrivateKeyInfo( new AlgorithmIdentifier( PkcsObjectIdentifiers.DhKeyAgreement, withNewL.ToAsn1Object()), new DerInteger(_key.X))); } if (key is RsaKeyParameters) { AlgorithmIdentifier algID = new AlgorithmIdentifier( PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance); RsaPrivateKeyStructure keyStruct; if (key is RsaPrivateCrtKeyParameters) { RsaPrivateCrtKeyParameters _key = (RsaPrivateCrtKeyParameters)key; keyStruct = new RsaPrivateKeyStructure( _key.Modulus, _key.PublicExponent, _key.Exponent, _key.P, _key.Q, _key.DP, _key.DQ, _key.QInv); } else { RsaKeyParameters _key = (RsaKeyParameters)key; keyStruct = new RsaPrivateKeyStructure( _key.Modulus, BigInteger.Zero, _key.Exponent, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero); } return(new PrivateKeyInfo(algID, keyStruct.ToAsn1Object())); } if (key is ECPrivateKeyParameters) { ECPrivateKeyParameters _key = (ECPrivateKeyParameters)key; AlgorithmIdentifier algID; if (_key.AlgorithmName == "ECGOST3410") { if (_key.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); algID = new AlgorithmIdentifier( CryptoProObjectIdentifiers.GostR3410x2001, gostParams.ToAsn1Object()); } else { X9ECParameters ecP = new X9ECParameters( _key.Parameters.Curve, _key.Parameters.G, _key.Parameters.N, _key.Parameters.H, _key.Parameters.GetSeed()); X962Parameters x962 = new X962Parameters(ecP); algID = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, x962.ToAsn1Object()); } return(new PrivateKeyInfo(algID, new ECPrivateKeyStructure(_key.D).ToAsn1Object())); } if (key is Gost3410PrivateKeyParameters) { Gost3410PrivateKeyParameters _key = (Gost3410PrivateKeyParameters)key; if (_key.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } byte[] keyEnc = _key.X.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, null); AlgorithmIdentifier algID = new AlgorithmIdentifier( CryptoProObjectIdentifiers.GostR3410x94, algParams.ToAsn1Object()); return(new PrivateKeyInfo(algID, new DerOctetString(keyBytes))); } throw new ArgumentException("Class provided is not convertible: " + key.GetType().FullName); }
/// <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.isPrivate()) { throw (new Exception("Private key passed - public key expected.")); } if (key is ElGamalPublicKeyParameters) { ElGamalPublicKeyParameters _key = (ElGamalPublicKeyParameters)key; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier( OIWObjectIdentifiers.elGamalAlgorithm, new ElGamalParameter( _key.getParameters().getP(), _key.getParameters().getG() ).toASN1Object()), new DERInteger(_key.getY())); return(info); } if (key is DSAPublicKeyParameters) { DSAPublicKeyParameters _key = (DSAPublicKeyParameters)key; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier( X9ObjectIdentifiers.id_dsa, new DSAParameter(_key.getParameters().getP(), _key.getParameters().getQ(), _key.getParameters().getG()).toASN1Object()), new DERInteger(_key.getY()) ); return(info); } if (key is DHPublicKeyParameters) { DHPublicKeyParameters _key = (DHPublicKeyParameters)key; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier(X9ObjectIdentifiers.dhpublicnumber, new DHParameter(_key.getParameters().getP(), _key.getParameters().getG(), _key.getParameters().getJ()).toASN1Object()), new DERInteger(_key.getY())); return(info); } // End of DH if (key is RSAKeyParameters) { RSAKeyParameters _key = (RSAKeyParameters)key; if (_key.isPrivate()) { throw (new Exception("Private RSA Key provided.")); } SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, new DERNull()), new RSAPublicKeyStructure(_key.getModulus(), _key.getExponent()).toASN1Object()); return(info); } // End of RSA. if (key is ECPublicKeyParameters) { ECPublicKeyParameters _key = (ECPublicKeyParameters)key; X9ECParameters ecP = new X9ECParameters( _key.getParameters().getCurve(), _key.getParameters().getG(), _key.getParameters().getN(), _key.getParameters().getH(), _key.getParameters().getSeed()); X962Parameters x962 = new X962Parameters(ecP); ASN1OctetString p = (ASN1OctetString)(new X9ECPoint(_key.getQ()).toASN1Object()); SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, x962.toASN1Object()), p.getOctets()); return(info); } // End of EC throw (new Exception("Class provided no convertable:" + key.GetType())); }
public static PrivateKeyInfo CreatePrivateKeyInfo(AsymmetricKeyParameter key) { if (key == null) { throw new ArgumentNullException("key"); } if (!key.IsPrivate) { throw new ArgumentException("Public key passed - private key expected", "key"); } if (key is ElGamalPrivateKeyParameters) { ElGamalPrivateKeyParameters elGamalPrivateKeyParameters = (ElGamalPrivateKeyParameters)key; return(new PrivateKeyInfo(new AlgorithmIdentifier(OiwObjectIdentifiers.ElGamalAlgorithm, new ElGamalParameter(elGamalPrivateKeyParameters.Parameters.P, elGamalPrivateKeyParameters.Parameters.G).ToAsn1Object()), new DerInteger(elGamalPrivateKeyParameters.X))); } if (key is DsaPrivateKeyParameters) { DsaPrivateKeyParameters dsaPrivateKeyParameters = (DsaPrivateKeyParameters)key; return(new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, new DsaParameter(dsaPrivateKeyParameters.Parameters.P, dsaPrivateKeyParameters.Parameters.Q, dsaPrivateKeyParameters.Parameters.G).ToAsn1Object()), new DerInteger(dsaPrivateKeyParameters.X))); } if (key is DHPrivateKeyParameters) { DHPrivateKeyParameters dHPrivateKeyParameters = (DHPrivateKeyParameters)key; DHParameter dHParameter = new DHParameter(dHPrivateKeyParameters.Parameters.P, dHPrivateKeyParameters.Parameters.G, dHPrivateKeyParameters.Parameters.L); return(new PrivateKeyInfo(new AlgorithmIdentifier(dHPrivateKeyParameters.AlgorithmOid, dHParameter.ToAsn1Object()), new DerInteger(dHPrivateKeyParameters.X))); } if (key is RsaKeyParameters) { AlgorithmIdentifier algID = new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance); RsaPrivateKeyStructure rsaPrivateKeyStructure; if (key is RsaPrivateCrtKeyParameters) { RsaPrivateCrtKeyParameters rsaPrivateCrtKeyParameters = (RsaPrivateCrtKeyParameters)key; rsaPrivateKeyStructure = new RsaPrivateKeyStructure(rsaPrivateCrtKeyParameters.Modulus, rsaPrivateCrtKeyParameters.PublicExponent, rsaPrivateCrtKeyParameters.Exponent, rsaPrivateCrtKeyParameters.P, rsaPrivateCrtKeyParameters.Q, rsaPrivateCrtKeyParameters.DP, rsaPrivateCrtKeyParameters.DQ, rsaPrivateCrtKeyParameters.QInv); } else { RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)key; rsaPrivateKeyStructure = new RsaPrivateKeyStructure(rsaKeyParameters.Modulus, BigInteger.Zero, rsaKeyParameters.Exponent, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero); } return(new PrivateKeyInfo(algID, rsaPrivateKeyStructure.ToAsn1Object())); } if (key is ECPrivateKeyParameters) { ECPrivateKeyParameters eCPrivateKeyParameters = (ECPrivateKeyParameters)key; AlgorithmIdentifier algID2; ECPrivateKeyStructure eCPrivateKeyStructure; if (eCPrivateKeyParameters.AlgorithmName == "ECGOST3410") { if (eCPrivateKeyParameters.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters(eCPrivateKeyParameters.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); algID2 = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x2001, gost3410PublicKeyAlgParameters.ToAsn1Object()); eCPrivateKeyStructure = new ECPrivateKeyStructure(eCPrivateKeyParameters.D); } else { X962Parameters x962Parameters; if (eCPrivateKeyParameters.PublicKeyParamSet == null) { ECDomainParameters parameters = eCPrivateKeyParameters.Parameters; X9ECParameters ecParameters = new X9ECParameters(parameters.Curve, parameters.G, parameters.N, parameters.H, parameters.GetSeed()); x962Parameters = new X962Parameters(ecParameters); } else { x962Parameters = new X962Parameters(eCPrivateKeyParameters.PublicKeyParamSet); } Asn1Object parameters2 = x962Parameters.ToAsn1Object(); eCPrivateKeyStructure = new ECPrivateKeyStructure(eCPrivateKeyParameters.D, parameters2); algID2 = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, parameters2); } return(new PrivateKeyInfo(algID2, eCPrivateKeyStructure.ToAsn1Object())); } if (!(key is Gost3410PrivateKeyParameters)) { throw new ArgumentException("Class provided is not convertible: " + key.GetType().FullName); } Gost3410PrivateKeyParameters gost3410PrivateKeyParameters = (Gost3410PrivateKeyParameters)key; if (gost3410PrivateKeyParameters.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } byte[] array = gost3410PrivateKeyParameters.X.ToByteArrayUnsigned(); byte[] array2 = new byte[array.Length]; for (int num = 0; num != array2.Length; num++) { array2[num] = array[array.Length - 1 - num]; } Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters(gost3410PrivateKeyParameters.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet, null); AlgorithmIdentifier algID3 = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x94, gost3410PublicKeyAlgParameters2.ToAsn1Object()); return(new PrivateKeyInfo(algID3, new DerOctetString(array2))); }
private static byte[] EncodePrivateKey(AsymmetricKeyParameter akp, out string keyType) { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp); AlgorithmIdentifier privateKeyAlgorithm = privateKeyInfo.PrivateKeyAlgorithm; DerObjectIdentifier objectID = privateKeyAlgorithm.ObjectID; if (objectID.Equals(X9ObjectIdentifiers.IdDsa)) { keyType = "DSA"; DsaParameter instance = DsaParameter.GetInstance(privateKeyAlgorithm.Parameters); BigInteger x = ((DsaPrivateKeyParameters)akp).X; BigInteger value = instance.G.ModPow(x, instance.P); return(new DerSequence(new Asn1Encodable[] { new DerInteger(0), new DerInteger(instance.P), new DerInteger(instance.Q), new DerInteger(instance.G), new DerInteger(value), new DerInteger(x) }).GetEncoded()); } if (objectID.Equals(PkcsObjectIdentifiers.RsaEncryption)) { keyType = "RSA"; } else { if (!objectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001) && !objectID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { throw new ArgumentException("Cannot handle private key of type: " + akp.GetType().FullName, "akp"); } keyType = "EC"; } return(privateKeyInfo.ParsePrivateKey().GetEncoded()); }
/// <summary> /// Convert a BouncyCastle AsymmetricKeyParameter into an AsymmetricAlgorithm. /// </summary> /// <remarks> /// <para>Converts a BouncyCastle AsymmetricKeyParameter into an AsymmetricAlgorithm.</para> /// <note type="note">Currently, only RSA and DSA keys are supported.</note> /// </remarks> /// <returns>The AsymmetricAlgorithm.</returns> /// <param name="key">The AsymmetricKeyParameter.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="key"/> is <c>null</c>. /// </exception> /// <exception cref="System.NotSupportedException"> /// <paramref name="key"/> is an unsupported asymmetric key parameter. /// </exception> public static AsymmetricAlgorithm AsAsymmetricAlgorithm(this AsymmetricKeyParameter key) { // TODO: Drop this API - it's no longer needed. The WindowsSecureMimeContext now exports the certificate & key into a pkcs12 and then loads that into an X509Certificate2. if (key == null) { throw new ArgumentNullException(nameof(key)); } if (key.IsPrivate) { if (key is RsaPrivateCrtKeyParameters rsaPrivateKey) { return(GetAsymmetricAlgorithm(rsaPrivateKey)); } if (key is DsaPrivateKeyParameters dsaPrivateKey) { return(GetAsymmetricAlgorithm(dsaPrivateKey, null)); } } else { if (key is RsaKeyParameters rsaPublicKey) { return(GetAsymmetricAlgorithm(rsaPublicKey)); } if (key is DsaPublicKeyParameters dsaPublicKey) { return(GetAsymmetricAlgorithm(dsaPublicKey)); } } throw new NotSupportedException(string.Format("{0} is currently not supported.", key.GetType().Name)); }
/// <summary> /// Gets OpenSsh formatted bytes from public key /// </summary> /// <param name="key">The key.</param> /// <param name="cert">When set to <c>true</c> and the key has a certificate, the certificate blob will be used.</param> /// <returns>byte array containing key information</returns> public static byte[] GetPublicKeyBlob(this ISshKey key, bool cert = true) { if (cert && key.Certificate != null) { return(key.Certificate.Blob); } AsymmetricKeyParameter parameters = key.GetPublicKeyParameters(); BlobBuilder builder = new BlobBuilder(); if (parameters is RsaKeyParameters) { RsaKeyParameters rsaPublicKeyParameters = (RsaKeyParameters)parameters; if (key.Version == SshVersion.SSH1) { builder.AddInt(key.Size); builder.AddSsh1BigIntBlob(rsaPublicKeyParameters.Exponent); builder.AddSsh1BigIntBlob(rsaPublicKeyParameters.Modulus); } else { builder.AddStringBlob(PublicKeyAlgorithm.SSH_RSA.GetIdentifierString()); builder.AddBigIntBlob(rsaPublicKeyParameters.Exponent); builder.AddBigIntBlob(rsaPublicKeyParameters.Modulus); } } else if (parameters is DsaPublicKeyParameters) { DsaPublicKeyParameters dsaParameters = (DsaPublicKeyParameters)parameters; builder.AddStringBlob(PublicKeyAlgorithm.SSH_DSS.GetIdentifierString()); builder.AddBigIntBlob(dsaParameters.Parameters.P); builder.AddBigIntBlob(dsaParameters.Parameters.Q); builder.AddBigIntBlob(dsaParameters.Parameters.G); builder.AddBigIntBlob(dsaParameters.Y); } else if (parameters is ECPublicKeyParameters) { ECPublicKeyParameters ecdsaParameters = (ECPublicKeyParameters)parameters; string algorithm; switch (ecdsaParameters.Parameters.Curve.FieldSize) { case 256: algorithm = PublicKeyAlgorithm.ECDSA_SHA2_NISTP256.GetIdentifierString(); break; case 384: algorithm = PublicKeyAlgorithm.ECDSA_SHA2_NISTP384.GetIdentifierString(); break; case 521: algorithm = PublicKeyAlgorithm.ECDSA_SHA2_NISTP521.GetIdentifierString(); break; default: throw new ArgumentException("Unsupported EC size: " + ecdsaParameters.Parameters.Curve.FieldSize); } builder.AddStringBlob(algorithm); algorithm = algorithm.Replace(PublicKeyAlgorithmExt.ALGORITHM_ECDSA_SHA2_PREFIX, string.Empty); builder.AddStringBlob(algorithm); builder.AddBlob(ecdsaParameters.Q.GetEncoded()); } else if (parameters is Ed25519PublicKeyParameter) { builder.AddStringBlob(PublicKeyAlgorithm.ED25519.GetIdentifierString()); builder.AddBlob(((Ed25519PublicKeyParameter)parameters).Key); } else { throw new ArgumentException(parameters.GetType() + " is not supported"); } byte[] result = builder.GetBlob(); builder.Clear(); return(result); }
public static PrivateKeyInfo CreatePrivateKeyInfo( AsymmetricKeyParameter key) { if (key == null) { throw new ArgumentNullException("key"); } if (!key.IsPrivate) { throw new ArgumentException("Public key passed - private key expected", "key"); } if (key is ElGamalPrivateKeyParameters) { ElGamalPrivateKeyParameters _key = (ElGamalPrivateKeyParameters)key; return(new PrivateKeyInfo( new AlgorithmIdentifier( OiwObjectIdentifiers.ElGamalAlgorithm, new ElGamalParameter( _key.Parameters.P, _key.Parameters.G).ToAsn1Object()), new DerInteger(_key.X))); } if (key is DsaPrivateKeyParameters) { DsaPrivateKeyParameters _key = (DsaPrivateKeyParameters)key; return(new PrivateKeyInfo( new AlgorithmIdentifier( X9ObjectIdentifiers.IdDsa, new DsaParameter( _key.Parameters.P, _key.Parameters.Q, _key.Parameters.G).ToAsn1Object()), new DerInteger(_key.X))); } if (key is DHPrivateKeyParameters) { DHPrivateKeyParameters _key = (DHPrivateKeyParameters)key; DHParameter p = new DHParameter( _key.Parameters.P, _key.Parameters.G, _key.Parameters.L); return(new PrivateKeyInfo( new AlgorithmIdentifier(_key.AlgorithmOid, p.ToAsn1Object()), new DerInteger(_key.X))); } if (key is RsaKeyParameters) { AlgorithmIdentifier algID = new AlgorithmIdentifier( PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance); RsaPrivateKeyStructure keyStruct; if (key is RsaPrivateCrtKeyParameters) { RsaPrivateCrtKeyParameters _key = (RsaPrivateCrtKeyParameters)key; keyStruct = new RsaPrivateKeyStructure( _key.Modulus, _key.PublicExponent, _key.Exponent, _key.P, _key.Q, _key.DP, _key.DQ, _key.QInv); } else { RsaKeyParameters _key = (RsaKeyParameters)key; keyStruct = new RsaPrivateKeyStructure( _key.Modulus, BigInteger.Zero, _key.Exponent, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero); } return(new PrivateKeyInfo(algID, keyStruct.ToAsn1Object())); } if (key is ECPrivateKeyParameters) { ECPrivateKeyParameters _key = (ECPrivateKeyParameters)key; AlgorithmIdentifier algID; ECPrivateKeyStructure ec; if (_key.AlgorithmName == "ECGOST3410") { if (_key.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); algID = new AlgorithmIdentifier( CryptoProObjectIdentifiers.GostR3410x2001, gostParams.ToAsn1Object()); // TODO Do we need to pass any parameters here? ec = new ECPrivateKeyStructure(_key.D); } 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); } Asn1Object x962Object = x962.ToAsn1Object(); // TODO Possible to pass the publicKey bitstring here? ec = new ECPrivateKeyStructure(_key.D, x962Object); algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962Object); } return(new PrivateKeyInfo(algID, ec.ToAsn1Object())); } if (key is Gost3410PrivateKeyParameters) { Gost3410PrivateKeyParameters _key = (Gost3410PrivateKeyParameters)key; if (_key.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } byte[] keyEnc = _key.X.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, null); AlgorithmIdentifier algID = new AlgorithmIdentifier( CryptoProObjectIdentifiers.GostR3410x94, algParams.ToAsn1Object()); return(new PrivateKeyInfo(algID, new DerOctetString(keyBytes))); } throw new ArgumentException("Class provided is not convertible: " + key.GetType().FullName); }
public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter key) { /* * Process DH private key. * The value for L was set to zero implicitly. * This is the same action as found in JCEDHPrivateKey getEncoded method. */ if (key is ElGamalPrivateKeyParameters) { ElGamalPrivateKeyParameters _key = (ElGamalPrivateKeyParameters)key; PrivateKeyInfo info = new PrivateKeyInfo( new AlgorithmIdentifier( OIWObjectIdentifiers.elGamalAlgorithm, new ElGamalParameter( _key.getParameters().getP(), _key.getParameters().getG()).toASN1Object()), new DERInteger(_key.getX())); return(info); } if (key is DSAPrivateKeyParameters) { DSAPrivateKeyParameters _key = (DSAPrivateKeyParameters)key; PrivateKeyInfo info = new PrivateKeyInfo( new AlgorithmIdentifier( X9ObjectIdentifiers.id_dsa, new DSAParameter( _key.getParameters().getP(), _key.getParameters().getQ(), _key.getParameters().getG()).toASN1Object()), new DERInteger(_key.getX())); return(info); } if (key is DHPrivateKeyParameters) { DHPrivateKeyParameters _key = (DHPrivateKeyParameters)key; PrivateKeyInfo info = new PrivateKeyInfo( new AlgorithmIdentifier( PKCSObjectIdentifiers.dhKeyAgreement, new DHParameter( _key.getParameters().getP(), _key.getParameters().getG(), 0 ).toASN1Object() ) , new DERInteger(_key.getX())); return(info); } if (key is RSAPrivateCrtKeyParameters) { RSAPrivateCrtKeyParameters _key = (RSAPrivateCrtKeyParameters)key; PrivateKeyInfo info = new PrivateKeyInfo( new AlgorithmIdentifier( PKCSObjectIdentifiers.rsaEncryption, new DERNull()), new RSAPrivateKeyStructure( _key.getModulus(), _key.getPublicExponent(), _key.getExponent(), _key.getP(), _key.getQ(), _key.getDP(), _key.getDQ(), _key.getQInv()).toASN1Object()); return(info); } if (key is ECPrivateKeyParameters) { ECPrivateKeyParameters _key = (ECPrivateKeyParameters)key; X9ECParameters ecP = new X9ECParameters( _key.getParameters().getCurve(), _key.getParameters().getG(), _key.getParameters().getN(), _key.getParameters().getH(), _key.getParameters().getSeed()); X962Parameters x962 = new X962Parameters(ecP); PrivateKeyInfo info = new PrivateKeyInfo( new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, x962.toASN1Object()), new ECPrivateKeyStructure(_key.getD()).toASN1Object()); return(info); } throw (new Exception("Class provided is not convertable:" + key.GetType())); }
/// <summary> /// Build private PrivateKeyInfo /// https://csharp.hotexamples.com/examples/Org.BouncyCastle.Asn1.Pkcs/RsaPrivateKeyStructure/-/php-rsaprivatekeystructure-class-examples.html /// </summary> /// <param name="key">AsymmetricKeyParameter key</param> /// <returns>PrivateKeyInfo from AsymmetricKeyParameter </returns> private PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter key) { if (key is DsaPrivateKeyParameters) { DsaPrivateKeyParameters _key = (DsaPrivateKeyParameters)key; this.hasPrivateKey = true; this.privateKeyAlgorithm = "ECDSA"; return(new PrivateKeyInfo( new AlgorithmIdentifier( X9ObjectIdentifiers.IdDsa, new DsaParameter( _key.Parameters.P, _key.Parameters.Q, _key.Parameters.G).ToAsn1Object()), new DerInteger(_key.X))); } if (key is RsaKeyParameters) { AlgorithmIdentifier algID = new AlgorithmIdentifier( PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance); RsaPrivateKeyStructure keyStruct; if (key is RsaPrivateCrtKeyParameters) { RsaPrivateCrtKeyParameters _key = (RsaPrivateCrtKeyParameters)key; this.hasPrivateKey = true; this.privateKeyAlgorithm = "RSA"; keyStruct = new RsaPrivateKeyStructure( _key.Modulus, _key.PublicExponent, _key.Exponent, _key.P, _key.Q, _key.DP, _key.DQ, _key.QInv); } else { RsaKeyParameters _key = (RsaKeyParameters)key; this.hasPrivateKey = true; this.privateKeyAlgorithm = "RSA"; keyStruct = new RsaPrivateKeyStructure( _key.Modulus, BigInteger.Zero, _key.Exponent, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero); } return(new PrivateKeyInfo(algID, keyStruct.ToAsn1Object())); } this.error.setError("PK013", "Class provided is not convertible: " + key.GetType().FullName); this.hasPrivateKey = false; throw new ArgumentNullException("Class provided is not convertible: " + key.GetType().FullName); }
/// <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); }
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> /// Convert a BouncyCastle AsymmetricKeyParameter into an AsymmetricAlgorithm. /// </summary> /// <remarks> /// <para>Converts a BouncyCastle AsymmetricKeyParameter into an AsymmetricAlgorithm.</para> /// <note type="note">Currently, only RSA and DSA keys are supported.</note> /// </remarks> /// <returns>The AsymmetricAlgorithm.</returns> /// <param name="key">The AsymmetricKeyParameter.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="key"/> is <c>null</c>. /// </exception> /// <exception cref="System.NotSupportedException"> /// <paramref name="key"/> is an unsupported asymmetric key parameter. /// </exception> public static AsymmetricAlgorithm AsAsymmetricAlgorithm(this AsymmetricKeyParameter key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (key.IsPrivate) { if (key is RsaPrivateCrtKeyParameters rsaPrivateKey) { return(GetAsymmetricAlgorithm(rsaPrivateKey)); } if (key is DsaPrivateKeyParameters dsaPrivateKey) { return(GetAsymmetricAlgorithm(dsaPrivateKey, null)); } } else { if (key is RsaKeyParameters rsaPublicKey) { return(GetAsymmetricAlgorithm(rsaPublicKey)); } if (key is DsaPublicKeyParameters dsaPublicKey) { return(GetAsymmetricAlgorithm(dsaPublicKey)); } } throw new NotSupportedException(string.Format("{0} is currently not supported.", key.GetType().Name)); }