本文实例讲述了C#实现Base64处理的加密解密,编码解码。分享给大家供大家参考,具体如下:
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
69
|
using System; using System.Text; namespace Common { /// <summary> /// 实现Base64加密解密 /// 作者:周公 /// </summary> public sealed class Base64 { /// <summary> /// Base64加密 /// </summary> /// <param name="codeName">加密采用的编码方式</param> /// <param name="source">待加密的明文</param> /// <returns></returns> public static string EncodeBase64(Encoding encode, string source) { byte [] bytes = encode.GetBytes(source); try { encode = Convert.ToBase64String(bytes); } catch { encode = source; } return encode; } /// <summary> /// Base64加密,采用utf8编码方式加密 /// </summary> /// <param name="source">待加密的明文</param> /// <returns>加密后的字符串</returns> public static string EncodeBase64( string source) { return EncodeBase64(Encoding.UTF8, source); } /// <summary> /// Base64解密 /// </summary> /// <param name="codeName">解密采用的编码方式,注意和加密时采用的方式一致</param> /// <param name="result">待解密的密文</param> /// <returns>解密后的字符串</returns> public static string DecodeBase64(Encoding encode, string result) { string decode = "" ; byte [] bytes = Convert.FromBase64String(result); try { decode = encode.GetString(bytes); } catch { decode = result; } return decode; } /// <summary> /// Base64解密,采用utf8编码方式解密 /// </summary> /// <param name="result">待解密的密文</param> /// <returns>解密后的字符串</returns> public static string DecodeBase64( string result) { return DecodeBase64(Encoding.UTF8, result); } } } |
希望本文所述对大家C#程序设计有所帮助。