RSA 登陸加密與解密

来源:https://www.cnblogs.com/w1-y2-q5/archive/2019/10/17/11695070.html
-Advertisement-
Play Games

最近公司項目驗收後,客戶請來的信息安全技術人員對我們的網站進行了各種安全測試與排查問題,其中就有一個登陸時的加密問題。本來如果只是單純的加密,可以直接在前臺用MD5加密,將加密的值添加到資料庫即可。但是現在的項目里有很多的用戶,密碼也是後臺MD5加密了的。這樣就不能單純在前臺用MD5加密,可能是本人 ...


  最近公司項目驗收後,客戶請來的信息安全技術人員對我們的網站進行了各種安全測試與排查問題,其中就有一個登陸時的加密問題。本來如果只是單純的加密,可以直接在前臺用MD5加密,將加密的值添加到資料庫即可。但是現在的項目里有很多的用戶,密碼也是後臺MD5加密了的。這樣就不能單純在前臺用MD5加密,可能是本人能力有限,使用的前臺MD5加密與後臺的MD5加密的值不一致,用戶登陸在密碼比對的時候就會失敗登陸不了。只能使用非對稱加密,前臺加密後臺解密後使用MD5加密再作對比,這種做法才能使用改動最少。網上查資料後就使用了RSA非對稱加密。

https://www.cnblogs.com/amylis_chen/p/6054414.html

前端代碼

 <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>

 <script src="http://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>

<script>

   var encrypt = new JSEncrypt();

    encrypt.setPublicKey("公鑰可以用工具生成");
    var userPwd = encrypt.encrypt(輸入的密碼);     //加密後的密碼

</script>

後端代碼

var publicKey = "公鑰可以用工具生成"

var privateKey = "私鑰可以用工具生成“

RSACrypto rsaCrypto = new RSACrypto(privateKey, publicKey);
userPwd = rsaCrypto.Decrypt(userPwd);    //解密後的密碼,就是輸入密碼的值

 

/// <summary>
/// RSA非對稱加密
/// </summary>
public class RSACrypto
{
private RSACryptoServiceProvider _privateKeyRsaProvider;
private RSACryptoServiceProvider _publicKeyRsaProvider;

public RSACrypto(string privateKey, string publicKey = null)
{
if (!string.IsNullOrEmpty(privateKey))
{
_privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
}

if (!string.IsNullOrEmpty(publicKey))
{
_publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
}
}

public string Decrypt(string cipherText)
{
if (_privateKeyRsaProvider == null)
{
throw new Exception("_privateKeyRsaProvider is null");
}
return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(System.Convert.FromBase64String(cipherText), false));
}

public string Encrypt(string text)
{
if (_publicKeyRsaProvider == null)
{
throw new Exception("_publicKeyRsaProvider is null");
}
return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), false));
}

private RSACryptoServiceProvider CreateRsaProviderFromPrivateKey(string privateKey)
{
var privateKeyBits = System.Convert.FromBase64String(privateKey);

var RSA = new RSACryptoServiceProvider();
var RSAparams = new RSAParameters();

using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits)))
{
byte bt = 0;
ushort twobytes = 0;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130)
binr.ReadByte();
else if (twobytes == 0x8230)
binr.ReadInt16();
else
throw new Exception("Unexpected value read binr.ReadUInt16()");

twobytes = binr.ReadUInt16();
if (twobytes != 0x0102)
throw new Exception("Unexpected version");

bt = binr.ReadByte();
if (bt != 0x00)
throw new Exception("Unexpected value read binr.ReadByte()");

RSAparams.Modulus = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.Exponent = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.D = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.P = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.Q = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.DP = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.DQ = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
}

RSA.ImportParameters(RSAparams);
return RSA;
}

private int GetIntegerSize(BinaryReader binr)
{
byte bt = 0;
byte lowbyte = 0x00;
byte highbyte = 0x00;
int count = 0;
bt = binr.ReadByte();
if (bt != 0x02)
return 0;
bt = binr.ReadByte();

if (bt == 0x81)
count = binr.ReadByte();
else
if (bt == 0x82)
{
highbyte = binr.ReadByte();
lowbyte = binr.ReadByte();
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
count = BitConverter.ToInt32(modint, 0);
}
else
{
count = bt;
}

while (binr.ReadByte() == 0x00)
{
count -= 1;
}
binr.BaseStream.Seek(-1, SeekOrigin.Current);
return count;
}

private RSACryptoServiceProvider CreateRsaProviderFromPublicKey(string publicKeyString)
{
// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
byte[] x509key;
byte[] seq = new byte[15];
int x509size;

x509key = Convert.FromBase64String(publicKeyString);
x509size = x509key.Length;

// --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------
using (MemoryStream mem = new MemoryStream(x509key))
{
using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading
{
byte bt = 0;
ushort twobytes = 0;

twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;

seq = binr.ReadBytes(15); //read the Sequence OID
if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct
return null;

twobytes = binr.ReadUInt16();
if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8203)
binr.ReadInt16(); //advance 2 bytes
else
return null;

bt = binr.ReadByte();
if (bt != 0x00) //expect null byte next
return null;

twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;

twobytes = binr.ReadUInt16();
byte lowbyte = 0x00;
byte highbyte = 0x00;

if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
else if (twobytes == 0x8202)
{
highbyte = binr.ReadByte(); //advance 2 bytes
lowbyte = binr.ReadByte();
}
else
return null;
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
int modsize = BitConverter.ToInt32(modint, 0);

int firstbyte = binr.PeekChar();
if (firstbyte == 0x00)
{ //if first byte (highest order) of modulus is zero, don't include it
binr.ReadByte(); //skip this null byte
modsize -= 1; //reduce modulus buffer size by 1
}

byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes

if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data
return null;
int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
byte[] exponent = binr.ReadBytes(expbytes);

// ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters();
RSAKeyInfo.Modulus = modulus;
RSAKeyInfo.Exponent = exponent;
RSA.ImportParameters(RSAKeyInfo);

return RSA;
}

}
}

private bool CompareBytearrays(byte[] a, byte[] b)
{
if (a.Length != b.Length)
return false;
int i = 0;
foreach (byte c in a)
{
if (c != b[i])
return false;
i++;
}
return true;
}
}

RSA密鑰對生成工具---------http://web.chacuo.net/netrsakeypair

請選用PKCS#1來生成公鑰與私鑰

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1. 安裝 輸入 pip install PIL報錯: ERROR: Could not find a version that satisfies the requirement PIL (from versions: none) ERROR: No matching distribution f ...
  • 1. JavaScript的概述 1.1 什麼是JavaScript JavaScript是web上一種功能強大的編程語言,用於開發互動式的web頁面。它不需要進行編譯,而是直接嵌入在HTML頁面中,由瀏覽器執行。 JavaScript被設計用來向HTML頁面添加交互行為。 JavaScript是一 ...
  • 用途 Clock函數可以有效地針對一些只能用隨機化做的題目 為了提高該類代碼的正確性,我們期望它運行的次數在要求時限內運行足夠多 因此將Clock函數充當計時器 調用 Clock函數所在頭文件ctime/time.h ClOCKS_PER_SEC為常量 時長的計算: 註:begin在程式開頭進行賦值 ...
  • 使用maven搭建Hibernate框架(web項目) 1 create table USERS 2 ( 3 ID NUMBER not null primary key, 4 NAME VARCHAR2(50), 5 PASSWORD VARCHAR2(50), 6 TELEPHONE VARCH ...
  • 公共依賴: 1、創建eureka-server註冊中心工程 a、eureka-server工程pom依賴: b、eureka-server啟動類: c、eureka-server工程配置文件:eureka-server\src\main\resources\bootstrap.yml d、啟動註冊中 ...
  • 2019-10-17-20:21:22 順序結構: 概述:順序執行,根據編寫的順序,從上到下執行語句 判斷語句1-if: if語句第一種格式: if(關係表達式){ 語句體; } 執行流程: 1.首先判斷關係表達式看其結果時true還是false 2.如果是true就執行語句體 3.如果是false ...
  • 如圖所示: C#代碼: lua代碼: ...
  • 昨天在比較完C++中std::vector的兩個方法的性能差異並留下記錄後—— "編程雜談——使用emplace_back取代push_back" ,今日嘗試在C 中測試對應功能的性能。 C 中對應std::vector的數據結構為List。更多的對應關係可以參照下麵: std::vector Li ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...