“git clone” 漏洞或可导致克隆过程中执行代码
近日,GitHub 官博披露了一个 “git clone” 命令的漏洞 CVE-2021-213,该漏洞可能导致特制的仓库在 git clone 过程中能够执行代码。 该漏洞源于 clean/smudge 过滤器(如Git LFS)中的延迟检查机制。 如果一个特别制作的版本库包含符号链接以及使用 clean/smudge 过滤器的文件,可能会导致在克隆到不区分大小写的文件系统(如 NTFS、HFS+ 或 APFS(即 Windows 和 macOS上 的默认文件系统))时执行刚检查出来的脚本。这个过程中,注意,clean/smudge 过滤器是必须的,而 Windows 默认配置了 Git LFS,因此更易受到攻击。2.15 到 2.30.1 的版本均会受到影响。 解决这个漏洞的最有效方法是升级到 2.30.2。如不能立即升级,也可以通过以下任何一种方式来降低风险: 通过运行 git config --global core.symlinks false 禁用 Git 中的符号链接支持。 禁用对进程过滤器的支持。(可以通过运行 git config --show-scope --get-regexp 'filter/\…*/\ process' 来查看系统是否配置了这些过滤器) 避免克隆不受信任的仓库。 GitHub 本身不容易受到这种攻击,因为其不会在服务器上存储已检查出的仓库副本,但 GitHub Pages 除外,尽管它没有使用任何 clean/smudge 过滤器。目前,该问题已在 3 月 9 日星期二发布的补丁中进行了修补。 from:https://www.oschina.net/news/132640/git-clone-vulnerability-cve-2021-213
View Detailsgit修改之前某一个特定的commit
假如之前的某个提交的上一笔commit id是:928fc8a3686bf5fcf4527873e075703a9998c127
1 2 |
git log #查看commit id 找到上一笔commit id git rebase 928fc8a3686bf5fcf4527873e075703a9998c127 --interactive |
然后在vi中修改pick为edit,wq保存退出,接着进行内容修改,git add后git commit --amend 最后git rebase --continue即可再次回到最新的头部 作者:一只特例独行de猪 链接:https://www.jianshu.com/p/96ed16586a86 来源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
View DetailsCBC模式和ECB模式解读
一 什么是CBC模式 CBC模式的全称是Cipher Block Chaining模式(密文分组链接模式),之所以叫这个名字,是因为密文分组像链条一样相互连接在一起。 在CBC模式中,首先将明文分组与前一个密文分组进行XOR运算,然后再进行加密。 CBC模式加解密过程如下: 我们来比较一下ECB模式与CBC模式的区别 ECB模式只进行了加密,而CBC模式则在加密之前进行了一次XOR。 二 初始化向量 当加密第一个明文分组时,由于不存在“前一个密文分组”,因此需要事先准备一个长度为一个分组的比特序列来代替“前一个密文分组”,这个比特序列称为初始化向量(Initialization Vector),通常缩写为IV,一般来说,每次加密时都会随机产生一个不同的比特序列来作为初始化向量。 三 CBC模式的特点 明文分组在加密之前一定会与“前一个密文分组”进行XOR运算,因此即使明文分组1和明文分组2的值是相等的,密文分组1和2的值也不一定是相等的。这样一来,ECB模式的缺陷在CBC模式中就不存在了。 加密过程:在CBC模式中,无法单独对一个中间的明文分组进行加密。例如,如果要生成密文分组3,则至少需要凑齐明文分组1、2、3才行。 解密过程:假设CBC模式加密的密文分组中有一个分组损坏了。在这种情况下,只要密文分组的长度没有发生变化,则解密时最多只有2个分组受到数据损坏的影响。见下图: 假设CBC模式的密文分组中有一些比特缺失了,那么此时即便只缺失1比特,也会导致密文分组的长度发生变化,此后的分组发生错位,这样一来,缺失比特的位置之后的密文分组也就全部无法解密。见下图: 四 对CBC模式的攻击 假设主动攻击者的目的是通过修改密文来操纵解密后的明文。如果攻击者能够对初始化向量中的任意比特进行反转(将1变成0,将0变成1),则明文分组中相应的比特也会被反转。这是因为在CBC模式的解密过程中,第一个明文分组会和初始化向量进行XOR运算。见下图。 但是想对密文分组也进行同样的攻击就非常困难了。例如,如果攻击者将密文分组1中的某个比特进行反转,则明文分组2中相应比特也会被反转,然而这一比特的变化却对解密后的明文分组1中的多个比特造成了影响,也就是说,只让明文分1中所期望的特定比特发生变化是很困难的。 五 填充提示攻击 填充提示攻击是一种利用分组密码中填充部分来进行攻击的方法。在分组密码中,当明文长度不为分组长度的整数倍时,需要在最后一个分组中填充一些数据使其凑满一个分组长度。在填充提示攻击中,攻击者会反复发送一段密文,每次发送时都对填充数据进行少许改变。由于接收者(服务器)在无法正确解密时会返回一个错误消息,攻击者通过这一错误消息就可以获得一部分与明文相关的信息。这一攻击并不仅限于CBC模式,而是适用所有需要进行分组填充的模式。 2014年对SSL3.0 造成了重大影响POODLE攻击实际上就是一种填充示攻击。 六 对初始化向量(IV)进行攻击 初始化向量(IV)必须使用不可预测的随机数。然而在SSL/TLS的TLS1.0版本协议中,IV并没有使用不可预测的随机数,而是使用上一次CBC模式加密时的最后一个分组。为了防御攻击者对此进行攻击,TLS1.1以上的版本中改为了必须显示传送IV。 七 CBC模式应用 确保互联网安全的通信协议之一SSL/TLS,就是使用CBC模式来确保通信机密性的,如使用CBC模式三重DES的3DES_EDE_CBC以及CBC模式256比特AES的AES_256_CBC等。 ———————————————— 版权声明:本文为CSDN博主「cakincqm」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/chengqiuming/article/details/82288851 from:https://www.cnblogs.com/wangle1001986/p/11468419.html
View DetailsPadLeft,PadRight用法
补位 string str = "100"; str.PadLeft(5,’0′) 输出:00100 str.PadRight(5, '0') 输出:10000 from:https://www.cnblogs.com/daviddong/p/5949794.html
View Detailsjs对url进行编码和解码(三种方式区别)
*** 只有 0-9[a-Z] $ – _ . + ! * ' ( ) , 以及某些保留字,才能不经过编码直接用于 URL。 ***例如:搜索的中文关键字,复制网址之后再粘贴就会发现该URL已经被转码。 1、escape 和 unescape 原理:对除ASCII字母、数字、标点符号 @ * _ + – . / 以外的其他字符进行编码。 编码:escape('http://www.baidu.com?name=zhang@xiao@jie&order=1') 结果:"http%3A//www.baidu.com%3Fname%3Dzhang@xiao@jie%26order%3D1" escape('张') 结果:"%u5F20" 解码:unescape("http%3A//www.baidu.com%3Fname%3Dzhang@xiao@jie%26order%3D1") 结果:"http://www.baidu.com?name=zhang@xiao@jie&order=1" unescape("%u5F20") 结果:"张" 2、encodeURI 和 decodeURI 原理:返回编码为有效的统一资源标识符 (URI) 的字符串,不会被编码的字符:! @ # $ & * ( ) = : / ; ? + ' encodeURI()是Javascript中真正用来对URL编码的函数。 编码:encodeURI('http://www.baidu.com?name=zhang@xiao@jie&order=1') 结果:"http://www.baidu.com?name=zhang@xiao@jie&order=1" 解码:decodeURI("http%3A//www.baidu.com%3Fname%3Dzhang@xiao@jie%26order%3D1") 结果:"http%3A//www.baidu.com%3Fname%3Dzhang@xiao@jie%26order%3D1" 3、encodeURIComponent 和 decodeURIComponent 原理:对URL的组成部分进行个别编码,而不用于对整个URL进行编码 编码:encodeURIComponent('http://www.baidu.com?name=zhang@xiao@jie&order=1') 结果:"http%3A%2F%2Fwww.baidu.com%3Fname%3Dzhang%40xiao%40jie%26order%3D1" 解码:decodeURIComponent("http%3A%2F%2Fwww.baidu.com%3Fname%3Dzhang%40xiao%40jie%26order%3D1") "http://www.baidu.com?name=zhang@xiao@jie&order=1" from:https://www.cnblogs.com/z-one/p/6542955.html
View Details详解WebApi如何传递参数
一 概述 一般地,我们在研究一个问题时,常规的思路是为该问题建模;我们在研究相似问题时,常规思路是找出这些问题的共性和异性。基于该思路,我们如何研究WebApi参数传递问题呢? 首先,从参数本身来说,种类较为多(如int,double,float,string,array,Object等),且有些类型较为复杂(如值类型和引用类型的机制等); 其次,从基于WebApi的Http请求方法来说,种类多且不尽相同(如Get,post,Delete,put,head等),在上一篇文章 :【WebApi系列】浅谈HTTP在WebApi开发中的运用 中,我们简要描述了Http请求的20个方法; ………. 如此复杂且不尽相同,关于WebApi参数传递,我们该选择什么作为切入点来研究呢?基于我们上面提到的研究思路,我们想到了.NET Framework框架,那么,我们来看看基于.NET Framework框架的的WebApi 模板是怎样的呢? 请按图中步骤操作 我们来看看Values控制器是怎样的
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 |
public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } } |
从Values控制器,我们不难得出如下几个结论: (1)WebApi常规方法为四个:Get,Post,Put和Delete; (2)四种方法的参数可归结为两大类:url传递(Request-url)和Body(Request-body)传递; (3)基于(2),我们将四种方法的参数传递归为两大类,而这两大类又集中在Get和Post中体现了(Put是Get和Post的组合,Delete与Get类似); 其实,分析到现在,我们很容易找得到了研究WebApi参数传递的切入点?研究Get和Post方法参数传递即可。是的,没错,我们本篇文章就是基于Get和Post方法的参数传递,前者对应Request-url,后者对应Reqeust-Body。 二 Get 1 基础数据类型 1.1 方法只含一个形参(参数传得进去) ajax
1 2 3 4 5 6 7 8 9 10 |
$(document).ready(function () { $("#FindProdcutDetail").click(function () { $.ajax({ type: "Get", //url: "/api/Default/GetProductDetails?ProductCode=JX80869" url: "/api/Default/GetProductDetails", data: { "ProductCode":"JX80869"} }) }) }) |
Result 总结 (1)当Get方法形参为一个且为基本数据类型时,Get方法能接受外部传递的值 (2)Get传值的本质是通过url字符串拼接,如上两两种url形式的传递的结果都是一样 url形式1
1 |
url: "/api/Default/GetProductDetails?ProductCode=JX80869" |
url形式2
1 2 |
url: "/api/Default/GetProductDetails", data: { "ProductCode":"JX80869"} |
我们用Goole Chrome来看看结果,发现url形式1和url形式2均一致 (3)Get传递参数本质是url字符串拼接,Request-Head头部传递,Request-Body中不能传递(这是与Post方法的本质区别),我们举两个例子 例子1:我们将形参添加[FromBody]属性后,值传递不进去 例子2:我们用PostMan来测试,发现PostMan中,Get方法参数Body为灰色,是不能选中的 1.2 方法含有多个形参(参数传得进去)
1 2 3 4 5 6 7 8 9 |
$(document).ready(function () { $("#FindProdcutDetail").click(function () { $.ajax({ type: "Get", url: "/api/Default/GetProductDetails", data: { "ProductCode": "JX80869","ProductName":"YaGao"} }) }) }) |
result 2 实体对象类型(参数传不进去) model
1 2 3 4 5 6 7 8 9 10 11 12 |
1 public class ProductDetail 2 { 3 //产品编码 4 [Required] 5 public string ProductCode { get; set; } 6 //产品名称 7 [Required] 8 public string ProductName { get; set; } 9 //产品价格 10 [Required] 11 public double ProductPrice{ get; set; } 12 } |
ajax
1 2 3 4 5 6 7 8 9 10 |
$(document).ready(function () { var productDetail = { "ProductName": "YaGao", "ProductCode": "JX80869", "ProductPrice": 40.5}; $("#FindProdcutDetail").click(function () { $.ajax({ type: "Get", url: "/api/Default/ProductDetails", data: productDetail }) }) }) |
result: 分析 3 实体对象和基础数据类型混合(实体传不进去,基础数据能传递进去) ajax
1 2 3 4 5 6 7 8 9 |
1 $(document).ready(function () { 2 $("#FindProdcutDetail").click(function () { 3 $.ajax({ 4 type: "Get", 5 url: "/api/Default/GetProductDetails", 6 data: { "_productDetail": "ObjectEntity","ProductName":"YaGao"} 7 }) 8 }) 9 }) |
result 4 最小满足原则(参数传得进去) 所谓“最小满足原则”,指外部参数必须至少满足被调用方法的形参(形参个数,形参类型和形参名字),换句话说,被调用方法具有的形参,外部参数必须传递进来,被调用方法没有 的形参,外部参数传递与否都可以,否则将会产生状态码404错误,用数学集合的思路来理解的话,被调用方法的形参相当于外部参数的子集。如下例子,我们举一个真子集的例子, 即外部传递参数的个数大于被调方法的的形参个数。 Ajax
1 2 3 4 5 6 7 8 9 |
$(document).ready(function () { $("#FindProdcutDetail").click(function () { $.ajax({ type: "Get", url: "/api/Default/GetProductDetails", data: {"ProductCode": "JX00034", "ProductName": "YaGao", "ProductPrice": 20.5, "PrudcutType": "Daily Necessities"} }) }) }) |
result 分析:主要原因是路由规则,路由从url里面取参数与aciton参数匹配,直到匹配满足为止,具体详细深入内容,在【WebApi系列】路由章节分析。 5 url长度限制 url参数长度是有一定限制的,当超过一定长度,会报404错误 ajax
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 |
$(document).ready(function () { $("#FindProdcutDetail").click(function () { $.ajax({ type: "Get", url: "/api/Default/GetProductDetails", data: { "ProductCode": "JX00034xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx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xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + "JX00034xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + "JX00034xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + "JX00034xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + "JX00034xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } }) }) }) |
result 6 Get规范化 关于Get类型规范化,应注意两点,避免不必要的错误或异常:(1)方法的命名尽量采用:“Get+方法名”的形式 (2)在每个方法上加上特性[HttpGet]。 […]
View DetailsWeb API POST [FromBody] string value 接受参数
网上看到很多关于这这个问题的解决方案,但是都不正确,我也恰巧遇到这个问题,所有把正确的解决方案写出来,希望给后来人参考,如有不同意见欢迎指正
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 |
namespace WebApi.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public IActionResult Post([FromBody] string value) { return Ok(value); } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } } } |
1 2 3 4 5 6 |
### POST http://localhost:49518/api/values HTTP/1.1 Content-Type: application/json "ddddff" |
1 2 3 4 5 6 7 |
var value = '1111';$.ajax({ type: 'POST', contentType: "application/json", url: url, data: value, //如果是 string,int 直接传值 ,如果是模型 就要传对象{} .......省略 }); |
也就是data 不要传{} 对象,直接传字符串或者int from:https://www.cnblogs.com/microestc/p/11003233.html
View Detailsswap空间不足需要扩充
1 2 3 4 5 6 7 8 9 10 |
mkdir /swap cd /swap # 创建4G分区文件 dd if=/dev/zero of=swapfile bs=1G count=4 # 修改权限 chmod 600 /swap/swapfile # 设置swap mkswap /swap/swapfile # 启用swap swapon /swap/swapfile |
1 2 3 4 |
[root@datagrad swap]# swapon -s Filename Type Size Used Priority /dev/dm-1 partition 4194300 0 -2 /swap/swapfile file 4194300 0 -3 |
1 2 |
# 开机挂载 echo '/swap/swapfile swap swap defaults 0 0' >> /etc/fstab |
from:https://www.cnblogs.com/leoshi/p/12679962.html
View DetailsAsp.Net Core实战常见加密算法(C#)
先问个问题:为什么要使用加密算法? 因为数据在网络中传输时面临4个问题: 窃听 假冒 篡改 事后否认 加密技术就是用来解决“窃听”这个问题的。通常分为两大类:对称加密和非对称加密。 对称加密 概念:对称加密就是加密和解密使用同一个密钥,通常称之为“Session Key ”,这种加密技术在当今被广泛采用,如美国政府所采用的DES加密标准就是一种典型的对称加密算法,它的Session Key长度为56bits。 优点:算法公开、计算量小、加密速度快、加密效率高。适用于需要加密大量数据的场景。 缺点:由于加解密使用同一个密钥,密钥传输的过程不安全,且容易被破解,密钥管理也比较麻烦。例如:不适用于浏览器到服务器的通信,因为密钥一旦发送到浏览器端就很容易暴露。 常见算法:AES,DES,3DES,TDEA,Blowfish,RC5,IDEA 非对称加密 概念:非对称加密就是加密和解密所使用的不是同一个密钥,通常有两个密钥,称为“公钥”和“私钥”,它们两个必需配对使用。“公钥”是指可以对外公布的,“私钥”则不能,只能由持有人一个人知道。 优点:由于加解密是用不同的密钥,私钥并不公开,这样就保证了信息在网络传输中的安全性:即使被拦截也无法解密。非常适用于客户端到服务端的数据传输。例如:支付宝的支付请求,数字签名等。 缺点:加密速度慢,比较耗资源。只适用于少量敏感信息的加密。如果加密大量消息则效率会变得低下。另外,如果动态生成公钥和私钥也比较耗资源。 常见算法:RSA,Elgamal,背包算法,Rabin,D-H,ECC 有人可能会问,上面两类加密方式怎么没有MD5?MD5……严格意义上说不是一种加密算法,因为它不能解密。它只是一种密码散列算法,只是为了校验信息用的:保证信息没有篡改。如:你下载软件或游戏时,在下载页面官方都会提供一个“MD5字符串”,你下载完成后可以用md5工具对下载到的软件md5校验,如果得到的md5串和下载页面的一致,就说明软件或游戏没有被篡改过,可放心使用。 下面我们就一块来实战几种常见的加密方式和散列算法: DES 分类:对称加密 DES全称为Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法,1977年被美国联邦政府的国家标准局确定为联邦资料处理标准(FIPS),并授权在非密级政府通信中使用,随后该算法在国际上广泛流传开来。
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 |
using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace EncryptionPractice.Utils { public class DESUtils { /// <summary> /// 加密数据 /// </summary> /// <param name="text"></param> /// <param name="sessionKey"></param> /// <returns></returns> public static string Encrypt(string text, string sessionKey) { try { var des = GetDESProvider(sessionKey); var bytes = Encoding.Default.GetBytes(text); using var memoryStream = GetMemoryStream(des.CreateEncryptor(), bytes); var result = new StringBuilder(); foreach (var byteItem in memoryStream.ToArray()) { result.AppendFormat("{0:X2}", byteItem); } return result.ToString(); } catch { return string.Empty; } } /// <summary> /// 解密数据 /// </summary> /// <param name="ciphertext"></param> /// <param name="sessionKey"></param> /// <returns></returns> public static string Decrypt(string ciphertext, string sessionKey) { try { var length = ciphertext.Length / 2; var bytes = new byte[length]; for (var i=0; i<length; i++) { var j = Convert.ToInt32(ciphertext.Substring(i * 2, 2), 16); bytes[i] = (byte) j; } var des = GetDESProvider(sessionKey); using var memoryStream = GetMemoryStream(des.CreateDecryptor(), bytes); return Encoding.Default.GetString(memoryStream.ToArray()); } catch { return string.Empty; } } /// <summary> /// 获取DES引擎 /// </summary> /// <param name="sessionKey"></param> /// <returns></returns> private static DESCryptoServiceProvider GetDESProvider(string sessionKey) { var md5Key = MD5Utils.Get32(sessionKey).Substring(8, 8); var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(md5Key), IV = Encoding.ASCII.GetBytes(md5Key) }; return des; } /// <summary> /// 获取内存流 /// </summary> /// <param name="cryptoTransform"></param> /// <param name="bytes"></param> /// <returns></returns> private static MemoryStream GetMemoryStream(ICryptoTransform cryptoTransform, byte[] bytes) { var memoryStream = new MemoryStream(); using var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write); cryptoStream.Write(bytes, 0, bytes.Length); cryptoStream.FlushFinalBlock(); return memoryStream; } } } |
AES 分类:对称加密 高级加密标准(Advanced Encryption Standard,AES),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES(Data Encryption Standard),已经被多方分析且广为全世界所使用。
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 |
using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace EncryptionPractice.Utils { public class AESUtils { /// <summary> /// 默认Key /// </summary> const string KEY = "E10ADC3949BA59AB"; /// <summary> /// 默认偏移量 /// </summary> const string IV = "BE56E057F20F883E"; /// <summary> /// 加密 /// </summary> /// <param name="text"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public static string Encrypt(string text, string key = KEY, string iv = IV) { var bytes = Encoding.UTF8.GetBytes(text); var result = Origin(bytes, false, key, iv); return Convert.ToBase64String(result, 0, result.Length); } /// <summary> /// 解密 /// </summary> /// <param name="ciphertext"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public static string Decrypt(string ciphertext, string key = KEY, string iv = IV) { var bytes = Convert.FromBase64String(ciphertext); var result = Origin(bytes, true, key, iv); if (result.Length < 1) return string.Empty; return Encoding.UTF8.GetString(result); } /// <summary> /// 底层方法 /// </summary> /// <param name="bytes"></param> /// <param name="isDecrypt"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> private static byte[] Origin(byte[] bytes, bool isDecrypt, string key = KEY, string iv = IV) { try { var keyBytes = Encoding.UTF8.GetBytes(key); var ivBytes = Encoding.UTF8.GetBytes(iv); var rijndaelManaged = new RijndaelManaged { BlockSize = 128, KeySize = 256, FeedbackSize = 128, Padding = PaddingMode.PKCS7, Key = keyBytes, IV = ivBytes, Mode = CipherMode.CBC }; var cryptoTransform = isDecrypt ? rijndaelManaged.CreateDecryptor() : rijndaelManaged.CreateEncryptor(); var result = cryptoTransform.TransformFinalBlock(bytes, 0, bytes.Length); return result; } catch { return new byte[] { }; } } } } |
RSA 分类:非对称加密 RSA是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。RSA就是他们三人姓氏开头字母拼在一起组成的。RSA公开密钥密码体制是一种使用不同的加密密钥与解密密钥,“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制。
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 |
using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace EncryptionPractice.Utils { public class RSAUtils { /// <summary> /// 加密 /// </summary> /// <param name="text">明文</param> /// <param name="publicKey">公钥</param> /// <returns>密文</returns> public static string Encrypt(string text, string publicKey) { var blockSize = 256; // 加密块大小,越大越慢 var bytes = Encoding.UTF8.GetBytes(text); var length = bytes.Length; // rsa实例 var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(publicKey); var offSet = 0; // 游标 var i = 0; byte[] cache; var ms = new MemoryStream(); while (length - offSet > 0) { var len = length - offSet > blockSize ? blockSize : length - offSet; var temp = new byte[len]; Array.Copy(bytes, offSet, temp, 0, len); cache = rsa.Encrypt(bytes, false); ms.Write(cache, 0, cache.Length); i++; offSet = i * blockSize; } var cipherBytes = ms.ToArray(); return Convert.ToBase64String(cipherBytes); } /// <summary> /// RSA解密 /// </summary> /// <param name="ciphertext">密文</param> /// <param name="privateKey">私钥</param> /// <returns>明文</returns> public static string Decrypt(string ciphertext, string privateKey) { var blockSize = 256; var bytes = Convert.FromBase64String(ciphertext); var length = bytes.Length; // rsa实例 var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(privateKey); var offSet = 0; // 游标 var i = 0; byte[] cache; var ms = new MemoryStream(); while (length - offSet > 0) { var len = length - offSet > blockSize ? blockSize : length - offSet; var temp = new byte[len]; Array.Copy(bytes, offSet, temp, 0, len); cache = rsa.Decrypt(temp, false); ms.Write(cache, 0, cache.Length); i++; offSet = i * blockSize; } var cipherBytes = ms.ToArray(); return Encoding.UTF8.GetString(cipherBytes); } } } |
生成公钥/密钥的方法(只适用于C#,其他编程语言使用需要转换)
1 2 3 |
var rsa = new RSACryptoServiceProvider(); var publicKey = rsa.ToXmlString(false); var privateKey = rsa.ToXmlString(true); |
MD5 分类:散列算法 MD5信息摘要算法(MD5 Message-Digest Algorithm),一种被广泛使用的密码散列函数,可以产生出一个128位(16字节)的散列值(hash value),用于确保信息传输完整一致。MD5由美国密码学家罗纳德·李维斯特(Ronald Linn Rivest)设计,于1992年公开。1996年后该算法被证实存在弱点,可以被加以破解,对于需要高度安全性的数据,专家一般建议改用其他算法,如SHA-2。
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 |
using System; using System.Security.Cryptography; using System.Text; namespace EncryptionPractice.Utils { public class MD5Utils { /// <summary> /// 获取16位散列值 /// </summary> /// <param name="text"></param> /// <returns></returns> public static string Get16(string text) { return Get32(text).Substring(7, 16); } /// <summary> /// 获取32位散列值 /// </summary> /// <param name="text"></param> /// <returns></returns> public static string Get32(string text) { using var md5 = MD5.Create(); var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(text)); var result = BitConverter.ToString(hash); return result.Replace("-", "").ToUpper(); } /// <summary> /// 获取16位散列值 v2 /// </summary> /// <param name="text"></param> /// <returns></returns> public static string Get16v2(string text) { return Get32v2(text).Substring(7, 16); } /// <summary> /// 获取32位散列值 /// </summary> /// <param name="text">字符串</param> /// <returns></returns> public static string Get32v2(string text) { var md5 = new MD5CryptoServiceProvider(); var hash = md5.ComputeHash(Encoding.Default.GetBytes(text)); var resutl = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { resutl.Append(hash[i].ToString("x2")); } return resutl.ToString().ToUpper(); } } } |
SHA-2 分类:散列算法 SHA-2,名称来自于安全散列算法2(英语:Secure Hash Algorithm 2)的缩写,一种密码散列函数算法标准,由美国国家安全局研发,由美国国家标准与技术研究院(NIST)在2001年发布。属于SHA算法之一,是SHA-1的后继者。其下又可再分为六个不同的算法标准,包括了:SHA-224、SHA-256、SHA-384、SHA-512、SHA-512/224、SHA-512/256。
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 |
using System.Security.Cryptography; using System.Text; namespace EncryptionPractice.Utils { public class SHAUtils { /// <summary> /// SHA256加密 /// </summary> /// <param name="data"></param> /// <returns></returns> public static string Encrypt(string data) { var bytes = Encoding.UTF8.GetBytes(data); var hash = SHA256.Create().ComputeHash(bytes); var result = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { result.Append(hash[i].ToString("x2")); } return result.ToString(); } } } |
欢迎转载,请注明出处:龙生时代
View DetailsJAVA版身份证获取性别、出生日期及年龄
工作中需要根据身份证获取性别、出生日期及年龄,且要还要支持15位长度的身份证号码,网上搜索了一下,经过测试好像多少存在点问题,干脆自已写一个。 CertificateNo.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 |
package com.bijian.study; import java.util.Calendar; import java.util.regex.Pattern; /** * 根据身份证获取性别、出生日期、年龄,支持15、18位身份证 */ public class CertificateNo { public ResultDTO parseCertificateNo(String certificateNo) { ResultDTO resultDTO = new ResultDTO(); String myRegExpIDCardNo = "^\\d{6}(((19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\\d{3}([0-9]|x|X))|(\\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\\d{3}))$"; boolean valid=Pattern.matches(myRegExpIDCardNo,certificateNo)||(certificateNo.length() == 17 && Pattern.matches(myRegExpIDCardNo,certificateNo.substring(0,15))); if(!valid){ resultDTO.setStatueMessage("证件号码不规范!"); return resultDTO; } int idxSexStart = 16; int birthYearSpan = 4; //如果是15位的证件号码 if(certificateNo.length() == 15) { idxSexStart = 14; birthYearSpan = 2; } //性别 String idxSexStr = certificateNo.substring(idxSexStart, idxSexStart + 1); int idxSex = Integer.parseInt(idxSexStr) % 2; String sex = (idxSex == 1) ? "M" : "F"; resultDTO.setSex(sex); //出生日期 String year = (birthYearSpan == 2 ? "19" : "") + certificateNo.substring(6, 6 + birthYearSpan); String month = certificateNo.substring(6 + birthYearSpan, 6 + birthYearSpan + 2); String day = certificateNo.substring(8 + birthYearSpan, 8 + birthYearSpan + 2); String birthday = year + '-' + month + '-' + day; resultDTO.setBirthday(birthday); //年龄 Calendar certificateCal = Calendar.getInstance(); Calendar currentTimeCal = Calendar.getInstance(); certificateCal.set(Integer.parseInt(year), Integer.parseInt(month)-1, Integer.parseInt(day)); int yearAge = (currentTimeCal.get(currentTimeCal.YEAR)) - (certificateCal.get(certificateCal.YEAR)); certificateCal.set(currentTimeCal.get(Calendar.YEAR), Integer.parseInt(month)-1, Integer.parseInt(day)); int monthFloor = (currentTimeCal.before(certificateCal) ? 1 : 0); resultDTO.setAge(yearAge - monthFloor); return resultDTO; } } |
ResultDTO.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 |
package com.bijian.study; public class ResultDTO { private String statueMessage; private String sex; private String birthday; private int age; public String getStatueMessage() { return statueMessage; } public void setStatueMessage(String statueMessage) { this.statueMessage = statueMessage; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { String res = ""; if(this.statueMessage != null) { res += this.statueMessage; }else { res += "sex:" + this.sex + ",birthday:" + this.birthday + ",age:" + this.age; } return res; } } |
CertificateNoTest.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 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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
package com.bijian.test; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import com.bijian.study.CertificateNo; import com.bijian.study.ResultDTO; /** * 说明: * 1.身份证信息完全是测试时随便写的,如有雷同,纯属巧合 * 2.写此测试案例的日期是2015-02-08,有测生日当天及前后的案例,后续再运行需更改 */ public class CertificateNoTest { private CertificateNo certificateNo; private ResultDTO resultDTO; @Before public void setUp() throws Exception { certificateNo = new CertificateNo(); } @Test public void test_abnormality_certificateNo_of_18_digit_430522199812623535() { resultDTO = certificateNo.parseCertificateNo("430522199812623535"); Assert.assertNotNull(resultDTO); Assert.assertEquals("证件号码不规范!", resultDTO.getStatueMessage()); } @Test public void test_abnormality_certificateNo_of_18_digit_430522198813013210() { resultDTO = certificateNo.parseCertificateNo("430522198813013210"); Assert.assertNotNull(resultDTO); Assert.assertEquals("证件号码不规范!", resultDTO.getStatueMessage()); } @Test public void test_normality_certificateNo_of_18_digit_430522199812101515() { resultDTO = certificateNo.parseCertificateNo("430522199812101515"); Assert.assertNotNull(resultDTO); Assert.assertEquals("M", resultDTO.getSex()); Assert.assertEquals("1998-12-10", resultDTO.getBirthday()); Assert.assertEquals(16, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_18_digit_430522199812101595() { resultDTO = certificateNo.parseCertificateNo("430522199812101595"); Assert.assertNotNull(resultDTO); Assert.assertEquals("M", resultDTO.getSex()); Assert.assertEquals("1998-12-10", resultDTO.getBirthday()); Assert.assertEquals(16, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_18_digit_430522199812101585() { resultDTO = certificateNo.parseCertificateNo("430522199812101585"); Assert.assertNotNull(resultDTO); Assert.assertEquals("F", resultDTO.getSex()); Assert.assertEquals("1998-12-10", resultDTO.getBirthday()); Assert.assertEquals(16, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_18_digit_430522198810103212() { resultDTO = certificateNo.parseCertificateNo("430522198810103212"); Assert.assertNotNull(resultDTO); Assert.assertEquals("M", resultDTO.getSex()); Assert.assertEquals("1988-10-10", resultDTO.getBirthday()); Assert.assertEquals(26, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_18_digit_before_birthday() { //测试的时间是2015-02-08,表明昨天刚过生日 resultDTO = certificateNo.parseCertificateNo("430522198802073210"); Assert.assertNotNull(resultDTO); Assert.assertEquals("M", resultDTO.getSex()); Assert.assertEquals("1988-02-07", resultDTO.getBirthday()); Assert.assertEquals(27, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_18_digit_birthday() { //测试的时间是2015-02-08,表明当天正好生日 resultDTO = certificateNo.parseCertificateNo("430522198802083210"); Assert.assertNotNull(resultDTO); Assert.assertEquals("M", resultDTO.getSex()); Assert.assertEquals("1988-02-08", resultDTO.getBirthday()); Assert.assertEquals(27, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_18_digit_after_birthday() { //测试的时间是2015-02-08,表明第二天才过生日 resultDTO = certificateNo.parseCertificateNo("430522198802093210"); Assert.assertNotNull(resultDTO); Assert.assertEquals("M", resultDTO.getSex()); Assert.assertEquals("1988-02-09", resultDTO.getBirthday()); Assert.assertEquals(26, resultDTO.getAge()); } @Test public void test_abnormality_certificateNo_of_15_digit_130503671401001() { resultDTO = certificateNo.parseCertificateNo("130503671401001"); Assert.assertNotNull(resultDTO); Assert.assertEquals("证件号码不规范!", resultDTO.getStatueMessage()); } @Test public void test_normality_certificateNo_of_15_digit_430522760201356() { resultDTO = certificateNo.parseCertificateNo("430522760201356"); Assert.assertNotNull(resultDTO); Assert.assertEquals("F", resultDTO.getSex()); Assert.assertEquals("1976-02-01", resultDTO.getBirthday()); Assert.assertEquals(39, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_15_digit_130503670401001() { resultDTO = certificateNo.parseCertificateNo("130503670401001"); Assert.assertNotNull(resultDTO); Assert.assertEquals("M", resultDTO.getSex()); Assert.assertEquals("1967-04-01", resultDTO.getBirthday()); Assert.assertEquals(47, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_15_digit_370802940221002() { resultDTO = certificateNo.parseCertificateNo("370802940221002"); Assert.assertNotNull(resultDTO); Assert.assertEquals("F", resultDTO.getSex()); Assert.assertEquals("1994-02-21", resultDTO.getBirthday()); Assert.assertEquals(20, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_15_digit_370802941031331() { resultDTO = certificateNo.parseCertificateNo("370802941031331"); Assert.assertNotNull(resultDTO); Assert.assertEquals("M", resultDTO.getSex()); Assert.assertEquals("1994-10-31", resultDTO.getBirthday()); Assert.assertEquals(20, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_15_digit_before_birthday() { //测试的时间是2015-02-08,表明昨天刚过生日 resultDTO = certificateNo.parseCertificateNo("370802940207331"); Assert.assertNotNull(resultDTO); Assert.assertEquals("M", resultDTO.getSex()); Assert.assertEquals("1994-02-07", resultDTO.getBirthday()); Assert.assertEquals(21, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_15_digit_birthday() { //测试的时间是2015-02-08,表明当天正好生日 resultDTO = certificateNo.parseCertificateNo("370802940208331"); Assert.assertNotNull(resultDTO); Assert.assertEquals("M", resultDTO.getSex()); Assert.assertEquals("1994-02-08", resultDTO.getBirthday()); Assert.assertEquals(21, resultDTO.getAge()); } @Test public void test_normality_certificateNo_of_15_digit_after_birthday() { //测试的时间是2015-02-08,表明第二天才过生日 resultDTO = certificateNo.parseCertificateNo("370802940209331"); Assert.assertNotNull(resultDTO); Assert.assertEquals("M", resultDTO.getSex()); Assert.assertEquals("1994-02-09", resultDTO.getBirthday()); Assert.assertEquals(20, resultDTO.getAge()); } } |
from:https://www.iteye.com/blog/bijian1013-2184409
View Details