如何解码Base64字符串? [英] How to decode a Base64 string?

查看:145
本文介绍了如何解码Base64字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Powershell中有一个普通字符串,该字符串来自包含Base64文本的文本文件;它存储在$x中.我正在尝试将其解码为这样:

I have a normal string in Powershell that is from a text file containing Base64 text; it is stored in $x. I am trying to decode it as such:

$z = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($x));

如果$x是在Powershell中创建的Base64字符串,则此方法有效(但不是).而且这不适用于来自文件的$x Base64字符串,$z最终会以类似于䐲券的形式结束.

This works if $x was a Base64 string created in Powershell (but it's not). And this does not work on the $x Base64 string that came from a file, $z simply ends up as something like 䐲券.

我想念什么?例如,$x可能是YmxhaGJsYWg=,对于blahblah,它是Base64.

What am I missing? For example, $x could be YmxhaGJsYWg= which is Base64 for blahblah.

简而言之,YmxhaGJsYWg=在文本文件中,然后在此Powershell代码中放入字符串,我尝试对其进行解码,但最终以䐲券等结束.

In a nutshell, YmxhaGJsYWg= is in a text file then put into a string in this Powershell code and I try to decode it but end up with 䐲券 etc.

推荐答案

不是将文本编码转换为base64,而是将base64编码解码为文本吗?您似乎在将它们混在一起.当我使用此在线解码器进行解码时,我得到:

Isn't encoding taking the text TO base64 and decoding taking base64 BACK to text? You seem be mixing them up here. When I decode using this online decoder I get:

BASE64: blahblah
UTF8: nVnV

反之亦然.我无法在PS中完全重现它.参见下面的示例:

not the other way around. I can't reproduce it completely in PS though. See sample below:

PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("blahblah"))
nV�nV�

PS > [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("nVnV"))
blZuVg==

编辑,我认为您为文本使用了错误的编码器.编码的base64字符串是使用UTF8(或ASCII)字符串编码的.

EDIT I believe you're using the wrong encoder for your text. The encoded base64 string is encoded from UTF8(or ASCII) string.

PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah

PS > [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
汢桡汢桡

PS > [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah

这篇关于如何解码Base64字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆