/// <summary> /// Creates a certificate signing request from an existing certificate. /// </summary> public static byte[] CreateSigningRequest( X509Certificate2 certificate, IList <String> domainNames = null ) { using (var cfrg = new CertificateFactoryRandomGenerator()) { SecureRandom random = new SecureRandom(cfrg); // try to get signing/private key from certificate passed in AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(certificate); RsaKeyParameters publicKey = GetPublicKeyParameter(certificate); ISignatureFactory signatureFactory = new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random); Asn1Set attributes = null; X509SubjectAltNameExtension alternateName = null; foreach (System.Security.Cryptography.X509Certificates.X509Extension extension in certificate.Extensions) { if (extension.Oid.Value == X509SubjectAltNameExtension.SubjectAltNameOid || extension.Oid.Value == X509SubjectAltNameExtension.SubjectAltName2Oid) { alternateName = new X509SubjectAltNameExtension(extension, extension.Critical); break; } } domainNames = domainNames ?? new List <String>(); if (alternateName != null) { foreach (var name in alternateName.DomainNames) { if (!domainNames.Any(s => s.Equals(name, StringComparison.OrdinalIgnoreCase))) { domainNames.Add(name); } } foreach (var ipAddress in alternateName.IPAddresses) { if (!domainNames.Any(s => s.Equals(ipAddress, StringComparison.OrdinalIgnoreCase))) { domainNames.Add(ipAddress); } } } if (domainNames.Count > 0) { List <GeneralName> generalNames = CreateSubjectAlternateNameDomains(domainNames); if (generalNames.Count > 0) { IList oids = new ArrayList(); IList values = new ArrayList(); oids.Add(X509Extensions.SubjectAlternativeName); values.Add(new Org.BouncyCastle.Asn1.X509.X509Extension(false, new DerOctetString(new GeneralNames(generalNames.ToArray()).GetDerEncoded()))); AttributePkcs attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(oids, values))); attributes = new DerSet(attribute); } } Pkcs10CertificationRequest pkcs10CertificationRequest = new Pkcs10CertificationRequest( signatureFactory, new CertificateFactoryX509Name(false, certificate.Subject), publicKey, attributes, signingKey); return(pkcs10CertificationRequest.GetEncoded()); } }
public bool verifyotp() { if (skipotp) { return(true); } // check if is a fmuv2 and bootloader >= 4 else fail; // 9 = fmuv2 // 5 = px4 1.x if (board_type == 9) // &&up.bl_rev >= 4 { try { // get the device sn byte[] sn = __get_sn(); string line = ""; line = "SN: "; for (int s = 0; s < sn.Length; s += 1) { line += sn[s].ToString("X2"); } print(line); // 20 bytes - sha1 Array.Resize(ref sn, 20); if (ByteArrayCompare(sn, new byte[] { 0x00, 0x23, 0x00, 0x30, 0x35, 0x32, 0x47, 0x18, 0x36, 0x34, 0x30, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })) { print("Libre bootloader"); libre = true; print("Forged Key"); throw new InvalidKeyException("Invalid Board"); } if (ByteArrayCompare(sn, new byte[] { 0x00, 0x38, 0x00, 0x1F, 0x34, 0x32, 0x47, 0x0D, 0x31, 0x32, 0x35, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })) { // pixhawk lite // please sign your board via the proper process. // nuttx has an auth command. use it. print("Forged Key"); throw new InvalidKeyException("Invalid Board"); } if (ByteArrayCompare(sn, new byte[] { 0x00, 0x38, 0x00, 0x21, 0x31, 0x34, 0x51, 0x17, 0x33, 0x36, 0x38, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })) { // pixfalcon print("Forged Key"); throw new InvalidKeyException("Invalid Board"); } object obj = new otp(); byte[] test = __read_otp(); ByteArrayToStructure(test, ref obj); otp otp = (otp)obj; print("id: " + otp.id_type.ToString("X")); print("vid: " + otp.vid.ToString("X")); print("pid: " + otp.pid.ToString("X")); if (otp.h1 == 'P' && otp.h2 == 'X' && otp.h3 == '4' && otp.h4 == '\0') { // no vendor checks yet byte[] sig = otp.signature; line = ""; for (int s = 0; s < 512; s += 1) { line += test[s].ToString("X2"); if (s % 16 == 15) { print(line); line = ""; } } /* * byte[] PEMbuffer = Convert.FromBase64String(@""); */ // RSACryptoServiceProvider rsa = DecodeRsaPrivateKey(PEMbuffer); // RSAParameters rsapublic = rsa.ExportParameters(false); foreach (var cert in certs) { byte[] pubpem = Convert.FromBase64String(cert.Value); AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(pubpem); RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter; RSAParameters rsaParameters = new RSAParameters(); rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(); rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(rsaParameters); bool valid = rsa.VerifyHash(sn, CryptoConfig.MapNameToOID("SHA1"), otp.signature); if (valid) { print("Valid Key"); return(true); } } print("Invalid Key"); throw new InvalidKeyException("Invalid Board"); } else { print("Failed Header Check"); throw new FormatException("Failed Header Check"); } } catch { print("Failed to read Certificate of Authenticity"); throw; } } // not board type 9 return(true); }
public BlindingRsaPubKey(RsaKeyParameters keyParameters) { KeyParameters = keyParameters ?? throw new ArgumentNullException(nameof(keyParameters)); }
private void doTestDudPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { checkForPkcs1Exception(pubParameters, privParameters, dudBlock, "unknown block type"); }
private void doTestMissingDataPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { checkForPkcs1Exception(pubParameters, privParameters, missingDataBlock, "no data in block"); }
/// <summary> /// Creates a cert with the connectionstring (token) and stores it in the given cert store. /// </summary> public static async Task WriteAsync(string name, string connectionString, string storeType, string storePath) { if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentException("Token not found in X509Store and no new token provided!"); } SecureRandom random = new SecureRandom(); KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048); RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair keys = keyPairGenerator.GenerateKeyPair(); ArrayList nameOids = new ArrayList(); nameOids.Add(X509Name.CN); ArrayList nameValues = new ArrayList(); nameValues.Add(name); X509Name subjectDN = new X509Name(nameOids, nameValues); X509Name issuerDN = subjectDN; X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); cg.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random)); cg.SetIssuerDN(issuerDN); cg.SetSubjectDN(subjectDN); cg.SetNotBefore(DateTime.Now); cg.SetNotAfter(DateTime.Now.AddMonths(12)); cg.SetPublicKey(keys.Public); cg.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment)); // encrypt the token with the public key so only the owner of the assoc. private key can decrypt it and // "hide" it in the instruction code cert extension RSA rsa = RSA.Create(); RSAParameters rsaParams = new RSAParameters(); RsaKeyParameters keyParams = (RsaKeyParameters)keys.Public; rsaParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length]; keyParams.Modulus.ToByteArrayUnsigned().CopyTo(rsaParams.Modulus, 0); rsaParams.Exponent = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length]; keyParams.Exponent.ToByteArrayUnsigned().CopyTo(rsaParams.Exponent, 0); rsa.ImportParameters(rsaParams); if (rsa != null) { byte[] bytes = rsa.Encrypt(Encoding.ASCII.GetBytes(connectionString), RSAEncryptionPadding.OaepSHA1); if (bytes != null) { cg.AddExtension(X509Extensions.InstructionCode, false, bytes); } else { throw new CryptographicException("Can not encrypt IoTHub security token using generated public key!"); } } // sign the cert with the private key ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keys.Private, random); Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory); // create a PKCS12 store for the cert and its private key X509Certificate2 certificate = null; using (MemoryStream pfxData = new MemoryStream()) { Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder(); builder.SetUseDerEncoding(true); Pkcs12Store pkcsStore = builder.Build(); X509CertificateEntry[] chain = new X509CertificateEntry[1]; string passcode = Guid.NewGuid().ToString(); chain[0] = new X509CertificateEntry(x509); pkcsStore.SetKeyEntry(name, new AsymmetricKeyEntry(keys.Private), chain); pkcsStore.Save(pfxData, passcode.ToCharArray(), random); // create X509Certificate2 object from PKCS12 file certificate = CertificateFactory.CreateCertificateFromPKCS12(pfxData.ToArray(), passcode); // handle each store type differently switch (storeType) { case CertificateStoreType.Directory: { // Add to DirectoryStore using (DirectoryCertificateStore store = new DirectoryCertificateStore()) { store.Open(storePath); X509CertificateCollection certificates = await store.Enumerate().ConfigureAwait(false); // remove any existing cert with our name from the store foreach (X509Certificate2 cert in certificates) { if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase)) { await store.Delete(cert.Thumbprint).ConfigureAwait(false); } } // add new one await store.Add(certificate).ConfigureAwait(false); } break; } case CertificateStoreType.X509Store: { // Add to X509Store using (X509Store store = new X509Store(storePath, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadWrite); // remove any existing cert with our name from the store foreach (X509Certificate2 cert in store.Certificates) { if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase)) { store.Remove(cert); } } // add new cert to store try { store.Add(certificate); } catch (Exception e) { throw new Exception($"Not able to add cert to the requested store type '{storeType}' (exception message: '{e.Message}'."); } } break; } default: { throw new Exception($"The requested store type '{storeType}' is not supported. Please change."); } } return; } }
public Stream Decrypt(EncryptionMethod encryptionMethod, KeyInfo keyInfo, Stream toDecrypt) { Assert.NotNull(encryptionMethod); Assert.NotNull(keyInfo); Assert.NotNull(toDecrypt); Assert.True(encryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncAES128Url || encryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncAES192Url || encryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncAES256Url); Assert.Equal(keyInfo.Count, 1); byte[] decryptedKey = null; foreach (KeyInfoClause clause in keyInfo) { if (clause is KeyInfoEncryptedKey) { KeyInfoEncryptedKey encryptedKeyInfo = clause as KeyInfoEncryptedKey; EncryptedKey encryptedKey = encryptedKeyInfo.EncryptedKey; Assert.Equal(encryptedKey.EncryptionMethod.KeyAlgorithm, EncryptedXml.XmlEncRSAOAEPUrl); Assert.Equal(encryptedKey.KeyInfo.Count, 1); Assert.NotEqual(_asymmetricKeys.Count, 0); RsaKeyParameters rsaParams = null; RsaKeyParameters rsaInputParams = null; foreach (KeyInfoClause rsa in encryptedKey.KeyInfo) { if (rsa is RSAKeyValue) { rsaParams = (rsa as RSAKeyValue).Key; break; } else { Assert.True(false, "Invalid License - MalformedKeyInfoClause"); } } bool keyMismatch = true; foreach (AsymmetricCipherKeyPair key in _asymmetricKeys) { RsaKeyParameters rsaKey = key.Private as RsaKeyParameters; Assert.NotNull(rsaKey); rsaInputParams = key.Public as RsaKeyParameters; Assert.NotNull(rsaInputParams); if (!PublicKeysEqual(rsaParams, rsaInputParams)) { continue; } keyMismatch = false; // Decrypt session key byte[] encryptedKeyValue = encryptedKey.CipherData.CipherValue; if (encryptedKeyValue == null) { throw new System.Security.Cryptography.CryptographicException("MissingKeyCipher"); } decryptedKey = EncryptedXml.DecryptKey(encryptedKeyValue, rsaKey, true); break; } if (keyMismatch) { throw new Exception("Invalid License - AsymmetricKeyMismatch"); } } else if (clause is KeyInfoName) { Assert.True(false, "This test should not have KeyInfoName clauses"); } else { throw new System.Security.Cryptography.CryptographicException("MalformedKeyInfoClause"); } break; } if (decryptedKey == null) { throw new System.Security.Cryptography.CryptographicException("KeyDecryptionFailure"); } return(DecryptStream(toDecrypt, new KeyParameter(decryptedKey), "AES/CBC/PKCS7")); }
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 ENABLE_EC 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))); } #endif 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 ENABLE_EC 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))); } #endif 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 ENABLE_EC if (key is ECPrivateKeyParameters) { ECPrivateKeyParameters priv = (ECPrivateKeyParameters)key; ECDomainParameters dp = priv.Parameters; int orderBitLength = dp.N.BitLength; AlgorithmIdentifier algID; ECPrivateKeyStructure ec; if (priv.AlgorithmName == "ECGOST3410") { if (priv.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( priv.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); algID = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x2001, gostParams); // TODO Do we need to pass any parameters here? ec = new ECPrivateKeyStructure(orderBitLength, priv.D); } else { X962Parameters x962; if (priv.PublicKeyParamSet == null) { X9ECParameters ecP = new X9ECParameters(dp.Curve, dp.G, dp.N, dp.H, dp.GetSeed()); x962 = new X962Parameters(ecP); } else { x962 = new X962Parameters(priv.PublicKeyParamSet); } // TODO Possible to pass the publicKey bitstring here? ec = new ECPrivateKeyStructure(orderBitLength, priv.D, x962); algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962); } return(new PrivateKeyInfo(algID, ec)); } 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))); } #endif throw new ArgumentException("Class provided is not convertible: " + Platform.GetTypeName(key)); }
public void SetKey(RsaKeyParameters rsaKeyParameter) { this.key = rsaKeyParameter; }
public void TestCreationRSA() { BigInteger rsaPubMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPubExp = new BigInteger(Base64.Decode("EQ==")); BigInteger rsaPrivMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPrivDP = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ==")); BigInteger rsaPrivDQ = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ==")); BigInteger rsaPrivExp = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E=")); BigInteger rsaPrivP = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE=")); BigInteger rsaPrivQ = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0=")); BigInteger rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg==")); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaPubMod, rsaPubExp); RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv); IDictionary attrs = new Hashtable(); attrs[X509Name.C] = "AU"; attrs[X509Name.O] = "The Legion of the Bouncy Castle"; attrs[X509Name.L] = "Melbourne"; attrs[X509Name.ST] = "Victoria"; attrs[X509Name.E] = "*****@*****.**"; IList ord = new ArrayList(); ord.Add(X509Name.C); ord.Add(X509Name.O); ord.Add(X509Name.L); ord.Add(X509Name.ST); ord.Add(X509Name.E); IList values = new ArrayList(); values.Add("AU"); values.Add("The Legion of the Bouncy Castle"); values.Add("Melbourne"); values.Add("Victoria"); values.Add("*****@*****.**"); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, attrs)); certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1)); certGen.SetNotAfter(DateTime.UtcNow.AddDays(1)); certGen.SetSubjectDN(new X509Name(ord, attrs)); certGen.SetPublicKey(rsaPublic); certGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); X509Certificate cert = certGen.Generate(rsaPrivate); // Assert.IsTrue((cert.IsValidNow && cert.Verify(rsaPublic)),"Certificate failed to be valid (RSA)"); cert.CheckValidity(); cert.Verify(rsaPublic); //Console.WriteLine(ASN1Dump.DumpAsString(cert.ToAsn1Object())); //ISet dummySet = cert.GetNonCriticalExtensionOids(); //if (dummySet != null) //{ // foreach (string key in dummySet) // { // Console.WriteLine("\t{0}:\t{1}", key); // } //} //Console.WriteLine(); //dummySet = cert.GetNonCriticalExtensionOids(); //if (dummySet != null) //{ // foreach (string key in dummySet) // { // Console.WriteLine("\t{0}:\t{1}", key); // } //} //Console.WriteLine(); }
static void Main(string[] args) { n = Int32.Parse(args[0]); TcpListener server = null; Int32 port = 13000; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); server = new TcpListener(localAddr, port); server.Start(); TcpClient client = server.AcceptTcpClient(); NetworkStream stream = client.GetStream(); Console.WriteLine("Connected!"); byte[] bytes; string response; Random random = new Random(); int N = random.Next(); bytes = System.Text.Encoding.ASCII.GetBytes(N.ToString()); stream.Write(bytes, 0, bytes.Length); bytes = new byte[64]; stream.Read(bytes, 0, bytes.Length); byte[] v = bytes; Console.WriteLine(v.Length); bytes = new byte[20480]; stream.Read(bytes, 0, bytes.Length); string P_str = System.Text.Encoding.ASCII.GetString(bytes, 0, bytes.Length); string[] temp_split; temp_split = P_str.Split("|"); Org.BouncyCastle.Math.BigInteger[] x = new Org.BouncyCastle.Math.BigInteger[n + 1]; for (int i = 0; i < n + 1; ++i) { x[i] = new Org.BouncyCastle.Math.BigInteger(temp_split[i]); } Org.BouncyCastle.Math.BigInteger[] M = new Org.BouncyCastle.Math.BigInteger[n + 1]; for (int i = 0; i < n + 1; ++i) { M[i] = new Org.BouncyCastle.Math.BigInteger(temp_split[i + n + 1]); } RsaKeyParameters[] P = new RsaKeyParameters[n + 1]; for (int i = 0; i < n + 1; ++i) { P[i] = new RsaKeyParameters(false, M[i], x[i]); } string[] X0 = new string[n + 1]; for (int i = 0; i < n + 1; ++i) { X0[i] = temp_split[i + n + n + 2]; } byte[][] X = new byte[n + 1][]; for (int i = 0; i < n + 1; ++i) { UTF8Encoding utf8enc = new UTF8Encoding(); X[i] = utf8enc.GetBytes(X0[i]); } ring_verify(P, v, X, N.ToString()); //End time DateTime now = DateTime.Now; Console.WriteLine("Strat Second: {0}", now.Millisecond); }
public override void PerformTest() { IX509AttributeCertificate aCert = new X509V2AttributeCertificate(attrCert); X509CertificateParser fact = new X509CertificateParser(); X509Certificate sCert = fact.ReadCertificate(signCert); aCert.Verify(sCert.GetPublicKey()); // // search test // IList list = new ArrayList(); list.Add(sCert); // CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); // CertStore store = CertStore.getInstance("Collection", ccsp); IX509Store store = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(list)); ArrayList certs = new ArrayList( // store.getCertificates(aCert.getIssuer())); store.GetMatches(aCert.Issuer)); if (certs.Count != 1 || !certs.Contains(sCert)) { Fail("sCert not found by issuer"); } X509Attribute[] attrs = aCert.GetAttributes("1.3.6.1.4.1.6760.8.1.1"); if (attrs == null || attrs.Length != 1) { Fail("attribute not found"); } // // reencode test // aCert = new X509V2AttributeCertificate(aCert.GetEncoded()); aCert.Verify(sCert.GetPublicKey()); IX509AttributeCertificate saCert = new X509V2AttributeCertificate(aCert.GetEncoded()); if (!aCert.NotAfter.Equals(saCert.NotAfter)) { Fail("failed date comparison"); } // base generator test // // a sample key pair. // RsaKeyParameters pubKey = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); IAsymmetricKeyParameter privKey = RSA_PRIVATE_KEY_SPEC; // // set up the keys // // PrivateKey privKey; // PublicKey pubKey; // // KeyFactory kFact = KeyFactory.getInstance("RSA"); // // privKey = kFact.generatePrivate(privKeySpec); // pubKey = kFact.generatePublic(pubKeySpec); X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator(); gen.AddAttribute(attrs[0]); gen.SetHolder(aCert.Holder); gen.SetIssuer(aCert.Issuer); gen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); gen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); gen.SetSerialNumber(aCert.SerialNumber); gen.SetSignatureAlgorithm("SHA1WithRSAEncryption"); aCert = gen.Generate(privKey); aCert.CheckValidity(); aCert.Verify(pubKey); // as the issuer is the same this should still work (even though it is not // technically correct certs = new ArrayList( // store.getCertificates(aCert.Issuer)); store.GetMatches(aCert.Issuer)); if (certs.Count != 1 || !certs.Contains(sCert)) { Fail("sCert not found by issuer"); } attrs = aCert.GetAttributes("1.3.6.1.4.1.6760.8.1.1"); if (attrs == null || attrs.Length != 1) { Fail("attribute not found"); } // // reencode test // aCert = new X509V2AttributeCertificate(aCert.GetEncoded()); aCert.Verify(pubKey); AttributeCertificateIssuer issuer = aCert.Issuer; X509Name[] principals = issuer.GetPrincipals(); // // test holder // AttributeCertificateHolder holder = aCert.Holder; if (holder.GetEntityNames() == null) { Fail("entity names not set"); } if (holder.SerialNumber != null) { Fail("holder serial number set when none expected"); } if (holder.GetIssuer() != null) { Fail("holder issuer set when none expected"); } principals = holder.GetEntityNames(); string ps = principals[0].ToString(); // TODO Check that this is a good enough test // if (!ps.Equals("C=US, O=vt, OU=Class 2, OU=Virginia Tech User, CN=Markus Lorch (mlorch), [email protected]")) if (!principals[0].Equivalent(new X509Name("C=US, O=vt, OU=Class 2, OU=Virginia Tech User, CN=Markus Lorch (mlorch), [email protected]"))) { Fail("principal[0] for entity names don't Match"); } // // extension test // gen.AddExtension("1.1", true, new DerOctetString(new byte[10])); gen.AddExtension("2.2", false, new DerOctetString(new byte[20])); aCert = gen.Generate(privKey); ISet exts = aCert.GetCriticalExtensionOids(); if (exts.Count != 1 || !exts.Contains("1.1")) { Fail("critical extension test failed"); } exts = aCert.GetNonCriticalExtensionOids(); if (exts.Count != 1 || !exts.Contains("2.2")) { Fail("non-critical extension test failed"); } Asn1OctetString extString = aCert.GetExtensionValue(new DerObjectIdentifier("1.1")); Asn1Encodable extValue = X509ExtensionUtilities.FromExtensionValue(extString); if (!extValue.Equals(new DerOctetString(new byte[10]))) { Fail("wrong extension value found for 1.1"); } doTestCertWithBaseCertificateID(); doTestGenerateWithCert(); doTestGenerateWithPrincipal(); }
private void doTestGenerateWithPrincipal() { X509CertificateParser fact = new X509CertificateParser(); X509Certificate iCert = fact.ReadCertificate(signCert); // // a sample key pair. // RsaKeyParameters pubKey = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); // // set up the keys // // PrivateKey privKey; // PublicKey pubKey; // // KeyFactory kFact = KeyFactory.getInstance("RSA"); // // privKey = kFact.generatePrivate(RSA_PRIVATE_KEY_SPEC); // pubKey = kFact.generatePublic(pubKeySpec); IAsymmetricKeyParameter privKey = RSA_PRIVATE_KEY_SPEC; X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator(); // the actual attributes GeneralName roleName = new GeneralName(GeneralName.Rfc822Name, "DAU123456789"); // roleSyntax OID: 2.5.24.72 X509Attribute attributes = new X509Attribute("2.5.24.72", new DerSequence(roleName)); gen.AddAttribute(attributes); gen.SetHolder(new AttributeCertificateHolder(iCert.SubjectDN)); gen.SetIssuer(new AttributeCertificateIssuer(new X509Name("cn=test"))); gen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); gen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); gen.SetSerialNumber(BigInteger.One); gen.SetSignatureAlgorithm("SHA1WithRSAEncryption"); IX509AttributeCertificate aCert = gen.Generate(privKey); aCert.CheckValidity(); aCert.Verify(pubKey); AttributeCertificateHolder holder = aCert.Holder; if (holder.GetEntityNames() == null) { Fail("entity names not set when expected"); } if (holder.SerialNumber != null) { Fail("holder serial number found when none expected"); } if (holder.GetIssuer() != null) { Fail("holder issuer found when none expected"); } if (!holder.Match(iCert)) { Fail("generated holder not matching holder certificate"); } X509Certificate sCert = fact.ReadCertificate(holderCertWithBaseCertificateID); if (holder.Match(sCert)) { Fail("principal generated holder matching wrong certificate"); } equalityAndHashCodeTest(aCert, aCert.GetEncoded()); }
/// <summary> /// 公钥解密 /// </summary> /// <param name="publicKey">RSA公钥</param> /// <param name="contentData">待解密数据</param> /// <param name="algorithm">加密算法</param> /// <returns></returns> public static byte[] DecryptWithPublicKey(byte[] publicKey, byte[] contentData, string algorithm = "RSA/ECB/PKCS1Padding") { RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(publicKey); return(Transform(publicKeyParam, contentData, algorithm, false)); }
public static void ring_authenticate(SslStream sslStream) { byte[][] X = new byte[11][]; Random rnd = new Random(); for (int i = 0; i < 11; ++i) { UTF8Encoding utf8enc = new UTF8Encoding(); X[i] = utf8enc.GetBytes(rnd.Next().ToString()); } RsaKeyParameters[] P = new RsaKeyParameters[11]; for (int i = 0; i < 10; ++i) { RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator(); rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512)); Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair(); RsaKeyParameters publicKey = (RsaKeyParameters)keyPair.Public; IAsymmetricBlockCipher cipher = new RsaEngine(); P[i + 1] = publicKey; } RsaKeyPairGenerator rsaKeyPairGnr_s = new RsaKeyPairGenerator(); rsaKeyPairGnr_s.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512)); Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair_s = rsaKeyPairGnr_s.GenerateKeyPair(); P[0] = (RsaKeyParameters)keyPair_s.Public; RsaKeyParameters Ks = (RsaKeyParameters)keyPair_s.Private; string m = "Hello!!"; byte[] v = ring_sign(P, m, Ks, X); Console.WriteLine("v: " + ByteArrayToString(v)); Console.WriteLine(); String P_str = ""; for (int i = 0; i < 11; ++i) { byte[] publicKeyDer = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(P[i]).GetDerEncoded(); P_str = P_str + Convert.ToBase64String(publicKeyDer) + "|"; } String X_str = ""; for (int i = 0; i < 11; ++i) { X_str = X_str + Encoding.ASCII.GetString(X[i]) + "|"; } Console.WriteLine(P_str); Console.WriteLine(X_str); byte[] data = Encoding.UTF8.GetBytes(P_str); sslStream.Write(data); sslStream.Flush(); data = Encoding.UTF8.GetBytes(X_str); sslStream.Write(data); sslStream.Flush(); TCPCommunication.send_message_tcp(sslStream, m); sslStream.Write(v); sslStream.Flush(); }
/// <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 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 ECParraN, ECParraH); ECDomainParameters ecDomain = new ECDomainParameters( curve, curve.ValidatePoint(ECParraGX, ECParraGY), ECParraN, ECParraH); ECPublicKeyParameters ecPub = new ECPublicKeyParameters( curve.ValidatePoint(ECPubQX, 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.ToUpper(CultureInfo.InvariantCulture); 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."); } }
private void RequestPublicKey() { RsaKeyParameters keys = GenerateKeysFromPem(rawPubkey); publicKey = keys; }
private static bool PublicKeysEqual(RsaKeyParameters a, RsaKeyParameters b) { return(a.Exponent.Equals(b.Exponent) && a.Modulus.Equals(b.Modulus)); }
/// <summary> /// Creates a certificate signing request from an /// existing certificate with a private key. /// </summary> public static byte[] CreateSigningRequest( X509Certificate2 certificate, IList <String> domainNames = null ) { if (certificate == null) { throw new ArgumentNullException(nameof(certificate)); } using (var cfrg = new CertificateFactoryRandomGenerator()) { SecureRandom random = new SecureRandom(cfrg); // try to get signing/private key from certificate passed in AsymmetricKeyParameter signingKey = X509Utils.GetPrivateKeyParameter(certificate); RsaKeyParameters publicKey = X509Utils.GetPublicKeyParameter(certificate); ISignatureFactory signatureFactory = new Asn1SignatureFactory(X509Utils.GetRSAHashAlgorithm(X509Defaults.HashAlgorithmName), signingKey, random); Asn1Set attributes = null; var san = X509Extensions.FindExtension <X509SubjectAltNameExtension>(certificate); X509SubjectAltNameExtension alternateName = new X509SubjectAltNameExtension(san, san.Critical); string applicationUri = null; domainNames = domainNames ?? new List <String>(); if (alternateName != null) { if (alternateName.Uris.Count > 0) { applicationUri = alternateName.Uris[0]; } foreach (var name in alternateName.DomainNames) { if (!domainNames.Any(s => s.Equals(name, StringComparison.OrdinalIgnoreCase))) { domainNames.Add(name); } } foreach (var ipAddress in alternateName.IPAddresses) { if (!domainNames.Any(s => s.Equals(ipAddress, StringComparison.OrdinalIgnoreCase))) { domainNames.Add(ipAddress); } } } // build CSR extensions var generalNames = new List <GeneralName>(); if (applicationUri != null) { generalNames.Add(new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri)); } if (domainNames.Count > 0) { generalNames.AddRange(BouncyCastle.X509Extensions.CreateSubjectAlternateNameDomains(domainNames)); } if (generalNames.Count > 0) { IList oids = new ArrayList(); IList values = new ArrayList(); oids.Add(Org.BouncyCastle.Asn1.X509.X509Extensions.SubjectAlternativeName); values.Add(new Org.BouncyCastle.Asn1.X509.X509Extension(false, new DerOctetString(new GeneralNames(generalNames.ToArray()).GetDerEncoded()))); var attribute = new Org.BouncyCastle.Asn1.Pkcs.AttributePkcs(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new Org.BouncyCastle.Asn1.X509.X509Extensions(oids, values))); attributes = new DerSet(attribute); } var pkcs10CertificationRequest = new Pkcs10CertificationRequest( signatureFactory, new CertificateFactoryX509Name(false, certificate.Subject), publicKey, attributes); return(pkcs10CertificationRequest.GetEncoded()); } }
private void doTestTruncatedPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { checkForPkcs1Exception(pubParameters, privParameters, truncatedDataBlock, "block truncated"); }
/// <summary> /// Antragstellung /// </summary> /// <param name="application">Antrag</param> /// <param name="certStore">Zertifikat-Speicher für die Ermittlung der Zertifikatskette des Absender-Zertifikats</param> /// <param name="pfx">Absender-Zertifikat für die Signierung des Antrags</param> /// <returns>Ergebnis der Antragstellung</returns> public async Task <OstcApplicationResult> SendApplicationAsync([NotNull] OstcAntrag application, [CanBeNull] IOstcCertificateStore certStore, [CanBeNull] Pkcs12Store pfx) { var now = DateTime.Now; application.Antragsteller.IK_BN = Sender.SenderId.ToString(); RsaPrivateCrtKeyParameters rsaPrivateKey; AsymmetricCipherKeyPair rsaKeyPair; X509Certificate certificate; if (pfx != null) { var alias = pfx.Aliases.Cast <string>().First(pfx.IsKeyEntry); rsaPrivateKey = (RsaPrivateCrtKeyParameters)pfx.GetKey(alias).Key; var rsaPublicKey = new RsaKeyParameters(false, rsaPrivateKey.Modulus, rsaPrivateKey.PublicExponent); rsaKeyPair = new AsymmetricCipherKeyPair(rsaPublicKey, rsaPrivateKey); certificate = pfx.GetCertificate(alias).Certificate; } else { var keyPairGen = new RsaKeyPairGenerator(); keyPairGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); rsaKeyPair = keyPairGen.GenerateKeyPair(); rsaPrivateKey = (RsaPrivateCrtKeyParameters)rsaKeyPair.Private; certificate = null; } var requester = new Requester(application.Antragsteller.IK_BN, application.Antragsteller.Firma, application.Antragsteller.Nachname); var p10Creator = new Pkcs10Creator(requester, rsaKeyPair); var p10Data = p10Creator.CreateRequest(); application.Antragsinfo.Requestschlüssel = p10Data.CertRequestDer; var applicationData = OstcUtils.Serialize(application, Iso88591); ValidateData(applicationData, OstcMessageType.ApplicationData); var receiver = Sender.SenderId.CommunicationServerReceiver; if (certificate != null) { Debug.Assert(certStore != null, "certStore != null"); var certChain = certStore.GetChain(certificate).ToList(); Debug.Assert(certChain[0].SubjectDN.Equivalent(certificate.SubjectDN)); certChain.RemoveAt(0); applicationData = OstcUtils.SignData(applicationData, rsaPrivateKey, certificate, certChain); var receiverCert = certStore.GetCertificate(receiver); applicationData = OstcUtils.EncryptData(applicationData, receiverCert); } var fileName = $"{application.Antragsteller.IK_BN}_{now.Date:ddMMyyyy}.xml"; var message = new TransportRequestType() { version = SupportedVersionsType.Item11, profile = ExtraProfileOstc, TransportHeader = CreateRequestHeader(now, OstcDataType.Application, ExtraScenario.RequestWithAcknowledgement), TransportBody = new TransportRequestBodyType { Items = new object[] { new DataType { Item = new Base64CharSequenceType() { Value = applicationData, }, }, }, }, }; if (certificate != null) { message.TransportPlugIns = new AnyPlugInContainerType { Items = new object[] { new DataTransformsType { version = "1.1", Encryption = new[] { new EncryptionType { order = "1", Algorithm = new EncryptionAlgorithmType { id = ExtraEncryption.Pkcs7, Specification = new SpecificationType { url = "http://www.gkv-datenaustausch.de", name = "Security-Schnittstelle fuer den Datenaustausch im Gesundheitswesen", }, }, }, }, }, new DataSourceType { version = "1.1", DataContainer = new DataContainerType { type = ExtraContainerType.File, name = fileName, created = now, createdSpecified = true, encoding = ExtraContainerEncoding.Utf8, } }, }, }; } ValidateRequest(message, OstcMessageType.Application); var messageData = OstcExtraSerializer.Iso88591.Serialize(message); var request = CreateRequest(Network.Requests.Application); using (var requestStream = await Task.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null)) { requestStream.Write(messageData, 0, messageData.Length); } using (var response = await Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)) { var serializer = new XmlSerializer(typeof(TransportResponseType)); var responseData = (TransportResponseType)serializer.Deserialize(response.GetResponseStream()); var flags = responseData.TransportHeader.GetFlags().ToList(); if (flags.Any(x => x.weight == ExtraFlagWeight.Error)) { throw new Ostc2Exception(flags); } return(new OstcApplicationResult { OrderId = responseData.TransportHeader.ResponseDetails.ResponseID.Value, Pkcs10 = p10Data.CertRequestDer, RSA = rsaPrivateKey, Hash = p10Data.PublicKeyHashRaw, }); } }
private void doTestWrongPaddingPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { checkForPkcs1Exception(pubParameters, privParameters, incorrectPadding, "block padding incorrect"); }
public RSAKeyValue(RsaKeyParameters key) { rsa = key; }
public override void PerformTest() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp); RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef); byte[] data = Hex.Decode(edgeInput); // // RAW // IAsymmetricBlockCipher eng = new RsaBlindedEngine(); eng.Init(true, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("RSA: failed - exception " + e.ToString(), e); } eng.Init(false, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!edgeInput.Equals(Hex.ToHexString(data))) { Fail("failed RAW edge Test"); } data = Hex.Decode(input); eng.Init(true, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed RAW Test"); } // // PKCS1 - public encrypt, private decrypt // eng = new Pkcs1Encoding(eng); eng.Init(true, pubParameters); if (eng.GetOutputBlockSize() != ((Pkcs1Encoding)eng).GetUnderlyingCipher().GetOutputBlockSize()) { Fail("PKCS1 output block size incorrect"); } try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed PKCS1 public/private Test"); } // // PKCS1 - private encrypt, public decrypt // eng = new Pkcs1Encoding(((Pkcs1Encoding)eng).GetUnderlyingCipher()); eng.Init(true, privParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed PKCS1 private/public Test"); } // // key generation test // RsaKeyPairGenerator pGen = new RsaKeyPairGenerator(); RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25); pGen.Init(genParam); IAsymmetricCipherKeyPair pair = pGen.GenerateKeyPair(); eng = new RsaBlindedEngine(); if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 768) { Fail("failed key generation (768) length test"); } eng.Init(true, pair.Public); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, pair.Private); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed key generation (768) Test"); } genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25); pGen.Init(genParam); pair = pGen.GenerateKeyPair(); eng.Init(true, pair.Public); if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 1024) { Fail("failed key generation (1024) length test"); } try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } eng.Init(false, pair.Private); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (Exception e) { Fail("failed - exception " + e.ToString(), e); } if (!input.Equals(Hex.ToHexString(data))) { Fail("failed key generation (1024) test"); } doTestOaep(pubParameters, privParameters); doTestStrictPkcs1Length(pubParameters, privParameters); doTestDudPkcs1Block(pubParameters, privParameters); doTestMissingDataPkcs1Block(pubParameters, privParameters); doTestTruncatedPkcs1Block(pubParameters, privParameters); doTestWrongPaddingPkcs1Block(pubParameters, privParameters); try { new RsaBlindedEngine().ProcessBlock(new byte[] { 1 }, 0, 1); Fail("failed initialisation check"); } catch (InvalidOperationException) { // expected } }
public static RSA ToRSA(RsaKeyParameters rsaKey) { // TODO This appears to not work for private keys (when no CRT info) return(CreateRSAProvider(ToRSAParameters(rsaKey))); }
/** * Read a Key Pair */ private object ReadPrivateKey(PemObject pemObject) { // // extract the key // Debug.Assert(Platform.EndsWith(pemObject.Type, "PRIVATE KEY")); string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim(); byte[] keyBytes = pemObject.Content; IDictionary fields = Platform.CreateHashtable(); foreach (PemHeader header in pemObject.Headers) { fields[header.Name] = header.Value; } string procType = (string)fields["Proc-Type"]; if (procType == "4,ENCRYPTED") { if (pFinder == null) { throw new PasswordException("No password finder specified, but a password is required"); } char[] password = pFinder.GetPassword(); if (password == null) { throw new PasswordException("Password is null, but a password is required"); } string dekInfo = (string)fields["DEK-Info"]; string[] tknz = dekInfo.Split(','); string dekAlgName = tknz[0].Trim(); byte[] iv = Hex.Decode(tknz[1].Trim()); keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv); } try { AsymmetricKeyParameter pubSpec, privSpec; Asn1Sequence seq = Asn1Sequence.GetInstance(keyBytes); switch (type) { case "RSA": { if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); pubSpec = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent); privSpec = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); break; } case "DSA": { if (seq.Count != 6) { throw new PemException("malformed sequence in DSA private key"); } // TODO Create an ASN1 object somewhere for this? //DerInteger v = (DerInteger)seq[0]; DerInteger p = (DerInteger)seq[1]; DerInteger q = (DerInteger)seq[2]; DerInteger g = (DerInteger)seq[3]; DerInteger y = (DerInteger)seq[4]; DerInteger x = (DerInteger)seq[5]; DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value); privSpec = new DsaPrivateKeyParameters(x.Value, parameters); pubSpec = new DsaPublicKeyParameters(y.Value, parameters); break; } case "EC": { ECPrivateKeyStructure pKey = ECPrivateKeyStructure.GetInstance(seq); AlgorithmIdentifier algId = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters()); PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object()); // TODO Are the keys returned here ECDSA, as Java version forces? privSpec = PrivateKeyFactory.CreateKey(privInfo); DerBitString pubKey = pKey.GetPublicKey(); if (pubKey != null) { SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes()); // TODO Are the keys returned here ECDSA, as Java version forces? pubSpec = PublicKeyFactory.CreateKey(pubInfo); } else { pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey( (ECPrivateKeyParameters)privSpec); } break; } case "ENCRYPTED": { char[] password = pFinder.GetPassword(); if (password == null) { throw new PasswordException("Password is null, but a password is required"); } return(PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq))); } case "": { return(PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq))); } default: throw new ArgumentException("Unknown key type: " + type, "type"); } return(new AsymmetricCipherKeyPair(pubSpec, privSpec)); } catch (IOException e) { throw e; } catch (Exception e) { throw new PemException( "problem creating " + type + " private key: " + e.ToString()); } }
public override void PerformTest() { // // personal keys // RsaPublicKeyStructure pubKeySpec = new RsaPublicKeyStructure( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RsaPrivateCrtKeyParameters privKeySpec = new RsaPrivateCrtKeyParameters( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // // intermediate keys. // RsaPublicKeyStructure intPubKeySpec = new RsaPublicKeyStructure( new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), new BigInteger("ffff", 16)); RsaPrivateCrtKeyParameters intPrivKeySpec = new RsaPrivateCrtKeyParameters( new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), new BigInteger("ffff", 16), new BigInteger("7deb1b194a85bcfd29cf871411468adbc987650903e3bacc8338c449ca7b32efd39ffc33bc84412fcd7df18d23ce9d7c25ea910b1ae9985373e0273b4dca7f2e0db3b7314056ac67fd277f8f89cf2fd73c34c6ca69f9ba477143d2b0e2445548aa0b4a8473095182631da46844c356f5e5c7522eb54b5a33f11d730ead9c0cff", 16), new BigInteger("ef4cede573cea47f83699b814de4302edb60eefe426c52e17bd7870ec7c6b7a24fe55282ebb73775f369157726fcfb988def2b40350bdca9e5b418340288f649", 16), new BigInteger("97c7737d1b9a0088c3c7b528539247fd2a1593e7e01cef18848755be82f4a45aa093276cb0cbf118cb41117540a78f3fc471ba5d69f0042274defc9161265721", 16), new BigInteger("6c641094e24d172728b8da3c2777e69adfd0839085be7e38c7c4a2dd00b1ae969f2ec9d23e7e37090fcd449a40af0ed463fe1c612d6810d6b4f58b7bfa31eb5f", 16), new BigInteger("70b7123e8e69dfa76feb1236d0a686144b00e9232ed52b73847e74ef3af71fb45ccb24261f40d27f98101e230cf27b977a5d5f1f15f6cf48d5cb1da2a3a3b87f", 16), new BigInteger("e38f5750d97e270996a286df2e653fd26c242106436f5bab0f4c7a9e654ce02665d5a281f2c412456f2d1fa26586ef04a9adac9004ca7f913162cb28e13bf40d", 16)); // // ca keys // RsaPublicKeyStructure caPubKeySpec = new RsaPublicKeyStructure( new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), new BigInteger("11", 16)); RsaPrivateCrtKeyParameters caPrivKeySpec = new RsaPrivateCrtKeyParameters( new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), new BigInteger("11", 16), new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16), new BigInteger("f75e80839b9b9379f1cf1128f321639757dba514642c206bbbd99f9a4846208b3e93fbbe5e0527cc59b1d4b929d9555853004c7c8b30ee6a213c3d1bb7415d03", 16), new BigInteger("b892d9ebdbfc37e397256dd8a5d3123534d1f03726284743ddc6be3a709edb696fc40c7d902ed804c6eee730eee3d5b20bf6bd8d87a296813c87d3b3cc9d7947", 16), new BigInteger("1d1a2d3ca8e52068b3094d501c9a842fec37f54db16e9a67070a8b3f53cc03d4257ad252a1a640eadd603724d7bf3737914b544ae332eedf4f34436cac25ceb5", 16), new BigInteger("6c929e4e81672fef49d9c825163fec97c4b7ba7acb26c0824638ac22605d7201c94625770984f78a56e6e25904fe7db407099cad9b14588841b94f5ab498dded", 16), new BigInteger("dae7651ee69ad1d081ec5e7188ae126f6004ff39556bde90e0b870962fa7b926d070686d8244fe5a9aa709a95686a104614834b0ada4b10f53197a5cb4c97339", 16)); // // set up the keys // IAsymmetricKeyParameter caPrivKey = caPrivKeySpec; RsaKeyParameters caPubKey = new RsaKeyParameters(false, caPubKeySpec.Modulus, caPubKeySpec.PublicExponent); IAsymmetricKeyParameter intPrivKey = intPrivKeySpec; RsaKeyParameters intPubKey = new RsaKeyParameters(false, intPubKeySpec.Modulus, intPubKeySpec.PublicExponent); IAsymmetricKeyParameter privKey = privKeySpec; RsaKeyParameters pubKey = new RsaKeyParameters(false, pubKeySpec.Modulus, intPubKeySpec.PublicExponent); X509Certificate trustCert = CreateTrustCert(caPubKey, caPrivKeySpec); Asn1EncodableVector intPolicies = null; Hashtable map = null; Asn1EncodableVector policies = null; ISet requirePolicies = null; X509Certificate intCert = null; X509Certificate endCert = null; // valid test_00 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = null; string msg = TestPolicies(0, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(0, msg, ""); // test_01 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.1"); msg = TestPolicies(1, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(1, msg, ""); // test_02 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.5.29.32.0"); msg = TestPolicies(2, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(2, msg, ""); // test_03 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.3"))); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.1"); msg = TestPolicies(3, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(3, msg, ""); // test_04 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.3"))); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.3"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.3"); msg = TestPolicies(4, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(4, msg, ""); // test_05 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.2"); msg = TestPolicies(5, trustCert, intCert, endCert, requirePolicies, false); CheckMessage(5, msg, "Path processing failed on policy."); // test_06 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.1"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.1"); msg = TestPolicies(6, trustCert, intCert, endCert, requirePolicies, true); CheckMessage(6, msg, ""); // test_07 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.2"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.3"); msg = TestPolicies(7, trustCert, intCert, endCert, requirePolicies, false); CheckMessage(7, msg, "Path processing failed on policy."); // test_08 intPolicies = new Asn1EncodableVector(); intPolicies.Add(new PolicyInformation(new DerObjectIdentifier("2.5.29.32.0"))); map = new Hashtable(); map["2.16.840.1.101.3.2.1.48.1"] = "2.16.840.1.101.3.2.1.48.2"; intCert = CreateIntmedCert(intPubKey, caPrivKey, caPubKey, intPolicies, map); policies = new Asn1EncodableVector(); policies.Add(new PolicyInformation(new DerObjectIdentifier("2.16.840.1.101.3.2.1.48.3"))); endCert = CreateEndEntityCert(pubKey, intPrivKey, intPubKey, policies); requirePolicies = new HashSet(); requirePolicies.Add("2.16.840.1.101.3.2.1.48.1"); msg = TestPolicies(8, trustCert, intCert, endCert, requirePolicies, false); CheckMessage(8, msg, "Path processing failed on policy."); }
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"); } }
public static byte[] SafeDecryptPreMasterSecret(TlsContext context, RsaKeyParameters rsaServerPrivateKey, byte[] encryptedPreMasterSecret) { /* * RFC 5246 7.4.7.1. */ ProtocolVersion clientVersion = context.ClientVersion; // TODO Provide as configuration option? bool versionNumberCheckDisabled = false; /* * Generate 48 random bytes we can use as a Pre-Master-Secret, if the * PKCS1 padding check should fail. */ byte[] fallback = new byte[48]; context.SecureRandom.NextBytes(fallback); byte[] M = Arrays.Clone(fallback); try { Pkcs1Encoding encoding = new Pkcs1Encoding(new RsaBlindedEngine(), fallback); encoding.Init(false, new ParametersWithRandom(rsaServerPrivateKey, context.SecureRandom)); M = encoding.ProcessBlock(encryptedPreMasterSecret, 0, encryptedPreMasterSecret.Length); } catch (Exception) { /* * This should never happen since the decryption should never throw an exception * and return a random value instead. * * In any case, a TLS server MUST NOT generate an alert if processing an * RSA-encrypted premaster secret message fails, or the version number is not as * expected. Instead, it MUST continue the handshake with a randomly generated * premaster secret. */ } /* * If ClientHello.client_version is TLS 1.1 or higher, server implementations MUST * check the version number [..]. */ if (versionNumberCheckDisabled && clientVersion.IsEqualOrEarlierVersionOf(ProtocolVersion.TLSv10)) { /* * If the version number is TLS 1.0 or earlier, server * implementations SHOULD check the version number, but MAY have a * configuration option to disable the check. * * So there is nothing to do here. */ } else { /* * OK, we need to compare the version number in the decrypted Pre-Master-Secret with the * clientVersion received during the handshake. If they don't match, we replace the * decrypted Pre-Master-Secret with a random one. */ int correct = (clientVersion.MajorVersion ^ (M[0] & 0xff)) | (clientVersion.MinorVersion ^ (M[1] & 0xff)); correct |= correct >> 1; correct |= correct >> 2; correct |= correct >> 4; int mask = ~((correct & 1) - 1); /* * mask will be all bits set to 0xff if the version number differed. */ for (int i = 0; i < 48; i++) { M[i] = (byte)((M[i] & (~mask)) | (fallback[i] & mask)); } } return(M); }