随机密码生成器
下午花了点时间用C#做了个随机密码生成器,发给运维的同事用,发现他那里用不了,原来是没装.net framework。一个几十k的小程序,还要装一个几十M的.net framework,真是很悲催。所以我又用go写了一个,顺便当作go的练习题了。非常感谢谢golang-china群里的各位大侠,在我完成这个程序过程中一直很耐心的充当人肉语法文档,其实没有系统的学习就到群里问是很不好的习惯,但是这个程序实在急用,下不为例了。
2011年5月7日:补全密码表
下面是go实现的代码:
package main import ("fmt"; "flag"; "time"; "rand") var pwdCount *int = flag.Int("n", 10, "How many password") var pwdLength *int = flag.Int("l", 20, "How long a password") var pwdCodes = [...]byte{ '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', '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', '`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '[', ']', '\',';', ''', ',', '.', '/', '{', '}', '|', ':', '"', '<', '>', '?', } func main() { flag.Parse() var r *rand.Rand = rand.New(rand.NewSource(time.Nanoseconds())) for i := 0; i < *pwdCount; i ++ { var pwd []byte = make([]byte, *pwdLength) for j := 0; j < *pwdLength; j ++ { index := r.Int() % len(pwdCodes) pwd[j] = pwdCodes[index] } fmt.Printf("%sn", string(pwd)) } }
顺便贴上C#实现的代码做对比:
using System; using System.Text; using System.Collections.Generic; namespace Password { class Program { static void Main(string[] args) { int length = 20; int count = 10; if (args.Length > 0) length = int.Parse(args[0]); if (args.Length > 1) count = int.Parse(args[1]); Random random = new Random(); for (int j = 0; j < count; j++) { StringBuilder password = new StringBuilder(); for (int i = 0; i < length; i++) { password.Append( Codes[random.Next(0, 10000) % Codes.Length] ); } Console.WriteLine(password.ToString()); } #if DEBUG Console.ReadKey(true); #endif } static char[] Codes = new char[]{ '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', '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', '`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '[', ']', ';', ''', ',', '.', '/', '{', '}', '|', ':', '"', '<', '>', '?' }; } }