搜索
首页后端开发Golang使用 AES-GSM 方法解密在 GO 中编码的 C# 字符串

使用 AES-GSM 方法解密在 GO 中编码的 C# 字符串

Feb 10, 2024 am 09:39 AM
go语言安全传输

使用 AES-GSM 方法解密在 GO 中编码的 C# 字符串

php小编西瓜为您介绍一种在GO语言中解密C#字符串的方法——AES-GSM。AES-GSM是一种高级加密标准,它结合了AES(高级加密标准)和GSM(全球系统移动通信)的优势。通过使用AES-GSM方法,我们可以有效地解密在GO中编码的C#字符串,从而实现数据的安全传输和保护。本文将详细介绍AES-GSM的原理和使用步骤,帮助读者轻松掌握这一加密解密技术。

问题内容

我有一个在 go 中经过 aes-gcm 加密的字符串及其密码短语,并尝试在 c# 中对其进行解密。但是,我无法找到正确的方法来在 c# 中对其进行解密。 我收到的错误提到 iv 的大小,块的长度不适合 c# 解密算法。以下是 go 中的值:

aes encr/decr passphrase:  this-is-a-test-passphrase
input string:  text to encrypt hello world 123
encrypted string:  94b681ef29d9a6d7-e6fa36c4c00977de1745fc63-a1ad0481bdbeeaa02c013a2dce82520ddd762355e18f1e2f20c0ea9d001ece24e9b8216ed4b9c6a06e1ef34c953f80

go代码:https://go.dev/play/p/jn8ie61ntzw

这是go中的解密代码

func appdecryptimpl(passphrase, ciphertext string) string {
arr := strings.split(ciphertext, "-")
salt, _ := hex.decodestring(arr[0])
iv, _ := hex.decodestring(arr[1])
data, _ := hex.decodestring(arr[2])
key, _ := appderivekey(passphrase, salt)
b, _ := aes.newcipher(key)
aesgcm, _ := cipher.newgcm(b)
data, _ = aesgcm.open(nil, iv, data, nil)
return string(data)
}

func appderivekey(passphrase string, salt []byte) ([]byte, []byte) {
if salt == nil {
    salt = make([]byte, 8)
    rand.read(salt)
}
return pbkdf2.key([]byte(passphrase), salt, 1000, 32, sha256.new), salt
}

这是go中的加密代码

func AppEncryptImpl(passphrase string, plaintext string) string {
key, salt := appDeriveKey(passphrase, nil)
iv := make([]byte, 12)
rand.Read(iv)
b, _ := aes.NewCipher(key)
aesgcm, _ := cipher.NewGCM(b)
data := aesgcm.Seal(nil, iv, []byte(plaintext), nil)
return hex.EncodeToString(salt) + "-" + hex.EncodeToString(iv) + "-" + hex.EncodeToString(data)
}

我正在尝试在 c# 中复制相同的解密登录,因此它将能够解密并生成最终的字符串。

我在 c# 中尝试了几种解密逻辑,它们可以在这里找到:

  • https://dotnetfiddle.net/32sb5m 此函数使用 system.security.cryptography 命名空间,但会导致 iv 大小错误。

  • https://dotnetfiddle.net/wxkuyr 上述针对 .net 5 的修改版本会产生相同的结果

  • https://dotnetfiddle.net/6iftps 使用充气城堡库会导致“gcm 中的 mac 检查失败”错误

  • https://dotnetfiddle.net/8mjs3g 使用 rfc2898derivebytes 方法的另一种方法会产生错误,提示“计算的身份验证标记与输入身份验证标记不匹配”

当前使用的方法是否正确,或者是否有其他方法可以在 c# 中解密 aes-gcm?当涉及到 c# 时,可以采取什么措施来绕过这些错误?

解决方法

您已经接近最后一个代码了。 go 将身份验证标签附加到生成的密文的末尾。您在这里正确提取它:

// extract the tag from the encrypted byte array
byte[] tag = new byte[16];
array.copy(encrypteddata, encrypteddata.length - 16, tag, 0, 16);

但是,您继续将具有实际加密文本+身份验证标记的数组视为仅包含加密文本。要修复,请将其也提取出来:

public static void Main() {
    // This is the encrypted string that you provided
    string encryptedString = "a6c0952b78967559-2953e738b9b005028bf4f6c0-7b8464d1ed75bc38b4503f6c8d25d6bfc22a19cc1a8a92bc6faa1ed6cd837b97072bc8e16fd95b6cfca67fccbad8fc";

    // This is the passphrase that you provided
    string passphrase = "this-is-a-test-passphrase";

    string[] splitStrs = encryptedString.Split('-');

    byte[] salt = Convert.FromHexString(splitStrs[0]);
    byte[] iv = Convert.FromHexString(splitStrs[1]);
    // this is encrypted data + tag
    byte[] encryptedDataWithTag = Convert.FromHexString(splitStrs[2]);
    // Extract the tag from the encrypted byte array
    byte[] tag = new byte[16];
    // But also extract actual encrypted data
    byte[] encryptedData = new byte[encryptedDataWithTag.Length - 16];
    Array.Copy(encryptedDataWithTag, 0, encryptedData, 0, encryptedData.Length);
    Array.Copy(encryptedDataWithTag, encryptedDataWithTag.Length - 16, tag, 0, 16);
    byte[] key = new Rfc2898DeriveBytes(passphrase, salt, 1000, HashAlgorithmName.SHA256).GetBytes(32);
    // Create an AesGcm object
    AesGcm aesGcm = new AesGcm(key);
    int textLength = encryptedData.Length;
    // Decrypt the ciphertext
    byte[] plaintext = new byte[textLength];
    aesGcm.Decrypt(iv, encryptedData, tag, plaintext);
    // Convert the plaintext to a string and print it
    string decryptedString = Encoding.UTF8.GetString(plaintext);
    Console.WriteLine(decryptedString);
}

以上是使用 AES-GSM 方法解密在 GO 中编码的 C# 字符串的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
去其他语言:比较分析去其他语言:比较分析Apr 28, 2025 am 12:17 AM

goisastrongchoiceforprojectsneedingsimplicity,绩效和引发性,butitmaylackinadvancedfeatures and ecosystemmaturity.1)

比较以其他语言的静态初始化器中的初始化功能比较以其他语言的静态初始化器中的初始化功能Apr 28, 2025 am 12:16 AM

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

GO中初始功能的常见用例GO中初始功能的常见用例Apr 28, 2025 am 12:13 AM

thecommonusecasesfortheinitfunctionoare:1)加载configurationfilesbeforeThemainProgramStarts,2)初始化的globalvariables和3)runningpre-checkSorvalidationsbeforEtheprofforeTheProgrecce.TheInitFunctionIsautefunctionIsautomentycalomationalmatomatimationalycalmatemationalcalledbebeforethemainfuniinfuninfuntuntion

GO中的频道:掌握际际交流GO中的频道:掌握际际交流Apr 28, 2025 am 12:04 AM

ChannelsarecrucialingoforenablingsafeandefficityCommunicationBetnewengoroutines.theyfacilitateSynChronizationAndManageGoroutIneLifeCycle,EssentialforConcurrentProgramming.ChannelSallSallSallSallSallowSallowsAllowsEnderDendingAndReceivingValues,ActassignalsignalsforsynChronization,and actassignalsynChronization and andsupppor

包装错误:将上下文添加到错误链中包装错误:将上下文添加到错误链中Apr 28, 2025 am 12:02 AM

在Go中,可以通过errors.Wrap和errors.Unwrap方法来包装错误并添加上下文。1)使用errors包的新功能,可以在错误传播过程中添加上下文信息。2)通过fmt.Errorf和%w包装错误,帮助定位问题。3)自定义错误类型可以创建更具语义化的错误,增强错误处理的表达能力。

使用GO开发时的安全考虑使用GO开发时的安全考虑Apr 27, 2025 am 12:18 AM

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

了解GO的错误接口了解GO的错误接口Apr 27, 2025 am 12:16 AM

Go的错误接口定义为typeerrorinterface{Error()string},允许任何实现Error()方法的类型被视为错误。使用步骤如下:1.基本检查和记录错误,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。2.创建自定义错误类型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。3.使用错误包装(自Go1.13起)来添加上下文而不丢失原始错误信息,

并发程序中的错误处理并发程序中的错误处理Apr 27, 2025 am 12:13 AM

对效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,EmparterRorwatchers,InsterTimeouts,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErstopassErrorsErtopassErrorsErrorsFromGoroutInestotheStothemainfunction.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器