public void TestRsaDigestSigner() { 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); byte[] msg = new byte[] { 1, 6, 3, 32, 7, 43, 2, 5, 7, 78, 4, 23 }; RsaDigestSigner signer = new RsaDigestSigner(new Sha1Digest()); signer.Init(true, rsaPrivate); signer.BlockUpdate(msg, 0, msg.Length); byte[] sig = signer.GenerateSignature(); signer.Init(false,rsaPublic); signer.BlockUpdate(msg, 0, msg.Length); Assert.IsTrue(signer.VerifySignature(sig), "RSA IDigest Signer failed."); }
public static byte[] GenerateEncryptedPreMasterSecret(SecureRandom random, RsaKeyParameters rsaServerPublicKey, Stream output) { /* * Choose a PremasterSecret and send it encrypted to the server */ byte[] premasterSecret = new byte[48]; random.NextBytes(premasterSecret); TlsUtilities.WriteVersion(premasterSecret, 0); Pkcs1Encoding encoding = new Pkcs1Encoding(new RsaBlindedEngine()); encoding.Init(true, new ParametersWithRandom(rsaServerPublicKey, random)); try { byte[] keData = encoding.ProcessBlock(premasterSecret, 0, premasterSecret.Length); TlsUtilities.WriteOpaque16(keData, output); } catch (InvalidCipherTextException) { /* * This should never happen, only during decryption. */ throw new TlsFatalAlert(AlertDescription.internal_error); } return premasterSecret; }
public override object GetPassword() { if (Settings.SslMode != MySqlSslMode.None) { // send as clear text, since the channel is already encrypted byte[] passBytes = this.Encoding.GetBytes(Settings.Password); byte[] buffer = new byte[passBytes.Length + 1]; Array.Copy(passBytes, 0, buffer, 0, passBytes.Length); buffer[passBytes.Length] = 0; return buffer; } else { #if BOUNCY_CASTLE_INCLUDED // send RSA encrypted, since the channel is not protected if (rawPubkey != null) { publicKey = GenerateKeysFromPem(rawPubkey); } if (publicKey == null) return new byte[] { 0x01 }; //RequestPublicKey(); else { byte[] bytes = GetRsaPassword(Settings.Password, AuthenticationData); if (bytes != null && bytes.Length == 1 && bytes[0] == 0) return null; return bytes; } #else throw new NotImplementedException( "You can use sha256 plugin only in SSL connections in this implementation." ); #endif } }
/// <summary> /// Genera la firma CADES /// </summary> /// <param name="data">Datos a firmar</param> /// <param name="privateKey">Clave privada usada para la firma</param> /// <param name="certificado">Certificado del firmante</param> /// <param name="algo">Algoritmo de firma</param> /// <param name="format">Formato de firma</param> /// <returns>Firma en formato binario</returns> public static byte[] getCades(byte[] data, RsaKeyParameters privateKey, byte[] certificado, string algo, string format) { GenCAdESEPESSignedData prueba = new GenCAdESEPESSignedData(); Dictionary<string, string> p1 = new Dictionary<string, string>(); p1.Add("format", format); p1.Add("mode", "implicit"); p1.Add("policyIdentifier", null); p1.Add("policyIdentifierHash", null); p1.Add("policyIdentifierHashAlgorithm", null); p1.Add("policyQualifier", null); p1.Add("signingCertificateV2", "false"); AdESPolicy politica = new AdESPolicy(p1); X509Certificate2 cert = new X509Certificate2(); cert.SetRawCertData(certificado); cert.SetKey(privateKey); X509Certificate2[] certs = new X509Certificate2[1]; certs[0] = cert; AOCAdESSigner cadesSigner = new AOCAdESSigner(); byte[] datos = cadesSigner.sign(data, algo, certs, p1); return datos; }
public override void ProcessServerCertificate(Certificate serverCertificate) { if (serverCertificate.IsEmpty) throw new TlsFatalAlert(AlertDescription.bad_certificate); X509CertificateStructure x509Cert = serverCertificate.GetCertificateAt(0); SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo; try { this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo); } catch (Exception e) { throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e); } // Sanity check the PublicKeyFactory if (this.mServerPublicKey.IsPrivate) throw new TlsFatalAlert(AlertDescription.internal_error); this.mRsaServerPublicKey = ValidateRsaPublicKey((RsaKeyParameters)this.mServerPublicKey); TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyEncipherment); base.ProcessServerCertificate(serverCertificate); }
public AsymmetricCipherKeyPair GetRsaKeyPair( RSACryptoServiceProvider rsaCsp) { RSAParameters rp = rsaCsp.ExportParameters(true); BigInteger modulus = new BigInteger(1, rp.Modulus); BigInteger pubExp = new BigInteger(1, rp.Exponent); RsaKeyParameters pubKey = new RsaKeyParameters( false, modulus, pubExp); RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( modulus, pubExp, new BigInteger(1, rp.D), new BigInteger(1, rp.P), new BigInteger(1, rp.Q), new BigInteger(1, rp.DP), new BigInteger(1, rp.DQ), new BigInteger(1, rp.InverseQ)); return new AsymmetricCipherKeyPair(pubKey, privKey); }
public GPSOAuthClient(string email, string password) { this.email = email; this.password = password; client = new HttpClient(); androidKey = GoogleKeyUtils.KeyFromB64(b64Key); }
public virtual void ProcessServerCertificate(Certificate serverCertificate) { X509CertificateStructure x509Cert = serverCertificate.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo; try { this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo); } // catch (RuntimeException) catch (Exception) { throw new TlsFatalAlert(AlertDescription.unsupported_certificate); } // Sanity check the PublicKeyFactory if (this.serverPublicKey.IsPrivate) { throw new TlsFatalAlert(AlertDescription.internal_error); } this.rsaServerPublicKey = ValidateRsaPublicKey((RsaKeyParameters)this.serverPublicKey); TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyEncipherment); // TODO /* * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the * signing algorithm for the certificate must be the same as the algorithm for the * certificate key." */ }
public BigIntegerRSAPublicKey(RsaKeyParameters rsaKeyParameters) { Debug.Assert(rsaKeyParameters != null); this.Modulus = rsaKeyParameters.Modulus; this.modulusAsString = rsaKeyParameters.Modulus.ToString(10); this.Exponent = rsaKeyParameters.Exponent; this.exponentAsString = rsaKeyParameters.Exponent.ToString(10); }
public RsaBlindingParameters( RsaKeyParameters publicKey, IBigInteger blindingFactor) { if (publicKey.IsPrivate) throw new ArgumentException("RSA parameters should be for a public key"); this.publicKey = publicKey; this.blindingFactor = blindingFactor; }
private void InitializeRSA() { string[] keyComponents = publicKey.Split('|'); var modulus = new Org.BouncyCastle.Math.BigInteger(keyComponents[1].ToLower(), 16); var exponent = new Org.BouncyCastle.Math.BigInteger(keyComponents[0].ToLower(), 16); RsaKeyParameters keyParams = new RsaKeyParameters(false, modulus, exponent); rsaCipher = CipherUtilities.GetCipher("RSA/None/PKCS1Padding"); rsaCipher.Init(true, keyParams); }
public Key(string pem) { var k = new CertificateLoader().LoadFirst<AsymmetricCipherKeyPair>("key", pem); _rsaKey = k.Private as RsaPrivateCrtKeyParameters; if (_rsaKey == null) throw new SecularException("Cannot find key in PEM string."); var rsaKeyParameters = new RsaKeyParameters(false, _rsaKey.Modulus, _rsaKey.PublicExponent); PublicKey = new PublicKey(rsaKeyParameters); }
private void doTestStrictPkcs1Length(RsaKeyParameters pubParameters, RsaKeyParameters privParameters) { IAsymmetricBlockCipher eng = new RsaBlindedEngine(); eng.Init(true, privParameters); byte[] data = null; try { data = eng.ProcessBlock(oversizedSig, 0, oversizedSig.Length); } catch (Exception e) { Fail("RSA: failed - exception " + e.ToString(), e); } eng = new Pkcs1Encoding(eng); eng.Init(false, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); Fail("oversized signature block not recognised"); } catch (InvalidCipherTextException e) { if (!e.Message.Equals("block incorrect size")) { Fail("RSA: failed - exception " + e.ToString(), e); } } // Create the encoding with StrictLengthEnabled=false (done thru environment in Java version) Pkcs1Encoding.StrictLengthEnabled = false; eng = new Pkcs1Encoding(new RsaBlindedEngine()); eng.Init(false, pubParameters); try { data = eng.ProcessBlock(data, 0, data.Length); } catch (InvalidCipherTextException e) { Fail("RSA: failed - exception " + e.ToString(), e); } Pkcs1Encoding.StrictLengthEnabled = true; }
/** * initialise the RSA engine. * * @param forEncryption true if we are encrypting, false otherwise. * @param param the necessary RSA key parameters. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { if (parameters is ParametersWithRandom) { parameters = ((ParametersWithRandom) parameters).Parameters; } if (!(parameters is RsaKeyParameters)) throw new InvalidKeyException("Not an RSA key"); this.key = (RsaKeyParameters) parameters; this.forEncryption = forEncryption; this.bitSize = key.Modulus.BitLength; }
static Rsa() { var openTibiaDecryptKey = new RsaPrivateCrtKeyParameters(new BigInteger(Constants.RSAKey.OpenTibiaM), new BigInteger(Constants.RSAKey.OpenTibiaE), new BigInteger(Constants.RSAKey.OpenTibiaE), new BigInteger(Constants.RSAKey.OpenTibiaP), new BigInteger(Constants.RSAKey.OpenTibiaQ), new BigInteger(Constants.RSAKey.OpenTibiaDP), new BigInteger(Constants.RSAKey.OpenTibiaDQ), new BigInteger(Constants.RSAKey.OpenTibiaInverseQ)); openTibiaDecryptEngine = new RsaEngine(); openTibiaDecryptEngine.Init(false, openTibiaDecryptKey); var realTibiaEncryptKey = new RsaKeyParameters(false, new BigInteger(Constants.RSAKey.RealTibiaM), new BigInteger(Constants.RSAKey.RealTibiaE)); realTibiaEncryptEngine = new RsaEngine(); realTibiaEncryptEngine.Init(true, realTibiaEncryptKey); var openTibiaEncryptKey = new RsaKeyParameters(false, new BigInteger(Constants.RSAKey.OpenTibiaM), new BigInteger(Constants.RSAKey.OpenTibiaE)); openTibiaEncryptEngine = new RsaEngine(); openTibiaEncryptEngine.Init(true, openTibiaEncryptKey); }
public static byte[] Init() { AsymmetricCipherKeyPair keyPair = null; string path = "proxy/session-key"; try { AsymmetricKeyParameter keyPub = PublicKeyFactory.CreateKey(File.ReadAllBytes(path + ".pub")); AsymmetricKeyParameter KeyPriv = PrivateKeyFactory.CreateKey(File.ReadAllBytes(path + ".priv")); keyPair = new AsymmetricCipherKeyPair(keyPub, KeyPriv); Debug.WriteLine("Loaded session.key"); } catch (Exception e) { Log.WriteServer(e); Debug.WriteLine("Generating session.key..."); var generator = new RsaKeyPairGenerator(); generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); keyPair = generator.GenerateKeyPair(); Debug.WriteLine("Generated, saving..."); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); byte[] bytePub = publicKeyInfo.ToAsn1Object().GetDerEncoded(); Directory.CreateDirectory(Path.GetDirectoryName(path)); File.WriteAllBytes(path + ".pub", bytePub); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); byte[] bytePriv = privateKeyInfo.ToAsn1Object().GetDerEncoded(); File.WriteAllBytes(path + ".priv", bytePriv); Debug.WriteLine("Saved session.key"); } //Old method /*var generator = new RsaKeyPairGenerator(); generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); var keyPair = generator.GenerateKeyPair(); */ keyParameters = (RsaKeyParameters)keyPair.Private; SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); return info.GetEncoded(); }
public static void DecodePublicKey(byte[] data) { /*TcpClient Client = new TcpClient(); Client.Connect(IPAddress.Parse("127.0.0.1"), 3128); BinaryWriter bwr = new BinaryWriter(Client.GetStream()); bwr.Write((byte)1); bwr.Write(data, 0, 162);*/ AsymmetricKeyParameter kp = PublicKeyFactory.CreateKey(data); Key = (RsaKeyParameters)kp; PublicKey = new byte[data.Length]; data.CopyTo(PublicKey,0); //Console.WriteLine("Exponent: " + Key.Exponent + "\nModulus: " + Key.Modulus); CipherKeyGenerator keygen = new CipherKeyGenerator(); keygen.Init(new KeyGenerationParameters(new SecureRandom(), 128)); SecretKey = keygen.GenerateKey(); }
/** * Initialise the factor generator * * @param param the necessary RSA key parameters. */ public void Init( ICipherParameters param) { if (param is ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)param; key = (RsaKeyParameters)rParam.Parameters; random = rParam.Random; } else { key = (RsaKeyParameters)param; random = new SecureRandom(); } if (key.IsPrivate) throw new ArgumentException("generator requires RSA public key"); }
/** * initialise the RSA engine. * * @param forEncryption true if we are encrypting, false otherwise. * @param param the necessary RSA key parameters. */ public virtual void Init( bool forEncryption, ICipherParameters param) { core.Init(forEncryption, param); if (param is ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)param; key = (RsaKeyParameters)rParam.Parameters; random = rParam.Random; } else { key = (RsaKeyParameters)param; random = new SecureRandom(); } }
private void ShouldPassSignatureTest2() { BigInteger n = new BigInteger("b746ba6c3c0be64bbe33aa55b2929b0af4e86d773d44bfe5914db9287788c4663984b61a418d2eecca30d752ff6b620a07ec72eeb2b422d2429da352407b99982800b9dd7697be6a7b1baa98ca5f4fc2fe33400f20b9dba337ac25c987804165d4a6e0ee4d18eabd6de5abdfe578cae6713ff91d16c80a5bb20217fe614d9509e75a43e1825327b9da8f0a9f6eeaa1c04b69fb4bacc073569fff4ab491becbe6d0441d437fc3fa823239c4a0f75321666b68dd3f66e2dd394089a15bcc288a68a4eb0a48e17d639743b9dea0a91cc35820544732aff253f8ca9967c609dc01c2f8cd0313a7a91cfa94ff74289a1d2b6f19d1811f4b9a65f4cce9e5759b4cc64f", 16); BigInteger e = new BigInteger("dcbbdb", 16); byte[] msg = Hex.Decode("a5d3c8a060f897bbbc20ae0955052f37fbc70986b6e11c65075c9f457142bfa93856897c69020aa81a91b5e4f39e05cdeecc63395ab849c8262ca8bc5c96870aecb8edb0aba0024a9bdb71e06de6100344e5c318bc979ef32b8a49a8278ba99d4861bce42ebbc5c8c666aaa6cac39aff8779f2cae367620f9edd4cb1d80b6c8c"); byte[] sig = Hex.Decode("39fbbd1804c689a533b0043f84da0f06081038c0fbf31e443e46a05e58f50de5198bbca40522afefaba3aed7082a6cb93b1da39f1f5a42246bf64930781948d300549bef0f8d554ecfca60a1b1ecba95a7014ee4545ad4f0c4e3a31942c6738b4ccd6244b6a21267dadf0826a5f713f13b1f5a9ab8501d957a26d4948278ac67851071a315674bdab173bfef2c2690c8373da6bf3d69f30c0e5da8883de872f59521b40793854085641adf98d13db991c5d0a8aaa0222934fa33332e90ef0b954e195cb267d6ffb36c96e14d1ec7b915a87598b4461a3146566354dc2ae748c84ee0cd46543b53ebff8cdf47725b280a1f799fb6ebb4a31ad2bdd5178250f83a"); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, n, e); X931Signer signer = new X931Signer(new RsaEngine(), new Sha224Digest()); signer.Init(false, rsaPublic); signer.BlockUpdate(msg, 0, msg.Length); if (!signer.VerifySignature(sig)) { Fail("RSA X931 verify test 2 failed."); } }
private void ShouldPassSignatureTest1() { BigInteger n = new BigInteger("c9be1b28f8caccca65d86cc3c9bbcc13eccc059df3b80bd2292b811eff3aa0dd75e1e85c333b8e3fa9bed53bb20f5359ff4e6900c5e9a388e3a4772a583a79e2299c76582c2b27694b65e9ba22e66bfb817f8b70b22206d7d8ae488c86dbb7137c26d5eff9b33c90e6cee640630313b7a715802e15142fef498c404a8de19674974785f0f852e2d470fe85a2e54ffca9f5851f672b71df691785a5cdabe8f14aa628942147de7593b2cf962414a5b59c632c4e14f1768c0ab2e9250824beea60a3529f11bf5e070ce90a47686eb0be1086fb21f0827f55295b4a48307db0b048c05a4aec3f488c576ca6f1879d354224c7e84cbcd8e76dd217a3de54dba73c35", 16); BigInteger e = new BigInteger("e75b1b", 16); byte[] msg = Hex.Decode("5bb0d1c0ef9b5c7af2477fe08d45523d3842a4b2db943f7033126c2a7829bacb3d2cfc6497ec91688189e81b7f8742488224ba320ce983ce9480722f2cc5bc42611f00bb6311884f660ccc244788378673532edb05284fd92e83f6f6dab406209032e6af9a33c998677933e32d6fb95fd27408940d7728f9c9c40267ca1d20ce"); byte[] sig = Hex.Decode("0fe8bb8e3109a1eb7489ef35bf4c1a0780071da789c8bd226a4170538eafefdd30b732d628f0e87a0b9450051feae9754d4fb61f57862d10f0bacc4f660d13281d0cd1141c006ade5186ff7d961a4c6cd0a4b352fc1295c5afd088f80ac1f8e192ef116a010a442655fe8ff5eeacea15807906fb0f0dfa86e680d4c005872357f7ece9aa4e20b15d5f709b30f08648ecaa34f2fbf54eb6b414fa2ff6f87561f70163235e69ccb4ac82a2e46d3be214cc2ef5263b569b2d8fd839b21a9e102665105ea762bda25bb446cfd831487a6b846100dee113ae95ae64f4af22c428c87bab809541c962bb3a56d4c86588e0af4ebc7fcc66dadced311051356d3ea745f7"); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, n, e); X931Signer signer = new X931Signer(new RsaEngine(), new Sha1Digest()); signer.Init(false, rsaPublic); signer.BlockUpdate(msg, 0, msg.Length); if (!signer.VerifySignature(sig)) { Fail("RSA X931 verify test 1 failed."); } }
/// <summary> /// Check an Active Authentication reply from the passport. /// </summary> /// <param name="publicKey">The AA public key read from the passport.</param> /// <param name="message">The original message.</param> /// <param name="signature">The response from the passport</param> /// <returns>True if the signature is correct for this message.</returns> public static bool CheckAA(RsaPublicKeyStructure publicKey, byte[] message, byte[] signature) { SHA1 sha1 = SHA1.Create(); RsaEngine rsa = new RsaEngine(); RsaKeyParameters p = new RsaKeyParameters(false, publicKey.Modulus, publicKey.PublicExponent); rsa.Init(false, p); byte[] digestedMessage = sha1.ComputeHash(message); // should always be 20 bytes byte[] m2 = new byte[8]; Array.Copy(digestedMessage, 0, m2, 0, m2.Length); byte[] plainText = rsa.ProcessBlock(signature, 0, signature.Length); byte[] m1 = recoverMessage(digestedMessage.Length, plainText); Sha1Digest digest = new Sha1Digest(); Iso9796d2Signer signer = new Iso9796d2Signer(rsa, digest); signer.Init(false, p); signer.BlockUpdate(m1, 0, m1.Length); signer.BlockUpdate(m2, 0, m2.Length); return signer.VerifySignature(signature); }
public string Encrypt(string text) { if (null == text) { return null; } var cipher = CipherUtilities.GetCipher("RSA/None/PKCS1Padding"); BigInteger modulus = this.BigIntegerForModulus(); BigInteger exponent = this.BigIntegerForExponent(); RsaKeyParameters publicKey = new RsaKeyParameters(false, modulus, exponent); ICipherParameters rsaOptions = publicKey; cipher.Init(true, rsaOptions); UTF8Encoding utf8 = new UTF8Encoding(); byte[] rawEncryptedData = cipher.DoFinal(utf8.GetBytes(text)); string encryptedData = Convert.ToBase64String(rawEncryptedData); return encryptedData; }
/** * Initialise the blinding engine. * * @param forEncryption true if we are encrypting (blinding), false otherwise. * @param param the necessary RSA key parameters. */ public void Init( bool forEncryption, ICipherParameters param) { RsaBlindingParameters p; if (param is ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)param; p = (RsaBlindingParameters)rParam.Parameters; } else { p = (RsaBlindingParameters)param; } core.Init(forEncryption, p.PublicKey); this.forEncryption = forEncryption; this.key = p.PublicKey; this.blindingFactor = p.BlindingFactor; }
/// <exception cref="IOException"></exception> public static byte[] GenerateEncryptedPreMasterSecret(TlsContext context, RsaKeyParameters rsaServerPublicKey, Stream output) { /* * Choose a PremasterSecret and send it encrypted to the server */ byte[] premasterSecret = new byte[48]; context.SecureRandom.NextBytes(premasterSecret); TlsUtilities.WriteVersion(context.ClientVersion, premasterSecret, 0); Pkcs1Encoding encoding = new Pkcs1Encoding(new RsaBlindedEngine()); encoding.Init(true, new ParametersWithRandom(rsaServerPublicKey, context.SecureRandom)); try { byte[] encryptedPreMasterSecret = encoding.ProcessBlock(premasterSecret, 0, premasterSecret.Length); if (TlsUtilities.IsSsl(context)) { // TODO Do any SSLv3 servers actually expect the length? output.Write(encryptedPreMasterSecret, 0, encryptedPreMasterSecret.Length); } else { TlsUtilities.WriteOpaque16(encryptedPreMasterSecret, output); } } catch (InvalidCipherTextException e) { /* * This should never happen, only during decryption. */ throw new TlsFatalAlert(AlertDescription.internal_error, e); } return premasterSecret; }
/// <summary> /// Parses the private key and public key from given file name. /// If the key file contains a key pair, it will be returned directly. /// If the key file only contains the RSA private key the public key will be created from the modulus and exponent. /// </summary> /// <param name="privateKeyFile">path to the private key file</param> /// <returns>the parsed key pair</returns> /// <exception cref="FormatException">Thrown if the key is not valid or can't be parsed</exception> public static AsymmetricCipherKeyPair ParseKeyPair(string privateKeyFile) { object obj = ReadPem(privateKeyFile); if (obj == null) throw new FormatException("The key file has an invalid PEM format. " + privateKeyFile); if (obj is AsymmetricCipherKeyPair) { return obj as AsymmetricCipherKeyPair; } if (obj is RsaPrivateCrtKeyParameters) { RsaPrivateCrtKeyParameters rsaPrivateKey = obj as RsaPrivateCrtKeyParameters; var publicParameters = new RsaKeyParameters(false, rsaPrivateKey.Modulus,rsaPrivateKey.PublicExponent); return new AsymmetricCipherKeyPair(publicParameters, rsaPrivateKey); } throw new FormatException("The given key does not have the correct type. The keyfile must include the private and public key in PEM format. It is of type: " + obj.GetType()); }
private static AsymmetricCipherKeyPair GenerateLongFixedKeys() { // RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( RsaKeyParameters pubKey = new RsaKeyParameters(false, new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16)); // RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16), new BigInteger("33a5042a90b27d4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b325",16), new BigInteger("e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e86296b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b3b6dcd3eda8e6443",16), new BigInteger("b69dca1cf7d4d7ec81e75b90fcca874abcde123fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc723e6963364a1f9425452b269a6799fd",16), new BigInteger("28fa13938655be1f8a159cbaca5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8dd3ede2448328f385d81b30e8e43b2fffa027861979",16), new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729",16), new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d",16)); // KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); // // PrivateKey privKey = fact.generatePrivate(privKeySpec); // PublicKey pubKey = fact.generatePublic(pubKeySpec); return new AsymmetricCipherKeyPair(pubKey, privKey); }
internal void checkCreation5() { // // a sample key pair. // RsaKeyParameters pubKey = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RsaPrivateCrtKeyParameters privKey = 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)); // // set up the keys // SecureRandom rand = new SecureRandom(); // AsymmetricKeyParameter privKey; // AsymmetricKeyParameter pubKey; // // KeyFactory fact = KeyFactory.GetInstance("RSA"); // // privKey = fact.generatePrivate(privKeySpec); // pubKey = fact.generatePublic(pubKeySpec); // // distinguished name table. // 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("*****@*****.**"); // // create base certificate - version 3 // X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, values)); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name(ord, values)); certGen.SetPublicKey(pubKey); certGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); certGen.AddExtension("2.5.29.15", true, new X509KeyUsage(X509KeyUsage.EncipherOnly)); certGen.AddExtension("2.5.29.37", true, new DerSequence(KeyPurposeID.AnyExtendedKeyUsage)); certGen.AddExtension("2.5.29.17", true, new GeneralNames(new GeneralName(GeneralName.Rfc822Name, "*****@*****.**"))); X509Certificate baseCert = certGen.Generate(privKey); // // copy certificate // certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, values)); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name(ord, values)); certGen.SetPublicKey(pubKey); certGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); certGen.CopyAndAddExtension(new DerObjectIdentifier("2.5.29.15"), true, baseCert); certGen.CopyAndAddExtension("2.5.29.37", false, baseCert); X509Certificate cert = certGen.Generate(privKey); cert.CheckValidity(DateTime.UtcNow); cert.Verify(pubKey); DerObjectIdentifier oid1 = new DerObjectIdentifier("2.5.29.15"); if (!baseCert.GetExtensionValue(oid1).Equals(cert.GetExtensionValue(oid1))) { Fail("2.5.29.15 differs"); } DerObjectIdentifier oid2 = new DerObjectIdentifier("2.5.29.37"); if (!baseCert.GetExtensionValue(oid2).Equals(cert.GetExtensionValue(oid2))) { Fail("2.5.29.37 differs"); } // // exception test // try { certGen.CopyAndAddExtension("2.5.99.99", true, baseCert); Fail("exception not thrown on dud extension copy"); } catch (CertificateParsingException) { // expected } try { certGen.SetPublicKey(dudPublicKey); certGen.Generate(privKey); Fail("key without encoding not detected in v3"); } catch (ArgumentException) { // expected } }
/** * we Generate a self signed certificate for the sake of testing - RSA */ internal void checkCreation1() { // // a sample key pair. // RsaKeyParameters pubKey = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RsaPrivateCrtKeyParameters privKey = 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)); // // set up the keys // // AsymmetricKeyParameter privKey; // AsymmetricKeyParameter pubKey; // KeyFactory fact = KeyFactory.GetInstance("RSA"); // // privKey = fact.generatePrivate(privKeySpec); // pubKey = fact.generatePublic(pubKeySpec); // // distinguished name table. // 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("*****@*****.**"); // // extensions // // // create the certificate - version 3 - without extensions // X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, values)); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name(ord, values)); certGen.SetPublicKey(pubKey); certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption"); X509Certificate cert = certGen.Generate(privKey); cert.CheckValidity(DateTime.UtcNow); cert.Verify(pubKey); ISet dummySet = cert.GetNonCriticalExtensionOids(); if (dummySet != null) { Fail("non-critical oid set should be null"); } dummySet = cert.GetCriticalExtensionOids(); if (dummySet != null) { Fail("critical oid set should be null"); } // // create the certificate - version 3 - with extensions // certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, values)); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name(ord, values)); certGen.SetPublicKey(pubKey); certGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); certGen.AddExtension("2.5.29.15", true, new X509KeyUsage(X509KeyUsage.EncipherOnly)); certGen.AddExtension("2.5.29.37", true, new DerSequence(KeyPurposeID.AnyExtendedKeyUsage)); certGen.AddExtension("2.5.29.17", true, new GeneralNames(new GeneralName(GeneralName.Rfc822Name, "*****@*****.**"))); cert = certGen.Generate(privKey); cert.CheckValidity(DateTime.UtcNow); cert.Verify(pubKey); cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded()); if (!cert.GetKeyUsage()[7]) { Fail("error generating cert - key usage wrong."); } IList l = cert.GetExtendedKeyUsage(); if (!l[0].Equals(KeyPurposeID.AnyExtendedKeyUsage.Id)) { Fail("failed extended key usage test"); } foreach (IList gn in cert.GetSubjectAlternativeNames()) { if (!gn[1].Equals("*****@*****.**")) { Fail("failed subject alternative names test"); } } // Console.WriteLine(cert); // // create the certificate - version 1 // X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator(); certGen1.SetSerialNumber(BigInteger.One); certGen1.SetIssuerDN(new X509Name(ord, values)); certGen1.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen1.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen1.SetSubjectDN(new X509Name(ord, values)); certGen1.SetPublicKey(pubKey); certGen1.SetSignatureAlgorithm("MD5WithRSAEncryption"); cert = certGen1.Generate(privKey); cert.CheckValidity(DateTime.UtcNow); cert.Verify(pubKey); cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded()); // Console.WriteLine(cert); if (!cert.IssuerDN.Equivalent(cert.SubjectDN)) { Fail("name comparison fails"); } }
// Would be needed to process RSA_EXPORT server key exchange // protected virtual void ProcessRsaServerKeyExchange(Stream input, ISigner signer) // { // Stream sigIn = input; // if (signer != null) // { // sigIn = new SignerStream(input, signer, null); // } // // byte[] modulusBytes = TlsUtilities.ReadOpaque16(sigIn); // byte[] exponentBytes = TlsUtilities.ReadOpaque16(sigIn); // // if (signer != null) // { // byte[] sigByte = TlsUtilities.ReadOpaque16(input); // // if (!signer.VerifySignature(sigByte)) // { // handler.FailWithError(AlertLevel.fatal, AlertDescription.bad_certificate); // } // } // // BigInteger modulus = new BigInteger(1, modulusBytes); // BigInteger exponent = new BigInteger(1, exponentBytes); // // this.rsaServerPublicKey = ValidateRSAPublicKey(new RsaKeyParameters(false, modulus, exponent)); // } protected virtual RsaKeyParameters ValidateRsaPublicKey(RsaKeyParameters key) { // TODO What is the minimum bit length required? // key.Modulus.BitLength; if (!key.Exponent.IsProbablePrime(2)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } return key; }
protected void Page_Load(object sender, EventArgs e) { //AuthCode(); //ModeWappay(); //return; _log.Info("测试"); //X509Certificate2 pc = new X509Certificate2(@"D:/182000899000001_01.pfx", "123456", X509KeyStorageFlags.MachineKeySet); ////return BigNum.ToDecimalStr(BigNum.ConvertFromHex(pc.SerialNumber)); 低于4.0版本的.NET请使用此方法 ////return BigInteger.Parse(pc.SerialNumber, System.Globalization.NumberStyles.HexNumber).ToString(); //Org.BouncyCastle.Math.BigInteger mod = new Org.BouncyCastle.Math.BigInteger(pc.GetSerialNumberString(), 16); //string m = "123333333333333333333333333333333333333333333333333333333333333333333333333333333333333333344444444444444444444444444FFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGG"; //string sign = Cmn.GetSign(m); //bool f = Cmn.ValitedSign(sign, m); //int a = 0; //Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)privateKey //RSA密钥对的构造器 RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator(); //RSA密钥构造器的参数 RsaKeyGenerationParameters param = new RsaKeyGenerationParameters( Org.BouncyCastle.Math.BigInteger.ValueOf(3), new Org.BouncyCastle.Security.SecureRandom(), 1024, //密钥长度 25); //用参数初始化密钥构造器 keyGenerator.Init(param); //产生密钥对 string input = "popozh RSA test"; AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair(); //获取公钥和密钥 AsymmetricKeyParameter publicKey = keyPair.Public; AsymmetricKeyParameter privateKey = keyPair.Private; if (((RsaKeyParameters)publicKey).Modulus.BitLength < 1024) { Console.WriteLine("failed key generation (1024) length test"); } Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters pu = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)publicKey; Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters pr = (Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)privateKey; //加密 string mSign = GetSign(input, pr); //解密 bool isPass = ValitedSign(mSign, input, pu); return; //一个测试…………………… //输入,十六进制的字符串,解码为byte[] //string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"; //byte[] testData = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(input); byte[] testData = Encoding.UTF8.GetBytes(input); Console.WriteLine("明文:" + input + Environment.NewLine); //非对称加密算法,加解密用 IAsymmetricBlockCipher engine = new RsaEngine(); //公钥加密 engine.Init(true, publicKey); try { testData = engine.ProcessBlock(testData, 0, testData.Length); Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine); } catch (Exception ex) { Console.WriteLine("failed - exception " + Environment.NewLine + ex.ToString()); } //string K = Convert.ToBase64String(testData);//System.Text.Encoding.Default.GetString(testData); //string sign = Cmn.GetSign(K); //int m = 1; //私钥解密 engine.Init(false, privateKey); try { testData = engine.ProcessBlock(testData, 0, testData.Length); } catch (Exception ef) { Console.WriteLine("failed - exception " + ef.ToString()); } if (input.Equals(Encoding.UTF8.GetString(testData))) { Console.WriteLine("解密成功"); } Console.Read(); }