移动端越来越火了,我们在开发过程中,总会碰到要和移动端打交道的场景,比如.NET和android或者iOS的打交道。为了让数据交互更安全,我们需要对数据进行加密传输。今天研究了一下,把几种语言的加密都实践了一遍,实现了.NET,java(android),iOS都同一套的加密算法,下面就分享给大家。 AES加密有多种算法模式,下面提供两套模式的可用源码。 加密方式: 先将文本AES加密 返回Base64转码 解密方式: 将数据进行Base64解码 进行AES解密 一、CBC(Cipher Block Chaining,加密块链)模式 是一种循环模式,前一个分组的密文和当前分组的明文异或操作后再加密,这样做的目的是增强破解难度. 密钥 密钥偏移量 java/adroid加密AESOperator类:
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
package com.bci.wx.base.util; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * AES 是一种可逆加密算法,对用户的敏感信息加密处理 对原始数据进行AES加密后,在进行Base64编码转化; */ public class AESOperator { /* * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式,key需要为16位。 */ private String sKey = "smkldospdosldaaa";//key,可自行修改 private String ivParameter = "0392039203920300";//偏移量,可自行修改 private static AESOperator instance = null; private AESOperator() { } public static AESOperator getInstance() { if (instance == null) instance = new AESOperator(); return instance; } public static String Encrypt(String encData ,String secretKey,String vector) throws Exception { if(secretKey == null) { return null; } if(secretKey.length() != 16) { return null; } Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] raw = secretKey.getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(vector.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度 cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8")); return new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码。 } // 加密 public String encrypt(String sSrc) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] raw = sKey.getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度 cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8")); return new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码。 } // 解密 public String decrypt(String sSrc) throws Exception { try { byte[] raw = sKey.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密 byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original, "utf-8"); return originalString; } catch (Exception ex) { return null; } } public String decrypt(String sSrc,String key,String ivs) throws Exception { try { byte[] raw = key.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(ivs.getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密 byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original, "utf-8"); return originalString; } catch (Exception ex) { return null; } } public static String encodeBytes(byte[] bytes) { StringBuffer strBuf = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a'))); strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a'))); } return strBuf.toString(); } public static void main(String[] args) throws Exception { // 需要加密的字串 String cSrc = "[{\"request_no\":\"1001\",\"service_code\":\"FS0001\",\"contract_id\":\"100002\",\"order_id\":\"0\",\"phone_id\":\"13913996922\",\"plat_offer_id\":\"100094\",\"channel_id\":\"1\",\"activity_id\":\"100045\"}]"; // 加密 long lStart = System.currentTimeMillis(); String enString = AESOperator.getInstance().encrypt(cSrc); System.out.println("加密后的字串是:" + enString); long lUseTime = System.currentTimeMillis() - lStart; System.out.println("加密耗时:" + lUseTime + "毫秒"); // 解密 lStart = System.currentTimeMillis(); String DeString = AESOperator.getInstance().decrypt(enString); System.out.println("解密后的字串是:" + DeString); lUseTime = System.currentTimeMillis() - lStart; System.out.println("解密耗时:" + lUseTime + "毫秒"); } } |
.NET AES加密解密:
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 |
using System; using System.Security.Cryptography; using System.Text; namespace AESDome { class Program { private static string key = "smkldospdosldaaa"; //key,可自行修改 private static string iv = "0392039203920300"; //偏移量,可自行修改 static void Main(string[] args) { string encrytpData = Encrypt("abc", key, iv); Console.WriteLine(encrytpData); string decryptData = Decrypt("5z9WEequVr7qtd+WoxV+Kw==", key, iv); Console.WriteLine(decryptData); Console.ReadLine(); } public static string Encrypt(string toEncrypt, string key, string iv) { byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv); byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); RijndaelManaged rDel = new RijndaelManaged(); rDel.BlockSize = 128; rDel.KeySize = 256; rDel.FeedbackSize = 128; rDel.Padding = PaddingMode.PKCS7; rDel.Key = keyArray; rDel.IV = ivArray; rDel.Mode = CipherMode.CBC; ICryptoTransform cTransform = rDel.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } public static string Decrypt(string toDecrypt, string key, string iv) { byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv); byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); // 这里的模式,请保持和上面加密的一样。但源代码里,这个地方并没有修正,虽然也能正确解密。看到博客的朋友,请自行修改。 // 这是个人疏忽的地址,感谢@jojoka 的提醒。 RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; rDel.IV = ivArray; rDel.Mode = CipherMode.CBC; rDel.Padding = PaddingMode.Zeros; rDel.BlockSize = 128; rDel.KeySize = 256; rDel.FeedbackSize = 128; rDel.Padding = PaddingMode.PKCS7; rDel.Key = keyArray; rDel.IV = ivArray; rDel.Mode = CipherMode.CBC; ICryptoTransform cTransform = rDel.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return UTF8Encoding.UTF8.GetString(resultArray); } } } |
iOS源码,请下载源码,源码里有包含。 java,.net,iOS,android通用AES加密解密源码:AES_CBC_ECB_android_java_ios_net通用模式 二、ECB(Electronic Code Book,电子密码本)模式 是一种基础的加密方式,密文被分割成分组长度相等的块(不足补齐),然后单独一个个加密,一个个输出组成密文。 只需要提供密码即可。 iOS,android,java已调通源码:AES_CBC_ECB_android_java_ios_net通用模式 AES在线加解密验证工具: http://www.seacha.com/tools/aes.html from:http://www.cnblogs.com/jys509/p/4768120.html
View Details本文目录 1.窗口的外观 2.窗口的位置 3.窗口的大小 4.窗口的可见性和状态 5.窗口的生命周期 1.窗口的外观 WPF中默认窗口框架的外观,主要取决于Icon、Title、WindowsStyle、ResizeMode等属性。 Icon 指定窗口的图标; Title 指定窗口的标题; WindowStyle 指定窗口样式,有4个取值: None,无边框;(当ResizeMode属性为NoResize时,仅剩下窗口核心。) SingleBorderWindow,单边框【默认】; ThreeDBorderWindow,3D边框; ToolBorderWindow,工具箱窗口; ResizeMode 是指定大小调节样式,有4个取值: NoResize,不可调节,同时没有最大最小按钮; CanMinimize,不可调节。但可以最小化;(此时最大化按钮不可用) CanResize,可调节【默认】; CanResizeWithGrid,可根据网格调节;(窗口右下脚显示可调节网格) 2.窗口的位置 WindowStartLocation 指定窗口初始位置,有3个取值: Manual,手工指定位置,表示可以通过设置其Top、Left属性值来决定窗口的初始位置; CenterScreen,屏幕中央; CenterOwner,父窗体中央; TopMost 调节窗口的前后顺序,属性值为true时,窗口位于最前。 TopMost值为true的窗口,位于TopMost值为false的窗口之前(如下图记事本与示例窗口); TopMost值都为true的窗口,获得焦点的窗口位于前(如下图QQ与示例窗口)。 3.窗口的大小 Width、Height,分别表示窗口的宽度和高度,称为“尺寸属性”。 MaxWidth、MinWidth、MaxHeight、MinHeight,分别表示窗口最大宽度、最小宽度、最大高度、最小高度。可以通过得到和更改这些属性值,来获取和改变窗口的大小和长宽范围。 ActualWidth、ActualHeight,分别表示窗口的实际宽度和实际高度,称为“实际尺寸属性”。 实际尺寸属性是根据当前窗口大小、最小化时窗口大小和最大化时窗口大小来计算得到的,其值是只读的,也就是说,不能通过改变ActualWidth、ActualHeight的值来更改窗口大小。 SizeToContent,表示窗口大小由内容决定,有4个取值: Manual,手工【默认】; Width,窗体宽度由内容决定; Height,窗体高度由内容决定; WidthAndHeight,窗体大小由内容决定; 如果内容尺寸超过了窗口的最大或最小范围,还是以最大/最小范围为主。如果手工指定了窗口的Width、Height 属性,那么SizeToContent将被忽略。 ReSize,窗口大小的可调整性(第1部分已提到)。 4.窗口的可见性和状态 Visibility,窗口可见性,有4个枚举值: Visiable,可见; Hidden,隐藏; Collapsed,折叠。 虽然窗口类认为Collapsed与Hidden一样,但二者区别在于,Hidden仅仅将元素设为不可见,但是元素在画面上依然占有空间;而Collapsed,在不可视的基础上,能将元素在画面上的占位符清除,元素彻底不影响画面。 Show、Hide,显示窗口和隐藏窗口的两个方法。如果窗口的ShowInTaskbar属性值为true,Hide不但隐藏窗口本身,同时隐藏其在任务栏上的图标。 WindowState,窗口状态属性,有3个枚举值: Normal,正常; Maximized,最大化; Minimized,最小化; RestoreBounds,获取窗口在最小化或最大化之前的大小和位置,有4个枚举值,Top、Left、Width、Height。
1 2 3 4 |
<span style="color:#008000;line-height:1.5 !important;">//</span><span style="color:#008000;line-height:1.5 !important;">输出当前窗口的RestoreBounds值</span><span style="color:#008000;line-height:1.5 !important;"> </span><span style="color:#0000FF;line-height:1.5 !important;">private</span> <span style="color:#0000FF;line-height:1.5 !important;">void</span> button1_Click(<span style="color:#0000FF;line-height:1.5 !important;">object</span> sender, RoutedEventArgs e) { MessageBox.Show(<span style="color:#0000FF;line-height:1.5 !important;">this</span>.RestoreBounds.ToString()); } |
该主窗口的Top:75,Left:75,Width:525,Height:350 只有窗口在Normal状态下移动或调整时,RestoreBounds的值才会改变。于是可以在窗口关闭时将RestoreBounds属性值保存到配置文件,下一次启动程序窗口时,读取上次保存的窗口大小、位置,来初始化窗口,以此实现保存用户配置等功能。MSDN上的例子:http://msdn.microsoft.com/zh-cn/library/system.windows.window.restorebounds.aspx 。但推荐使用config文件来保存配置,更方便。 应用程序窗口在上次关闭处启动 向资源中添加两个变量MainRestoreBounds和MainWindowState,对应类型如图所示,用于保存主窗口的RestoreBounds属性值。 XAML
1 |
<span style="color:#0000FF;line-height:1.5 !important;"><</span><span style="color:#800000;line-height:1.5 !important;">Window </span><span style="color:#FF0000;line-height:1.5 !important;">x:Class</span><span style="color:#0000FF;line-height:1.5 !important;">="WpfApplication1.MainWindow"</span><span style="color:#FF0000;line-height:1.5 !important;"> xmlns</span><span style="color:#0000FF;line-height:1.5 !important;">="http://schemas.microsoft.com/winfx/2006/xaml/presentation"</span><span style="color:#FF0000;line-height:1.5 !important;"> xmlns:x</span><span style="color:#0000FF;line-height:1.5 !important;">="http://schemas.microsoft.com/winfx/2006/xaml"</span><span style="color:#FF0000;line-height:1.5 !important;"> Width</span><span style="color:#0000FF;line-height:1.5 !important;">="360"</span><span style="color:#FF0000;line-height:1.5 !important;"> Height</span><span style="color:#0000FF;line-height:1.5 !important;">="240"</span><span style="color:#FF0000;line-height:1.5 !important;"> Closing</span><span style="color:#0000FF;line-height:1.5 !important;">="Window_Closing"</span><span style="color:#0000FF;line-height:1.5 !important;">></span> <span style="color:#0000FF;line-height:1.5 !important;"></</span><span style="color:#800000;line-height:1.5 !important;">Window</span><span style="color:#0000FF;line-height:1.5 !important;">></span> |
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<span style="color:#0000FF;line-height:1.5 !important;">using</span> System; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Collections.Generic; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Linq; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Text; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Controls; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Data; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Documents; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Input; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Media; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Media.Imaging; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Navigation; <span style="color:#0000FF;line-height:1.5 !important;">using</span> System.Windows.Shapes; <span style="color:#0000FF;line-height:1.5 !important;">namespace</span> WpfApplication1 { <span style="color:#0000FF;line-height:1.5 !important;">public</span> <span style="color:#0000FF;line-height:1.5 !important;">partial</span> <span style="color:#0000FF;line-height:1.5 !important;">class</span> MainWindow : Window { <span style="color:#0000FF;line-height:1.5 !important;">public</span> MainWindow() { InitializeComponent(); <span style="color:#008000;line-height:1.5 !important;">//</span><span style="color:#008000;line-height:1.5 !important;">读取配置文件</span><span style="color:#008000;line-height:1.5 !important;"> </span> <span style="color:#0000FF;line-height:1.5 !important;">try</span> { <span style="color:#008000;line-height:1.5 !important;">//</span><span style="color:#008000;line-height:1.5 !important;">设置位置、大小</span><span style="color:#008000;line-height:1.5 !important;"> </span> Rect restoreBounds = Properties.Settings.Default.MainRestoreBounds; <span style="color:#0000FF;line-height:1.5 !important;">this</span>.WindowState = WindowState.Normal; <span style="color:#0000FF;line-height:1.5 !important;">this</span>.Left = restoreBounds.Left; <span style="color:#0000FF;line-height:1.5 !important;">this</span>.Top = restoreBounds.Top; <span style="color:#0000FF;line-height:1.5 !important;">this</span>.Width = restoreBounds.Width; <span style="color:#0000FF;line-height:1.5 !important;">this</span>.Height = restoreBounds.Height; <span style="color:#008000;line-height:1.5 !important;">//</span><span style="color:#008000;line-height:1.5 !important;">设置窗口状态</span><span style="color:#008000;line-height:1.5 !important;"> </span> <span style="color:#0000FF;line-height:1.5 !important;">this</span>.WindowState = Properties.Settings.Default.MainWindowState; } <span style="color:#0000FF;line-height:1.5 !important;">catch</span> { } } <span style="color:#0000FF;line-height:1.5 !important;">private</span> <span style="color:#0000FF;line-height:1.5 !important;">void</span> Window_Closing(<span style="color:#0000FF;line-height:1.5 !important;">object</span> sender, System.ComponentModel.CancelEventArgs e) { <span style="color:#008000;line-height:1.5 !important;">//</span><span style="color:#008000;line-height:1.5 !important;">保存当前位置、大小和状态,到配置文件</span><span style="color:#008000;line-height:1.5 !important;"> </span> Properties.Settings.Default.MainRestoreBounds = <span style="color:#0000FF;line-height:1.5 !important;">this</span>.RestoreBounds; Properties.Settings.Default.MainWindowState = <span style="color:#0000FF;line-height:1.5 !important;">this</span>.WindowState; Properties.Settings.Default.Save(); } } } |
5.窗口的生命周期 关于各事件的描述: Initialized:当窗口的FrameworkElement底层初始化时触发,即InitializeComponent方法调用时触发。 LocationChanged:窗口被移动时触发。 Activated:窗口被激活时触发。 Deactivated:窗口处于非激活时(即其他窗口处于激活时)触发。 Loaded:显示窗口之前触发。 ContentRendered:当内容显示的时候触发。 Closing:尝试关闭窗口时触发,可以将参数CancelEventArgs的Cancel的属性设置为true,取消关闭操作。 Closed:在窗口关闭后触发该事件,无法取消。 Unloaded:当关闭窗口并且从可视化树移除后触发。 from:http://www.cnblogs.com/libaoheng/archive/2011/11/18/2253751.html
View DetailsWPF / Silverlight中的 Timer 与 DispatcherTimer 有什么区别呢? 这里我给大家简单介绍一下他们在使用和实现上的区别。 在一个应用程序中,Timer会重复生成time事件,而DispatcherTimer是一个集成到了Dispatcher队列中的时钟,这可以使它被按照指定的时间间隔以指定的priority定期执行。 对于一个Timer时钟事件,系统并不能保证在时间间隔到达后被立即执行,但是能够确保在时间间隔到达之前不被执行。这是因为DispatcherTimer像其他操作一样被放置在了Dispatcher队列中。何时执行DispatcherTimer事件依赖于队列中的其他任务以及他们的优先级. 如果一个WPF应用程序使用了Timer时钟,那么它的事件必须在一个单独的时钟线程中运行,而不是在UI线程中,这对于WPF应用程序毫无用处——你没法在UI线程之外直接访问UI元素,而只能通过Invoke或者BeginInvoke将操作发送给Dispatcher 对象,委托Dispatcher去执行UI操作。 看到这里,你大概知道了为什么我们在WPF中应该用DispatcherTimer而不是Timer了:DispatcherTimer与Dispatcher运行于同一个线程中——UI线程,而且具有相同的DispatcherPriority优先级。 所以,在WPF/Silverlight应用中,正确的做法如下所示:
1 2 3 4 |
DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(10); //10秒 timer.Tick += new EventHandler(timer_Tick); timer.Start(); |
1 2 3 4 |
private void timer1_Tick(object sender, EventArgs e) { //(你的定时处理) } |
参考:http://www.roboby.com/the_different_bitween_timer_and_dispatchertimer_in_wpf.html
View Detailseclipse打开当前文件所在文件夹 Run-->External Tools-->External Tools Configurations… new 一个 program Name 里面填:打开当前目录 location 里面填:C:\WINDOWS\explorer.exe Arguments 里面填:${container_loc} 打开文件夹目录 from:http://blog.csdn.net/aerchi/article/details/7102496
View Details在学习Android开发的过程你,你往往会去借鉴别人的应用是怎么开发的,那些漂亮的动画和精致的布局可能会让你爱不释手,作为一个开发者,你可能会很想知道这些效果界面是怎么去实现的,这时,你便可以对改应用的APK进行反编译查看。下面是我参考了一些文章后简单的教程详解。 (注:反编译不是让各位开发者去对一个应用破解搞重装什么的,主要目的是为了促进开发者学习,借鉴好的代码,提升自我开发水平。) 测试环境: win 7 使用工具: CSDN上下载地址: apktool (资源文件获取) 下载 dex2jar(源码文件获取) 下载 jd-gui (源码查看) 下载 Android反编译整合工具包(最新) 下载 官方最新版本下载地址: apktool(google code) dex2jar(google code) jd-gui(google code)最新版请见官方 工具介绍: apktool 作用:资源文件获取,可以提取出图片文件和布局文件进行使用查看 dex2jar 作用:将apk反编译成java源码(classes.dex转化成jar文件) jd-gui 作用:查看APK中classes.dex转化成出的jar文件,即源码文件 反编译流程: 一、apk反编译得到程序的源代码、图片、XML配置、语言资源等文件 下载上述工具中的apktool,解压得到3个文件:aapt.exe,apktool.bat,apktool.jar ,将需要反编译的APK文件放到该目录下, 打开命令行界面(运行-CMD) ,定位到apktool文件夹,输入以下命令:apktool.bat d -f test.apk test (命令中test.apk指的是要反编译的APK文件全名,test为反编译后资源文件存放的目录名称,即为:apktool.bat d -f [apk文件 ] [输出文件夹]) 说明获取成功,之后发现在文件夹下多了个test文件,点击便可以查看该应用的所有资源文件了。 如果你想将反编译完的文件重新打包成apk,那你可以:输入apktool.bat b test(你编译出来文件夹)便可,效果如下: 之后在之前的test文件下便可以发现多了2个文件夹: build dist(里面存放着打包出来的APK文件) 二、Apk反编译得到Java源代码 下载上述工具中的dex2jar和jd-gui ,解压 将要反编译的APK后缀名改为.rar或则 .zip,并解压,得到其中的额classes.dex文件(它就是java文件编译再通过dx工具打包而成的),将获取到的classes.dex放到之前解压出来的工具dex2jar-0.0.9.15 文件夹内, 在命令行下定位到dex2jar.bat所在目录,输入dex2jar.bat classes.dex,效果如下: 在改目录下会生成一个classes_dex2jar.jar的文件,然后打开工具jd-gui文件夹里的jd-gui.exe,之后用该工具打开之前生成的classes_dex2jar.jar文件,便可以看到源码了,效果如下: 被混淆过的效果图(类文件名称以及里面的方法名称都会以a,b,c….之类的样式命名): 三、 […]
View Details这年头找个正经能用的东西那是真难,网上一搜索一大堆,正经能用的没几个,得,最后还是得靠自己,正巧遇上需要AES加解密的地方了,而且还是Java和C#间的相互加解密操作,这里做个备忘 这里采用的加解密使用base64转码方法,ECB模式,PKCS5Padding填充,密码必须是16位,否则会报错哈 模式:Java的ECB对应C#的System.Security.Cryptography.CipherMode.ECB 填充方法:Java的PKCS5Padding对应C#System.Security.Cryptography.PaddingMode.PKCS7 Java和C#版的加解密是互通的,也就是能相互加解密,编码明确指定了采用UTF-8,有需要其他编码方法的请自行扩展 Java版
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 |
package nb.tmall.util; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import sun.misc.*; @SuppressWarnings("restriction") public class EncryptUtil { public static String aesEncrypt(String str, String key) throws Exception { if (str == null || key == null) return null; Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES")); byte[] bytes = cipher.doFinal(str.getBytes("utf-8")); return new BASE64Encoder().encode(bytes); } public static String aesDecrypt(String str, String key) throws Exception { if (str == null || key == null) return null; Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES")); byte[] bytes = new BASE64Decoder().decodeBuffer(str); bytes = cipher.doFinal(bytes); return new String(bytes, "utf-8"); } } |
C#版
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 |
using System; using System.Security.Cryptography; using System.Text; namespace CSharp.Util.Security { /// <summary> /// AES 加密 /// </summary> /// <param name="str"></param> /// <param name="key"></param> /// <returns></returns> public static string AesEncrypt(string str, string key) { if (string.IsNullOrEmpty(str)) return null; Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } /// <summary> /// AES 解密 /// </summary> /// <param name="str"></param> /// <param name="key"></param> /// <returns></returns> public static string AesDecrypt(string str, string key) { if (string.IsNullOrEmpty(str)) return null; Byte[] toEncryptArray = Convert.FromBase64String(str); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray); } } } |
from:http://www.cnblogs.com/lzrabbit/p/3639503.html
View DetailsAES指高级加密标准(Advanced Encryption Standard),是当前最流行的一种密码算法,在web应用开发,特别是对外提供接口时经常会用到,下面是我整理的一套php与java通用的AES加密解密算法。 php版代码如下:
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
<?php class CryptAES { protected $cipher = MCRYPT_RIJNDAEL_128; protected $mode = MCRYPT_MODE_ECB; protected $pad_method = NULL; protected $secret_key = ''; protected $iv = ''; public function set_cipher($cipher) { $this->cipher = $cipher; } public function set_mode($mode) { $this->mode = $mode; } public function set_iv($iv) { $this->iv = $iv; } public function set_key($key) { $this->secret_key = $key; } public function require_pkcs5() { $this->pad_method = 'pkcs5'; } protected function pad_or_unpad($str, $ext) { if ( is_null($this->pad_method) ) { return $str; } else { $func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad'; if ( is_callable($func_name) ) { $size = mcrypt_get_block_size($this->cipher, $this->mode); return call_user_func($func_name, $str, $size); } } return $str; } protected function pad($str) { return $this->pad_or_unpad($str, ''); } protected function unpad($str) { return $this->pad_or_unpad($str, 'un'); } public function encrypt($str) { $str = $this->pad($str); $td = mcrypt_module_open($this->cipher, '', $this->mode, ''); if ( empty($this->iv) ) { $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); } else { $iv = $this->iv; } mcrypt_generic_init($td, $this->secret_key, $iv); $cyper_text = mcrypt_generic($td, $str); $rt=base64_encode($cyper_text); //$rt = bin2hex($cyper_text); mcrypt_generic_deinit($td); mcrypt_module_close($td); return $rt; } public function decrypt($str){ $td = mcrypt_module_open($this->cipher, '', $this->mode, ''); if ( empty($this->iv) ) { $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); } else { $iv = $this->iv; } mcrypt_generic_init($td, $this->secret_key, $iv); //$decrypted_text = mdecrypt_generic($td, self::hex2bin($str)); $decrypted_text = mdecrypt_generic($td, base64_decode($str)); $rt = $decrypted_text; mcrypt_generic_deinit($td); mcrypt_module_close($td); return $this->unpad($rt); } public static function hex2bin($hexdata) { $bindata = ''; $length = strlen($hexdata); for ($i=0; $i amp;< $length; $i += 2) { $bindata .= chr(hexdec(substr($hexdata, $i, 2))); } return $bindata; } public static function pkcs5_pad($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); } public static function pkcs5_unpad($text) { $pad = ord($text{strlen($text) - 1}); if ($pad > strlen($text)) return false; if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false; return substr($text, 0, -1 * $pad); } } $keyStr = 'UITN25LMUQC436IM'; $plainText = 'this is a string will be AES_Encrypt'; $aes = new CryptAES(); $aes->set_key($keyStr); $aes->require_pkcs5(); $encText = $aes->encrypt($plainText); $decString = $aes->decrypt($encText); echo $encText,"n",$decString; ?> |
运行结果: fhTD0NNIzv4jUEhJuC1htFFXJ/4S/rL6tDCJPiNvJ8mVLHWOD0HWweuxHynxoZf9 this is a string will be AES_Encrypt java版代码如下:
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 |
import java.security.Key; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class CryptAES { private static final String AESTYPE ="AES/ECB/PKCS5Padding"; public static String AES_Encrypt(String keyStr, String plainText) { byte[] encrypt = null; try{ Key key = generateKey(keyStr); Cipher cipher = Cipher.getInstance(AESTYPE); cipher.init(Cipher.ENCRYPT_MODE, key); encrypt = cipher.doFinal(plainText.getBytes()); }catch(Exception e){ e.printStackTrace(); } return new String(Base64.encodeBase64(encrypt)); } public static String AES_Decrypt(String keyStr, String encryptData) { byte[] decrypt = null; try{ Key key = generateKey(keyStr); Cipher cipher = Cipher.getInstance(AESTYPE); cipher.init(Cipher.DECRYPT_MODE, key); decrypt = cipher.doFinal(Base64.decodeBase64(encryptData)); }catch(Exception e){ e.printStackTrace(); } return new String(decrypt).trim(); } private static Key generateKey(String key)throws Exception{ try{ SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES"); return keySpec; }catch(Exception e){ e.printStackTrace(); throw e; } } public static void main(String[] args) { String keyStr = "UITN25LMUQC436IM"; String plainText = "this is a string will be AES_Encrypt"; String encText = AES_Encrypt(keyStr, plainText); String decString = AES_Decrypt(keyStr, encText); System.out.println(encText); System.out.println(decString); } } |
运行结果: fhTD0NNIzv4jUEhJuC1htFFXJ/4S/rL6tDCJPiNvJ8mVLHWOD0HWweuxHynxoZf9 this is a string will be AES_Encrypt 转自: http://alunblog.duapp.com/?p=17
View Details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/// <summary> /// 更新点击量 /// </summary> /// <param name="id"></param> /// <param name="num"></param> public void UpdateHits(int id, int num) { const string sql = @"update articles set hits+=@Hits where id=@Id"; object[] args = { new SqlParameter { ParameterName = "@Hits", Value = num}, new SqlParameter { ParameterName = "@Id", Value=id} }; _db.Database.ExecuteSqlCommand(sql, args); } |
1. 一个控制台例子,实现动态生成Word。 首先,添加引用:COM->Microsoft Word 11.0 Object Library。
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Microsoft.Office.Interop.Word; using System.Reflection; namespace TestWord { class Program { static void Main(string[] args) { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; //endofdoc是预定义的bookmark //创建一个document. Microsoft.Office.Interop.Word._Application oWord; Microsoft.Office.Interop.Word._Document oDoc; oWord = new Microsoft.Office.Interop.Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); //在document的开始部分添加一个paragraph. Microsoft.Office.Interop.Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Text = "Heading 1"; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; //24 pt 行间距 oPara1.Range.InsertParagraphAfter(); //在当前document的最后添加一个paragraph Microsoft.Office.Interop.Word.Paragraph oPara2; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara2 = oDoc.Content.Paragraphs.Add(ref oRng); oPara2.Range.Text = "Heading 2"; oPara2.Format.SpaceAfter = 6; oPara2.Range.InsertParagraphAfter(); //接着添加一个paragraph Microsoft.Office.Interop.Word.Paragraph oPara3; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara3 = oDoc.Content.Paragraphs.Add(ref oRng); oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:"; oPara3.Range.Font.Bold = 0; oPara3.Format.SpaceAfter = 24; oPara3.Range.InsertParagraphAfter(); //添加一个3行5列的表格,填充数据,并且设定第一行的样式 Microsoft.Office.Interop.Word.Table oTable; Microsoft.Office.Interop.Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; int r, c; string strText; for (r = 1; r <= 3; r++) for (c = 1; c <= 5; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } oTable.Rows[1].Range.Font.Bold = 1; oTable.Rows[1].Range.Font.Italic = 1; //接着添加一些文字 Microsoft.Office.Interop.Word.Paragraph oPara4; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara4 = oDoc.Content.Paragraphs.Add(ref oRng); oPara4.Range.InsertParagraphBefore(); oPara4.Range.Text = "And here's another table:"; oPara4.Format.SpaceAfter = 24; oPara4.Range.InsertParagraphAfter(); //添加一个5行2列的表,填充数据并且改变列宽 wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; for (r = 1; r <= 5; r++) for (c = 1; c <= 2; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } oTable.Columns[1].Width = oWord.InchesToPoints(2); //设置列宽 oTable.Columns[2].Width = oWord.InchesToPoints(3); //Keep inserting text. When you get to 7 inches from top of the //document, insert a hard page break. object oPos; double dPos = oWord.InchesToPoints(7); oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter(); do { wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.ParagraphFormat.SpaceAfter = 6; wrdRng.InsertAfter("A line of text"); wrdRng.InsertParagraphAfter(); oPos = wrdRng.get_Information (Microsoft.Office.Interop.Word.WdInformation.wdVerticalPositionRelativeToPage); } while (dPos >= Convert.ToDouble(oPos)); object oCollapseEnd = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd; object oPageBreak = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak; wrdRng.Collapse(ref oCollapseEnd); wrdRng.InsertBreak(ref oPageBreak); wrdRng.Collapse(ref oCollapseEnd); wrdRng.InsertAfter("We're now on page 2. Here's my chart:"); wrdRng.InsertParagraphAfter(); //添加一个chart Microsoft.Office.Interop.Word.InlineShape oShape; object oClassType = "MSGraph.Chart.8"; wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Demonstrate use of late bound oChart and oChartApp objects to //manipulate the chart object with MSGraph. object oChart; object oChartApp; oChart = oShape.OLEFormat.Object; oChartApp = oChart.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, oChart, null); //Change the chart type to Line. object[] Parameters = new Object[1]; Parameters[0] = 4; //xlLine = 4 oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty, null, oChart, Parameters); //Update the chart image and quit MSGraph. oChartApp.GetType().InvokeMember("Update", BindingFlags.InvokeMethod, null, oChartApp, null); oChartApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, oChartApp, null); //... If desired, you can proceed from here using the Microsoft Graph //Object model on the oChart and oChartApp objects to make additional //changes to the chart. //Set the width of the chart. oShape.Width = oWord.InchesToPoints(6.25f); oShape.Height = oWord.InchesToPoints(3.57f); //Add text after the chart. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("THE END."); Console.ReadLine(); } } } |
2. 介绍几篇牛人写的关于操作Word的文章 [分享]一段导出到word模版的代码 http://www.cnblogs.com/goody9807/archive/2005/08/25/222526.html 再谈word2003编程 http://www.cnblogs.com/Andmm/archive/2008/06/18/1224422.html 最近一直在做C#操作office方面的工作!总结一下!Word(二) http://www.cnblogs.com/wngwz/archive/2004/08/19/34678.html C#也能动态生成Word文档并填充数据 http://www.cnblogs.com/qyfan82/archive/2007/09/14/893293.html from:http://www.cnblogs.com/tianzhiliang/archive/2011/07/07/2099800.html
View Details引用http://blog.csdn.net/mengyao/archive/2007/09/13/1784079.aspx using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using Microsoft.Office.Interop.Word; namespace WindowsApplication4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { CreateWordFile("c:\\dd.doc"); } public string CreateWordFile(string CheckedInfo) { string message = ""; try { Object Nothing = System.Reflection.Missing.Value; Directory.CreateDirectory("C:/CNSI"); //创建文件所在目录 string name = "CNSI_" + DateTime.Now.ToLongDateString()+".doc"; object filename = "C://CNSI//" + name; //文件保存路径 //创建Word文档 Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); //添加页眉 WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader; WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]"); WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置 WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距 //移动焦点并换行 object count = 14; object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行; WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 WordApp.Selection.TypeParagraph();//插入段落 //文档中创建表格 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing); //设置表格样式 newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap; newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; newTable.Columns[1].Width = 100f; newTable.Columns[2].Width = 220f; newTable.Columns[3].Width = 105f; //填充表格内容 newTable.Cell(1, 1).Range.Text = "产品详细信息表"; newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体 //合并单元格 newTable.Cell(1, 1).Merge(newTable.Cell(1, 3)); WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中 //填充表格内容 newTable.Cell(2, 1).Range.Text = "产品基本信息"; newTable.Cell(2, 1).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色 //合并单元格 newTable.Cell(2, 1).Merge(newTable.Cell(2, 3)); WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //填充表格内容 newTable.Cell(3, 1).Range.Text = "品牌名称:"; newTable.Cell(3, 2).Range.Text = "BrandName"; //纵向合并单元格 newTable.Cell(3, 3).Select();//选中一行 object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine; object moveCount = 5; object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend; WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend); WordApp.Selection.Cells.Merge(); //插入图片 string FileName = @"c:\picture.jpg";//图片所在路径 object LinkToFile = false; object SaveWithDocument = true; object Anchor = WordDoc.Application.Selection.Range; WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度 WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度 //将图片设置为四周环绕型 Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape(); […]
View Details