本文翻译自:How do I encode and decode a base64 string?

  1. How do I return a base64 encoded string given a string? 给定字符串,如何返回以base64编码的字符串?

  2. How do I decode a base64 encoded string into a string? 如何将base64编码的字符串解码为字符串?


#1楼

参考:https://stackoom.com/question/nGvo/如何编码和解码base-字符串


#2楼

Encode 编码

public static string Base64Encode(string plainText) {var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);return System.Convert.ToBase64String(plainTextBytes);
}

Decode 解码

public static string Base64Decode(string base64EncodedData) {var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

#3楼

I'm sharing my implementation with some neat features: 我将通过一些简洁的功能分享我的实现:

  • uses Extension Methods for Encoding class. 使用扩展方法编码类。 Rationale is that someone may need to support different types of encodings (not only UTF8). 理由是有人可能需要支持不同类型的编码(不仅限于UTF8)。
  • Another improvement is failing gracefully with null result for null entry - it's very useful in real life scenarios and supports equivalence for X=decode(encode(X)). 另一个改进是由于空输入而导致的空结果优雅地失败了-这在现实生活中非常有用,并且支持X = decode(encode(X))的等效项。

Remark: Remember that to use Extension Method you have to (!) import the namespace with using keyword (in this case using MyApplication.Helpers.Encoding ). 备注:请记住,要使用扩展方法,您必须 (!) using关键字(在这种情况下using MyApplication.Helpers.Encoding )导入名称空间。

Code: 码:

namespace MyApplication.Helpers.Encoding
{public static class EncodingForBase64{public static string EncodeBase64(this System.Text.Encoding encoding, string text){if (text == null){return null;}byte[] textAsBytes = encoding.GetBytes(text);return System.Convert.ToBase64String(textAsBytes);}public static string DecodeBase64(this System.Text.Encoding encoding, string encodedText){if (encodedText == null){return null;}byte[] textAsBytes = System.Convert.FromBase64String(encodedText);return encoding.GetString(textAsBytes);}}
}

Usage example: 用法示例:

using MyApplication.Helpers.Encoding; // !!!namespace ConsoleApplication1
{class Program{static void Main(string[] args){Test1();Test2();}static void Test1(){string textEncoded = System.Text.Encoding.UTF8.EncodeBase64("test1...");System.Diagnostics.Debug.Assert(textEncoded == "dGVzdDEuLi4=");string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);System.Diagnostics.Debug.Assert(textDecoded == "test1...");}static void Test2(){string textEncoded = System.Text.Encoding.UTF8.EncodeBase64(null);System.Diagnostics.Debug.Assert(textEncoded == null);string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);System.Diagnostics.Debug.Assert(textDecoded == null);}}
}

#4楼

A slight variation on andrew.fox answer, as the string to decode might not be a correct base64 encoded string: andrew.fox答案略有不同,因为要解码的字符串可能不是正确的base64编码的字符串:

using System;namespace Service.Support
{public static class Base64{public static string ToBase64(this System.Text.Encoding encoding, string text){if (text == null){return null;}byte[] textAsBytes = encoding.GetBytes(text);return Convert.ToBase64String(textAsBytes);}public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText){if (encodedText == null){decodedText = null;return false;}try{byte[] textAsBytes = Convert.FromBase64String(encodedText);decodedText = encoding.GetString(textAsBytes);return true;}catch (Exception){decodedText = null;return false;   }}}
}

#5楼

Based on the answers by Andrew Fox and Cebe, I turned it around and made them string extensions instead of Base64String extensions. 根据安德鲁·福克斯(Andrew Fox)和塞贝(Cebe)的回答,我把它改了一下,使它们成为字符串扩展而不是Base64String扩展。

public static class StringExtensions
{public static string ToBase64(this string text){return ToBase64(text, Encoding.UTF8);}public static string ToBase64(this string text, Encoding encoding){if (string.IsNullOrEmpty(text)){return text;}byte[] textAsBytes = encoding.GetBytes(text);return Convert.ToBase64String(textAsBytes);}public static bool TryParseBase64(this string text, out string decodedText){return TryParseBase64(text, Encoding.UTF8, out decodedText);}public static bool TryParseBase64(this string text, Encoding encoding, out string decodedText){if (string.IsNullOrEmpty(text)){decodedText = text;return false;}try{byte[] textAsBytes = Convert.FromBase64String(text);decodedText = encoding.GetString(textAsBytes);return true;}catch (Exception){decodedText = null;return false;}}
}

#6楼

    using System;using System.Text;public static class Base64Conversions{public static string EncodeBase64(this string text, Encoding encoding = null){ if (text == null) return null;encoding = encoding ?? Encoding.UTF8;var bytes = encoding.GetBytes(text);return Convert.ToBase64String(bytes);}public static string DecodeBase64(this string encodedText, Encoding encoding = null){if (encodedText == null) return null;encoding = encoding ?? Encoding.UTF8;var bytes = Convert.FromBase64String(encodedText);return encoding.GetString(bytes);}}

Usage 用法

    var text = "Sample Text";var base64 = text.EncodeBase64();base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding

如何编码和解码base64字符串?相关推荐

  1. JS CryptoJS 编码/解码 Base64 字符串

    用的JavaScript 的 CryptoJS库 https://github.com/brix/crypto-js 字符串 转 base64 要将文本字符串(UTF-8 编码) 转换为base-64 ...

  2. php指令字符编码,如何在命令行上编码和解码percent-encoded字符串?

    问题描述 如何在命令行上编码和解码percent-encoded(URL编码)字符串? 我正在寻找可以做到这一点的解决方案: $ percent-encode "ændrük" % ...

  3. [转载] python将图片进行base64编码, 解码

    参考链接: 在Python中编码和解码Base64字符串 一.将图片进行base64编码 import base64 img_path = 'D:xxx/file/img/juwan.jpg' wit ...

  4. Python 对图像进行base64编码及解码读取为numpy、opencv、matplot需要的格式

    Python 对图像进行base64编码及解码读取为numpy.opencv.matplot需要的格式 1. 效果图 2. 源码 参考 这篇博客将介绍Python如何对图像进行base64编解码及读取 ...

  5. linux解码base64工具,如何解码Linux中的base64编码行?(How do I decode base64 encoded lines in linux?)...

    如何解码Linux中的base64编码行?(How do I decode base64 encoded lines in linux?) 我正在尝试读取文件并仅提取base64编码部分. 我通过使用 ...

  6. 【后端过程记录】用flask搭建服务器作后端接收数据 将base64字符串码解码为可读取文件 载入训练好的模型进行预测

    因为项目的原因了解到有一个python的flask框架,查了一下: 关于前端图片上传的canvas: 如下元素 <canvas id="canvas" width=" ...

  7. android 图片转base64内存变大了_开发者最喜爱的图片编码格式:opencv编码,解码,显示base64图片...

    由于图片格式尺寸较大,在互联网上若想传递一张图片,往往会 把图片进行格式转换,然后进行数据传输,图片格式往往会转换为base64编码图片 base64编码图片 BASE64编码表 base64编码 是 ...

  8. Vue中base64编码和解码

    推荐一个不错的学习资料库 Vue中base64编码和解码 1.在项目更目录下执行命令,安装 npm install --save js-base64 2.在使用的项目引入 let Base64 = r ...

  9. Java 8中的Base64编码和解码

    转自:https://juejin.im/post/5c99b2976fb9a070e76376cc Java 8会因为将lambdas,流,新的日期/时间模型和Nashorn JavaScript引 ...

最新文章

  1. 数据库中数据类型和约束(整数类型、字符串、时间类型)
  2. ECShop 模板库项目功能详解
  3. 猜拳小程序c语言编程,无聊的时候写的猜拳小程序
  4. Windows Embedded Compact 2013升级:VS2013也能编译
  5. 操作选项_消防设施操作员关键技能之六:能切换集中火灾报警控制器、消防联动控制器工作状态...
  6. matplotlib-绘制精美的图表
  7. 《分布式操作系统》知识点(8~14)二
  8. java面试时候算法题多吗,Java面试必问算法题
  9. shell编程-分支语句
  10. 道指mt4代码_道恩转债上市首日遭大股东清仓式减持!
  11. 【Java】用for循环实现1+2+3......+100 =
  12. Python使用爬山算法寻找序列“最大值”
  13. el表达式 多条件判断
  14. 以一种标准的办法,获取工作目录
  15. qlearning算法_通过OpenAI Gym编写第一个强化学习算法
  16. android 单独编译contacts,Android编译全过程
  17. Julia: [1 +j] ==[1 + j] ?
  18. 5G mib和sib的意义
  19. pm2开机启动项目脚本
  20. Kindle:电子书资源

热门文章

  1. Android stadio
  2. 学习JNI一些基础知识
  3. python渐变颜色表_python – 具有固定颜色渐变的np.histogram2D
  4. python 如何封装dll_如何为DLL库创建Python包装器
  5. python面向对象设计模式_python面向对象之设计模式
  6. python支持中文吗_Python中使用中文
  7. python并发编程之多进程理论部分
  8. [HNOI 2014]画框
  9. django源码解析一(请求处理流程)
  10. 13.13通过代码创建数据库和表