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

查看:33
本文介绍了如何解码 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天全站免登陆