RSA 加密
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | //通用RSA加密,可兼容.Net 6.0以下 string CommonRSAEncrypt( string publicKeyBase64, string plaintext) { try { byte [] publicKeyBytes = Convert.FromBase64String(publicKeyBase64); AsymmetricKeyParameter publicKeyParam = PublicKeyFactory.CreateKey(publicKeyBytes); IBufferedCipher rsa = CipherUtilities.GetCipher( "RSA" ); rsa.Init( true , publicKeyParam); byte [] plaintextBytes = Encoding.UTF8.GetBytes(plaintext); byte [] ciphertextBytes = rsa.DoFinal(plaintextBytes); string encryptedText = Convert.ToBase64String(ciphertextBytes); return encryptedText; } catch (Exception e) { Console.WriteLine(e); } return null ; } //RSA 加密,.Net6.0版本可用 string RSAEncrypt( string publicKey, string password) { try { byte [] decoded = Convert.FromBase64String(publicKey); RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); provider.ImportSubjectPublicKeyInfo(decoded, out int bytesRead); // RSA加密 byte [] bytesToEncrypt = Encoding.UTF8.GetBytes(password); byte [] ciphertext = provider.Encrypt(bytesToEncrypt, false ); //**此处Base64编码,开发者可以使用自己的库** string outStr = Convert.ToBase64String(ciphertext); //outStr 是加密密文 return outStr; } catch (Exception e) { Console.WriteLine(e); } return null ; } //通用RSA解密,可兼容.Net 6.0以下 string CommonRSADecrypt( string privateKeyBase64, string ciphertext) { try { byte [] privateKeyBytes = Convert.FromBase64String(privateKeyBase64); AsymmetricKeyParameter privateKeyParam = PrivateKeyFactory.CreateKey(privateKeyBytes); IBufferedCipher rsa = CipherUtilities.GetCipher( "RSA" ); rsa.Init( false , privateKeyParam); byte [] ciphertextBytes = Convert.FromBase64String(ciphertext); byte [] decryptedBytes = rsa.DoFinal(ciphertextBytes); string decryptedText = Encoding.UTF8.GetString(decryptedBytes); return decryptedText; } catch (Exception e) { Console.WriteLine(e); } return null ; } |
分类:
学习日记
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)