稳扎稳打Silverlight(22) - 2.0通信之调用WCF服务, 对传输信息做加密

简介:
[索引页]
[源码下载]


稳扎稳打Silverlight(22) - 2.0通信之调用WCF服务, 对传输信息做加密


作者: webabcd


介绍
Silverlight 2.0 调用 WCF 服务,对客户端与服务端传输的消息做加密    
    在 Visual Studio 2008 中使用"添加服务引用"会自动生成代理类。只支持BasicHttpBinding


在线DEMO
http://webabcd.blog.51cto.com/1787395/342779


示例
clientaccesspolicy.xml
<? xml  version ="1.0"  encoding ="utf-8"  ?> 
< access-policy > 
         < cross-domain-access > 
                 < policy > 
                         < allow-from  http-request-headers ="*" > 
                                 < domain  uri ="*"  /> 
                         </ allow-from > 
                         < grant-to > 
                                 < resource  path ="/"  include-subpaths ="true"  /> 
                         </ grant-to > 
                 </ policy > 
         </ cross-domain-access > 
</ access-policy > 
<!--  
System.Net 命名空间 和 System.Net.Sockets 命名空间的跨域调用,需要在目标域的根目录下配置策略文件 
Image 控件 和 MediaElement 控件所访问的跨域地址,不受策略文件的限制 
HTTP 调用 仅支持 GET 和 POST ,只有 200(确定) 和 404(未找到) 状态代码可用 
同域:同一子域、协议和端口。不符合以上任一条件则为跨域 
Silverlight 与 HTTP/HTTPS 的所有通信均为异步 

关于策略文件详见文档 
-->
 
 
1、调用 WCF 服务
WCFService.cs(WCF 服务)
using System; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Activation; 
using System.Collections.Generic; 
using System.Text; 
 
using System.Security.Cryptography; 
using System.IO; 
 
/// <summary> 
/// 提供 WCF 服务的类 
/// </summary> 
[ServiceContract] 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
public  class WCFService 

         /// <summary> 
         /// 返回指定的 User 对象(用于演示 Silverlight 调用 WCF 服务) 
         /// </summary> 
         /// <param name="name">名字</param> 
         /// <returns></returns> 
        [OperationContract] 
         public User GetUser( string name) 
        { 
                 return  new User { Name = name, DayOfBirth =  new DateTime(1980, 2, 14) }; 
        } 
}
 
WCF.xaml
<UserControl x:Class="Silverlight20.Communication.WCF" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
        <StackPanel HorizontalAlignment="Left" Margin="5"> 
         
                <TextBlock x:Name="lblMsg" /> 
         
        </StackPanel> 
</UserControl>
 
WCF.xaml.cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 
 
using Silverlight20.WCFServiceReference; 
using System.Threading; 
using System.ServiceModel; 
 
namespace Silverlight20.Communication 

         public partial  class WCF : UserControl 
        { 
                SynchronizationContext _syncContext; 
 
                 /// <summary> 
                 /// 演示 Silverlight 调用 WCF 服务 
                 /// </summary> 
                 public WCF() 
                { 
                        InitializeComponent(); 
 
                         // 代理的配置信息在配置文件中,UI线程上的异步调用 
                        Demo(); 
 
                         // 代理的配置信息在程序中指定,UI线程上的异步调用 
                        Demo2(); 
 
                         // 后台线程(非UI线程)上的异步调用) 
                        Demo3(); 
                } 
 
                 void Demo() 
                { 
                         /*                            
                         * 服务名Client - 系统自动生成的代理类 
                         *         方法名Completed - 调用指定的方法完成后所触发的事件 
                         *         方法名Async(参数1, 参数2 , object 用户标识) - 异步调用指定的方法 
                         *         Abort() - 取消调用 
                         */
 
 
                        WCFServiceClient client =  new WCFServiceClient(); 
                        client.GetUserCompleted +=  new EventHandler<GetUserCompletedEventArgs>(client_GetUserCompleted); 
                        client.GetUserAsync( "webabcd"); 
                } 
 
                 void Demo2() 
                { 
                         /* 
                         * 服务名Client - 其构造函数可以动态地指定代理的配置信息(Silverlight 2.0 调用 WCF 只支持 BasicHttpBinding) 
                         */
 
 
                        WCFServiceClient client =  new WCFServiceClient( new BasicHttpBinding(),  new EndpointAddress( "http://localhost:3036/WCFService.svc")); 
                        client.GetUserCompleted += new EventHandler<GetUserCompletedEventArgs>(client_GetUserCompleted); 
                        client.GetUserAsync("webabcd2"); 
                } 
 
                void client_GetUserCompleted(object sender, GetUserCompletedEventArgs e) 
                { 
                        /* 
                         * 方法名CompletedEventArgs.Error - 该异步操作期间是否发生了错误 
                         * 方法名CompletedEventArgs.Result - 异步操作返回的结果。本例为 User 类型 
                         * 方法名CompletedEventArgs.UserState - 用户标识 
                         */
 
 
                        if (e.Error != null
                        { 
                                lblMsg.Text += e.Error.ToString() + "\r\n"
                                return
                        } 
 
                        if (e.Cancelled != true
                        { 
                                OutputResult(e.Result); 
                        } 
                } 
 
                void Demo3() 
                { 
                        // UI 线程 
                        _syncContext = SynchronizationContext.Current; 
 
                        /* 
                         * ChannelFactory<T>.CreateChannel() - 创建 T 类型的信道 
                         * 服务名.Begin方法名() - 后台线程上异步调用指定方法(最后一个参数为 代理对象) 
                         */
 
 
                        WCFService client = new ChannelFactory<WCFService>(new BasicHttpBinding(), new EndpointAddress("http://localhost:3036/WCFService.svc")).CreateChannel(); 
                        client.BeginGetUser("webabcd3"new AsyncCallback(ResponseCallback), client); 
                } 
 
                private void ResponseCallback(IAsyncResult result) 
                { 
                        WCFService client = result.AsyncState as WCFService; 
 
                        // 服务名.End方法名() - 获取在后台线程(非UI线程)上异步调用的结果 
                        User user = client.EndGetUser(result); 
 
                        // 调用 UI 线程 
                        _syncContext.Post(GetResponse, user); 
                } 
 
                private void GetResponse(object state) 
                { 
                        OutputResult(state as User); 
                } 
 
 
                /// <summary> 
                /// 输出异步调用 WCF 服务的方法后返回的结果 
                /// </summary> 
                /// <param name="user"></param> 
                void OutputResult(User user) 
                { 
                        lblMsg.Text += string.Format("姓名:{0};生日:{1}\r\n"
                                user.Name, 
                                user.DayOfBirth.ToString("yyyy-MM-dd")); 
                } 
        } 
}
 
 
2、对客户端与服务端传输的消息做加密
WCFService.cs(WCF 服务)
using System; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Activation; 
using System.Collections.Generic; 
using System.Text; 
 
using System.Security.Cryptography; 
using System.IO; 
 
/// <summary> 
/// 提供 WCF 服务的类 
/// </summary> 
[ServiceContract] 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
public  class WCFService 

         /// <summary> 
         /// 返回指定的 User 对象(用于演示传输信息的加密/解密) 
         /// </summary> 
         /// <param name="name"></param> 
         /// <returns></returns> 
        [OperationContract] 
         public User GetUserByCryptography( string name) 
        { 
                 return  new User { Name = Decrypt(name), DayOfBirth =  new DateTime(1980, 2, 14) }; 
        } 
 
         /// <summary> 
         /// 解密数据 
         /// </summary> 
         /// <param name="input">加密后的字符串</param> 
         /// <returns>加密前的字符串</returns> 
         public  string Decrypt( string input) 
        { 
                 // 盐值(与加密时设置的值一致) 
                 string saltValue =  "saltValue"
                 // 密码值(与加密时设置的值一致) 
                 string pwdValue =  "pwdValue"
 
                 byte[] encryptBytes = Convert.FromBase64String(input); 
                 byte[] salt = Encoding.UTF8.GetBytes(saltValue); 
 
                AesManaged aes =  new AesManaged(); 
 
                Rfc2898DeriveBytes rfc =  new Rfc2898DeriveBytes(pwdValue, salt); 
 
                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; 
                aes.KeySize = aes.LegalKeySizes[0].MaxSize; 
                aes.Key = rfc.GetBytes(aes.KeySize / 8); 
                aes.IV = rfc.GetBytes(aes.BlockSize / 8); 
 
                 // 用当前的 Key 属性和初始化向量 IV 创建对称解密器对象 
                ICryptoTransform decryptTransform = aes.CreateDecryptor(); 
 
                 // 解密后的输出流 
                MemoryStream decryptStream =  new MemoryStream(); 
 
                 // 将解密后的目标流(decryptStream)与解密转换(decryptTransform)相连接 
                CryptoStream decryptor =  new CryptoStream(decryptStream, decryptTransform, CryptoStreamMode.Write); 
 
                 // 将一个字节序列写入当前 CryptoStream (完成解密的过程) 
                decryptor.Write(encryptBytes, 0, encryptBytes.Length); 
                decryptor.Close(); 
 
                 // 将解密后所得到的流转换为字符串 
                 byte[] decryptBytes = decryptStream.ToArray(); 
                 string decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); 
 
                 return decryptedString; 
        } 

 
Cryptography.xaml
<UserControl x:Class="Silverlight20.Communication.Cryptography" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
        <StackPanel HorizontalAlignment="Left" Margin="5"> 
         
                <TextBlock x:Name="lblMsg" /> 
         
        </StackPanel> 
</UserControl>
 
Cryptography.xaml.cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 
 
using Silverlight20.WCFServiceReference; 
using System.Text; 
using System.Security.Cryptography; 
using System.IO; 
 
namespace Silverlight20.Communication 

         public partial  class Cryptography : UserControl 
        { 
                 public Cryptography() 
                { 
                        InitializeComponent(); 
 
                        Demo(); 
                } 
 
                 void Demo() 
                { 
                        WCFServiceClient client =  new WCFServiceClient(); 
 
                        client.GetUserByCryptographyCompleted+= new EventHandler<GetUserByCryptographyCompletedEventArgs>(client_GetUserByCryptographyCompleted); 
                        client.GetUserByCryptographyAsync(Encrypt( "webabcd")); 
                } 
 
                 void client_GetUserByCryptographyCompleted( object sender, GetUserByCryptographyCompletedEventArgs e) 
                { 
                         if (e.Error !=  null
                        { 
                                lblMsg.Text += e.Error.ToString() +  "\r\n"
                                 return
                        } 
 
                         if (e.Cancelled !=  true
                        { 
                                lblMsg.Text +=  string.Format( "姓名:{0};生日:{1}\r\n"
                                        e.Result.Name, 
                                        e.Result.DayOfBirth.ToString( "yyyy-MM-dd")); 
                        } 
                } 
 
                 /// <summary> 
                 /// 加密数据 
                 /// </summary> 
                 /// <param name="input">加密前的字符串</param> 
                 /// <returns>加密后的字符串</returns> 
                 private  string Encrypt( string input) 
                { 
                         // 盐值 
                         string saltValue =  "saltValue"
                         // 密码值 
                         string pwdValue =  "pwdValue"
 
                         byte[] data = UTF8Encoding.UTF8.GetBytes(input); 
                         byte[] salt = UTF8Encoding.UTF8.GetBytes(saltValue); 
 
                         // AesManaged - 高级加密标准(AES) 对称算法的管理类 
                        AesManaged aes =  new AesManaged(); 
 
                         // Rfc2898DeriveBytes - 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2 - 一种基于密码的密钥派生函数) 
                         // 通过 密码 和 salt 派生密钥 
                        Rfc2898DeriveBytes rfc =  new Rfc2898DeriveBytes(pwdValue, salt); 
 
                         /* 
                         * AesManaged.BlockSize - 加密操作的块大小(单位:bit) 
                         * AesManaged.LegalBlockSizes - 对称算法支持的块大小(单位:bit) 
                         * AesManaged.KeySize - 对称算法的密钥大小(单位:bit) 
                         * AesManaged.LegalKeySizes - 对称算法支持的密钥大小(单位:bit) 
                         * AesManaged.Key - 对称算法的密钥 
                         * AesManaged.IV - 对称算法的密钥大小 
                         * Rfc2898DeriveBytes.GetBytes(int 需要生成的伪随机密钥字节数) - 生成密钥 
                         */
 
 
                        aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; 
                        aes.KeySize = aes.LegalKeySizes[0].MaxSize; 
                        aes.Key = rfc.GetBytes(aes.KeySize / 8); 
                        aes.IV = rfc.GetBytes(aes.BlockSize / 8); 
 
                         // 用当前的 Key 属性和初始化向量 IV 创建对称加密器对象 
                        ICryptoTransform encryptTransform = aes.CreateEncryptor(); 
 
                         // 加密后的输出流 
                        MemoryStream encryptStream =  new MemoryStream(); 
 
                         // 将加密后的目标流(encryptStream)与加密转换(encryptTransform)相连接 
                        CryptoStream encryptor =  new CryptoStream(encryptStream, encryptTransform, CryptoStreamMode.Write); 
 
                         // 将一个字节序列写入当前 CryptoStream (完成加密的过程) 
                        encryptor.Write(data, 0, data.Length); 
                        encryptor.Close(); 
 
                         // 将加密后所得到的流转换成字节数组,再用Base64编码将其转换为字符串 
                         string encryptedString = Convert.ToBase64String(encryptStream.ToArray()); 
 
                         return encryptedString; 
                }                 
        } 
}
 
 
      本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/343130,如需转载请自行联系原作者
相关文章
|
安全 算法 Java
在Spring Boot中应用Jasypt以加密配置信息。
通过以上步骤,可以在Spring Boot应用中有效地利用Jasypt对配置信息进行加密,这样即使配置文件被泄露,其中的敏感信息也不会直接暴露给攻击者。这是一种在不牺牲操作复杂度的情况下提升应用安全性的简便方法。
1611 10
|
安全 Java 数据库
Jasypt加密数据库配置信息
本文介绍了使用 Jasypt 对配置文件中的公网数据库认证信息进行加密的方法,以提升系统安全性。主要内容包括:1. 背景介绍;2. 前期准备,如依赖导入及版本选择;3. 生成密钥并实现加解密测试;4. 在配置文件中应用加密后的密码,并通过测试接口验证解密结果。确保密码安全的同时,保障系统的正常运行。
904 3
Jasypt加密数据库配置信息
|
人工智能 安全 Java
Spring Boot yml 配置敏感信息加密
本文介绍了如何在 Spring Boot 项目中使用 Jasypt 实现配置文件加密,包含添加依赖、配置密钥、生成加密值、在配置中使用加密值及验证步骤,并提供了注意事项,确保敏感信息的安全管理。
1697 1
|
安全 算法 物联网
SSL/TLS:互联网通信的加密基石与安全实践
**简介:** 在数字化时代,互联网每天传输海量敏感数据,网络攻击频发。SSL/TLS协议作为网络安全的基石,通过加密技术确保数据安全传输。本文解析SSL/TLS的技术架构、密码学原理、应用场景及常见误区,探讨其在未来的发展趋势,强调持续演进以应对新型威胁的重要性。 SSL/TLS不仅保障Web安全,还广泛应用于API、邮件、物联网等领域,并遵循合规标准如PCI DSS和GDPR。
|
安全 网络协议 网络安全
【Azure 环境】从网络包中分析出TLS加密套件信息
An TLS 1.2 connection request was received from a remote client application, but non of the cipher suites supported by the client application are supported by the server. The connection request has failed. 从远程客户端应用程序收到 TLS 1.2 连接请求,但服务器不支持客户端应用程序支持的任何密码套件。连接请求失败。
657 2
|
SQL 安全 算法
网络安全的隐形盾牌:漏洞防御与信息加密的艺术
【10月更文挑战第36天】在数字世界的海洋中,网络安全犹如一艘船的保护罩,守护着我们的隐私和数据安全。本文将揭开网络安全的神秘面纱,从常见的网络漏洞到先进的加密技术,再到培养必要的安全意识,我们将一步步构建起防御的堡垒。文章不仅分享技术细节,还强调了在个人和组织层面采取积极措施的重要性。
|
SQL 安全 算法
网络安全与信息安全:构建数字世界的防线在数字化浪潮席卷全球的今天,网络安全与信息安全已成为维系社会秩序、保障个人隐私与企业机密的重要基石。本文旨在深入探讨网络安全漏洞的本质、加密技术的前沿进展以及提升安全意识的有效策略,为读者揭示数字时代下信息保护的核心要义。
本文聚焦网络安全与信息安全领域,详细剖析了网络安全漏洞的形成机理、常见类型及其潜在危害,强调了及时检测与修复的重要性。同时,文章系统介绍了对称加密、非对称加密及哈希算法等主流加密技术的原理、应用场景及优缺点,展现了加密技术在保障数据安全中的核心地位。此外,针对社会普遍存在的安全意识薄弱问题,提出了一系列切实可行的提升措施,如定期安全培训、强化密码管理、警惕钓鱼攻击等,旨在引导公众树立全面的网络安全观,共同构筑数字世界的安全防线。
|
SQL 安全 网络安全
网络安全的盾牌:漏洞防御与信息加密技术
【9月更文挑战第27天】在数字时代,网络安全和信息安全成为维护数据完整性、保密性和可用性的关键因素。本文将探讨网络安全漏洞的概念、成因及预防措施,同时深入讨论加密技术在保护信息安全中的作用。通过分析安全意识的重要性和提升方法,旨在为读者提供一套全面的网络安全知识框架,以增强个人和组织对抗网络威胁的能力。
210 5
|
安全 算法 Java
数据库信息/密码加盐加密 —— Java代码手写+集成两种方式,手把手教学!保证能用!
本文提供了在数据库中对密码等敏感信息进行加盐加密的详细教程,包括手写MD5加密算法和使用Spring Security的BCryptPasswordEncoder进行加密,并强调了使用BCryptPasswordEncoder时需要注意的Spring Security配置问题。
1607 0
数据库信息/密码加盐加密 —— Java代码手写+集成两种方式,手把手教学!保证能用!
|
安全 网络安全 数据安全/隐私保护
网络安全漏洞与加密技术:保护信息的艺术
【8月更文挑战第31天】在数字时代,网络安全和信息安全的重要性日益凸显。本文将探讨网络安全漏洞、加密技术以及提升安全意识等方面的内容。我们将通过实际代码示例和案例分析,深入了解网络攻击者如何利用安全漏洞进行攻击,以及如何运用加密技术来保护数据安全。同时,我们还将讨论如何提高个人和组织的安全意识,以应对不断变化的网络安全威胁。让我们一起探索这个充满挑战和机遇的领域吧!