微薄短地址的实现-python 转

java-苦苦甜甜

http://www.guokr.com/question/297490/ 这个url 经过短地址算法后就成了 http://t.cn/zWCRWpM

``````#!/usr/bin/env python
#coding=utf-8
import hashlib

chars = (
"a","b","c","d","e","f","g","h",
"i","j","k","l","m","n","o","p",
"q","r","s","t","u","v","w","x",
"y","z","0","1","2","3","4","5",
"6","7","8","9","A","B","C","D",
"E","F","G","H","I","J","K","L",
"M","N","O","P","Q","R","S","T",
"U","V","W","X","Y","Z",)

def shorten(origin):
key = "fuck-gfw.ooxx.shorten"
#对传入网址进行MD5加密
hex = hashlib.md5(key + origin).hexdigest()
res = [0 for i in range(4)]
for i in range(4):
#把加密字符按照8位一组16进制与0x3FFFFFFF进行位与运算
hexint = 0x3FFFFFFF & int("0x" + hex[i * 8: i*8+8], 16)
outChars = ""
for j in range(7):
#把得到的值与0x0000003D进行位与运算，取得字符数组chars索引
index = 0x0000003D & hexint
#把取得的字符相加
outChars += chars[index]
#每次循环按位右移5位
hexint = hexint >> 5
#把字符串存入对应索引的输出数组
res[i] = outChars
return res

``shorten(url) 这个方法会返回一个包含4个字符串的地址``

``````
['3IJJ7va', '6ZZfUfa', 'YNJniia', 'UFVRzea']
``````

评论(1)

qq_42156420
2018/05/28
0
0
《Python Cookbook》第三版中文版发布

2015/12/29
7.1K
65

2016/02/21
379
4
[原]我为什么要学习python

2012/11/14
156
1
《Python Cookbook》第三版中文版

2015/01/07
58.7K
42

Jenkins World 贡献者峰会及专家答疑展位

Jenkins中文社区
20分钟前
6
0

liululee
34分钟前
6
0
OSChina 周二乱弹 —— 我等饭呢，你是不是来错食堂了？

Osc乱弹歌单（2019）请戳（这里） 【今日歌曲】 @ 自行车丢了：给主编推荐首歌 《クリスマスの夜》- 岡村孝子 手机党少年们想听歌，请使劲儿戳（这里） @烽火燎原 ：国庆快来，我需要长假！ ...

329
8

Devtools 介绍 SpringBoot 提供了热部署的功能，那啥是热部署累？SpringBoot官方是这样说的：只要类路径上的文件发生更改，就会自动重新启动应用程序。在IDE中工作时，这可能是一个有用的功能...

5
0
CSS--列表

wytao1995

10
0