Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RSA Implement

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest. →
Avatar for Chen-Lin Yu Chen-Lin Yu
April 24, 2013
80

RSA Implement

RSA Algorithm

Avatar for Chen-Lin Yu

Chen-Lin Yu

April 24, 2013

Transcript

  1. RSA Implement Department of Computer Science & Information Engineering National

    Kaohsiung University of Applied Sciences Chen-Lin Yu (1098108145) 2013.04.24
  2. Algorithm Three steps: key generation, encryption and decryption.  Key

    generation: 1. 隨意選擇兩個大的質數p和q,p不等於q,計算N=pq。 2. 根據歐拉函數,求得r=(p-1)(q-1) 3. 選擇一個小於r的整數e,求得e關於模r的MOD運算,命名為d。(模反元素存在, 若且唯若e與r互質) 4. 將p和q的記錄銷毀。 5. (N,e)是公鑰(Public key),(N,d)是私鑰(Private key)
  3. Flow Chart Alice Generate Asymmetric Key Provide Public Key Bob

    Get Public Key of Alice Encrypt Data Alice Private Key to Decrypt Data Data Data
  4. Code //CspParameters Class new keycontainer and store key public static

    void initialParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); }
  5. Code //CspParameters Class new keycontainer and store key public void

    GenerateKey() { initialParameter(); //provide public & private Key RSA 物件的金鑰 string Key = rsa.ToXmlString(true); this.textBox6.Text = Key; //provide public key string publicKey = rsa.ToXmlString(false); this.textBox7.Text = publicKey; }
  6. Code // EncryptData public string EncryptData (string data2Encrypt) { initialParameter();

    string publickey = this.textBox8.Text; rsa.FromXmlString(publickey); //加解密都是以byte[],要將資料轉成byte[] byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); //array 轉回字串base 64編碼->此即為秘文(ciphertext) }
  7. Code // DecryptData public string DecryptData (string data2Decrypt) { initialParameter();

    byte[] getciphertext = Convert.FromBase64String(data2Decrypt); string privatekey = this.textBox6.Text; //從 XML 字串的金鑰資訊初始化 RSA 物件。 rsa.FromXmlString(privatekey); // decrypt ciphertext byte[] plain = rsa.Decrypt(getciphertext, false); return System.Text.Encoding.UTF8.GetString(plain); }