├── .gitignore ├── README.md ├── cert ├── client │ ├── cli.cnf │ └── create_cli_crt.sh └── serv │ ├── create_serv_crt.sh │ ├── root.cnf │ └── serv.cnf ├── china_ipv4 ├── dnsmasq-china-list ├── go_proxy ├── go_proxy.json └── src ├── go_proxy ├── go_client │ ├── tcp_client.go │ └── udp_client.go ├── go_server │ ├── tcp_server.go │ └── udp_server.go ├── local_proxy │ ├── connection_handler.go │ ├── http_proxy_handler.go │ ├── local_proxy.go │ └── socks5_handler.go ├── main.go ├── test.go └── util │ ├── config.go │ ├── connection_util.go │ ├── crypt.go │ ├── dns_util.go │ └── logger.go └── golang.org └── x └── crypto ├── acme ├── acme.go ├── acme_test.go ├── autocert │ ├── autocert.go │ ├── autocert_test.go │ ├── cache.go │ ├── cache_test.go │ ├── example_test.go │ ├── listener.go │ ├── renewal.go │ └── renewal_test.go ├── jws.go ├── jws_test.go ├── types.go └── types_test.go ├── bcrypt ├── base64.go ├── bcrypt.go └── bcrypt_test.go ├── blake2b ├── blake2b.go ├── blake2bAVX2_amd64.go ├── blake2bAVX2_amd64.s ├── blake2b_amd64.go ├── blake2b_amd64.s ├── blake2b_generic.go ├── blake2b_ref.go ├── blake2b_test.go ├── blake2x.go └── register.go ├── blake2s ├── blake2s.go ├── blake2s_386.go ├── blake2s_386.s ├── blake2s_amd64.go ├── blake2s_amd64.s ├── blake2s_generic.go ├── blake2s_ref.go ├── blake2s_test.go ├── blake2x.go └── register.go ├── blowfish ├── block.go ├── blowfish_test.go ├── cipher.go └── const.go ├── bn256 ├── bn256.go ├── bn256_test.go ├── constants.go ├── curve.go ├── example_test.go ├── gfp12.go ├── gfp2.go ├── gfp6.go ├── optate.go └── twist.go ├── cast5 ├── cast5.go └── cast5_test.go ├── chacha20poly1305 ├── chacha20poly1305.go ├── chacha20poly1305_amd64.go ├── chacha20poly1305_amd64.s ├── chacha20poly1305_generic.go ├── chacha20poly1305_noasm.go ├── chacha20poly1305_test.go ├── chacha20poly1305_vectors_test.go └── internal │ └── chacha20 │ ├── chacha_generic.go │ └── chacha_test.go ├── cryptobyte ├── asn1.go ├── asn1 │ └── asn1.go ├── asn1_test.go ├── builder.go ├── cryptobyte_test.go ├── example_test.go └── string.go ├── curve25519 ├── const_amd64.h ├── const_amd64.s ├── cswap_amd64.s ├── curve25519.go ├── curve25519_test.go ├── doc.go ├── freeze_amd64.s ├── ladderstep_amd64.s ├── mont25519_amd64.go ├── mul_amd64.s └── square_amd64.s ├── ed25519 ├── ed25519.go ├── ed25519_test.go ├── internal │ └── edwards25519 │ │ ├── const.go │ │ └── edwards25519.go └── testdata │ └── sign.input.gz ├── hkdf ├── example_test.go ├── hkdf.go └── hkdf_test.go ├── md4 ├── example_test.go ├── md4.go ├── md4_test.go └── md4block.go ├── nacl ├── auth │ ├── auth.go │ ├── auth_test.go │ └── example_test.go ├── box │ ├── box.go │ ├── box_test.go │ └── example_test.go └── secretbox │ ├── example_test.go │ ├── secretbox.go │ └── secretbox_test.go ├── ocsp ├── ocsp.go └── ocsp_test.go ├── openpgp ├── armor │ ├── armor.go │ ├── armor_test.go │ └── encode.go ├── canonical_text.go ├── canonical_text_test.go ├── clearsign │ ├── clearsign.go │ └── clearsign_test.go ├── elgamal │ ├── elgamal.go │ └── elgamal_test.go ├── errors │ └── errors.go ├── keys.go ├── keys_test.go ├── packet │ ├── compressed.go │ ├── compressed_test.go │ ├── config.go │ ├── encrypted_key.go │ ├── encrypted_key_test.go │ ├── literal.go │ ├── ocfb.go │ ├── ocfb_test.go │ ├── one_pass_signature.go │ ├── opaque.go │ ├── opaque_test.go │ ├── packet.go │ ├── packet_test.go │ ├── private_key.go │ ├── private_key_test.go │ ├── public_key.go │ ├── public_key_test.go │ ├── public_key_v3.go │ ├── public_key_v3_test.go │ ├── reader.go │ ├── signature.go │ ├── signature_test.go │ ├── signature_v3.go │ ├── signature_v3_test.go │ ├── symmetric_key_encrypted.go │ ├── symmetric_key_encrypted_test.go │ ├── symmetrically_encrypted.go │ ├── symmetrically_encrypted_test.go │ ├── userattribute.go │ ├── userattribute_test.go │ ├── userid.go │ └── userid_test.go ├── read.go ├── read_test.go ├── s2k │ ├── s2k.go │ └── s2k_test.go ├── write.go └── write_test.go ├── otr ├── libotr_test_helper.c ├── otr.go ├── otr_test.go └── smp.go ├── pbkdf2 ├── pbkdf2.go └── pbkdf2_test.go ├── pkcs12 ├── bmp-string.go ├── bmp-string_test.go ├── crypto.go ├── crypto_test.go ├── errors.go ├── internal │ └── rc2 │ │ ├── bench_test.go │ │ ├── rc2.go │ │ └── rc2_test.go ├── mac.go ├── mac_test.go ├── pbkdf.go ├── pbkdf_test.go ├── pkcs12.go ├── pkcs12_test.go └── safebags.go ├── poly1305 ├── poly1305.go ├── poly1305_test.go ├── sum_amd64.go ├── sum_amd64.s ├── sum_arm.go ├── sum_arm.s └── sum_ref.go ├── ripemd160 ├── ripemd160.go ├── ripemd160_test.go └── ripemd160block.go ├── salsa20 ├── salsa │ ├── hsalsa20.go │ ├── salsa2020_amd64.s │ ├── salsa208.go │ ├── salsa20_amd64.go │ ├── salsa20_ref.go │ └── salsa_test.go ├── salsa20.go └── salsa20_test.go ├── scrypt ├── example_test.go ├── scrypt.go └── scrypt_test.go ├── sha3 ├── doc.go ├── hashes.go ├── keccakf.go ├── keccakf_amd64.go ├── keccakf_amd64.s ├── register.go ├── sha3.go ├── sha3_test.go ├── shake.go ├── testdata │ └── keccakKats.json.deflate ├── xor.go ├── xor_generic.go └── xor_unaligned.go ├── ssh ├── agent │ ├── client.go │ ├── client_test.go │ ├── example_test.go │ ├── forward.go │ ├── keyring.go │ ├── keyring_test.go │ ├── server.go │ ├── server_test.go │ └── testdata_test.go ├── benchmark_test.go ├── buffer.go ├── buffer_test.go ├── certs.go ├── certs_test.go ├── channel.go ├── cipher.go ├── cipher_test.go ├── client.go ├── client_auth.go ├── client_auth_test.go ├── client_test.go ├── common.go ├── connection.go ├── doc.go ├── example_test.go ├── handshake.go ├── handshake_test.go ├── kex.go ├── kex_test.go ├── keys.go ├── keys_test.go ├── knownhosts │ ├── knownhosts.go │ └── knownhosts_test.go ├── mac.go ├── mempipe_test.go ├── messages.go ├── messages_test.go ├── mux.go ├── mux_test.go ├── server.go ├── session.go ├── session_test.go ├── streamlocal.go ├── tcpip.go ├── tcpip_test.go ├── terminal │ ├── terminal.go │ ├── terminal_test.go │ ├── util.go │ ├── util_bsd.go │ ├── util_linux.go │ ├── util_plan9.go │ ├── util_solaris.go │ └── util_windows.go ├── test │ ├── agent_unix_test.go │ ├── cert_test.go │ ├── dial_unix_test.go │ ├── doc.go │ ├── forward_unix_test.go │ ├── session_test.go │ ├── test_unix_test.go │ └── testdata_test.go ├── testdata │ ├── doc.go │ └── keys.go ├── testdata_test.go ├── transport.go └── transport_test.go ├── tea ├── cipher.go └── tea_test.go ├── twofish ├── twofish.go └── twofish_test.go ├── xtea ├── block.go ├── cipher.go └── xtea_test.go └── xts ├── xts.go └── xts_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | log 3 | pkg 4 | 5 | 6 | -------------------------------------------------------------------------------- /cert/client/cli.cnf: -------------------------------------------------------------------------------- 1 | [ req ] 2 | default_bits = 2048 3 | prompt = no 4 | distinguished_name = dn 5 | 6 | [ dn ] 7 | C = CN 8 | ST = CN 9 | L = CN 10 | O = miku_fan 11 | OU = miku_fan 12 | 13 | 14 | 15 | 16 | [ v3_ext ] 17 | extendedKeyUsage=clientAuth 18 | 19 | -------------------------------------------------------------------------------- /cert/client/create_cli_crt.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | if [ "$#" -eq 0 ];then 5 | openssl genrsa -out client.key 2048 6 | 7 | openssl req -x509 -new -nodes -key client.key -days 3650 -out client.crt -config cli.cnf -extensions v3_ext 8 | 9 | exit 0 10 | fi 11 | 12 | re='^[0-9]+$' 13 | if ! [[ $1 =~ $re ]] ; then 14 | echo "param 1 must a number" 15 | exit 1 16 | fi 17 | 18 | for i in `seq 1 1 $1`;do 19 | 20 | openssl genrsa -out client_$i.key 2048 21 | 22 | openssl req -x509 -new -nodes -key client_$i.key -days 3650 -out client_$i.crt -config cli.cnf -extensions v3_ext 23 | 24 | 25 | done 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /cert/serv/create_serv_crt.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | echo "create root private key" 5 | echo 6 | openssl genrsa -out root.key 2048 7 | 8 | echo "create root cert" 9 | echo 10 | openssl req -x509 -new -nodes -key root.key -days 3650 -out root.crt -config root.cnf 11 | 12 | echo "create server private key" 13 | echo 14 | openssl genrsa -out server.key 2048 15 | 16 | echo "create server sign request" 17 | echo 18 | openssl req -new -key server.key -config serv.cnf -extensions v3_ext -out server.csr 19 | 20 | echo "sign" 21 | echo 22 | openssl x509 -req -days 3650 -in server.csr -CA root.crt -CAkey root.key -out server.crt -CAcreateserial -extensions v3_ext -extfile serv.cnf 23 | 24 | rm server.csr 25 | rm root.srl 26 | 27 | 28 | -------------------------------------------------------------------------------- /cert/serv/root.cnf: -------------------------------------------------------------------------------- 1 | [ req ] 2 | default_bits = 2048 3 | prompt = no 4 | distinguished_name = dn 5 | 6 | [ dn ] 7 | C = HK 8 | ST = HK 9 | L = HK 10 | O = root 11 | OU = root 12 | 13 | 14 | -------------------------------------------------------------------------------- /cert/serv/serv.cnf: -------------------------------------------------------------------------------- 1 | [ req ] 2 | default_bits = 2048 3 | prompt = no 4 | req_extensions = req_ext 5 | distinguished_name = dn 6 | 7 | [ dn ] 8 | C = HK 9 | ST = HK 10 | L = HK 11 | O = miku_fan 12 | OU = miku_fan 13 | 14 | 15 | [ req_ext ] 16 | subjectAltName = @alt_names 17 | 18 | [ alt_names ] 19 | DNS.1 = ydx.com 20 | DNS.2= cn1.vxtrans.link 21 | DNS.3= cn2.vxtrans.link 22 | IP.1 = 47.244.137.231 23 | 24 | [ v3_ext ] 25 | extendedKeyUsage=serverAuth 26 | subjectAltName=@alt_names 27 | -------------------------------------------------------------------------------- /go_proxy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qq906907952/go_proxy/d750932506068316b6031e68699c160e87361b59/go_proxy -------------------------------------------------------------------------------- /go_proxy.json: -------------------------------------------------------------------------------- 1 | { 2 | 3 | "Client": { 4 | "Turn":false, 5 | "Local_proxy": true, 6 | "Ipv6": false, 7 | "Local_addr": "0.0.0.0", 8 | "Local_port": 3939, 9 | "Server_addr": "ydx.com", 10 | "Server_port":44444, 11 | "Enc_method": "chacha20", 12 | "Password": " miku chann wa yichibann kawaii ", 13 | "Dns_addr": "8.8.8.8", 14 | "Dns_port": 53, 15 | "Dns_req_proto": "tcp", 16 | "Domain_cache_time":3600, 17 | "Tls":{ 18 | "Turn":true, 19 | "Tcp_encrypt":true, 20 | "Root_cert_path":"cert/serv/root.crt", 21 | "Client_cert":[ 22 | { 23 | "Cert":"cert/client/client_2.crt", 24 | "Private_key":"cert/client/client_2.key" 25 | }, 26 | { 27 | "Cert":"cert/client/client_3.crt", 28 | "Private_key":"cert/client/client_3.key" 29 | }, 30 | { 31 | "Cert":"cert/client/client_1.crt", 32 | "Private_key":"cert/client/client_1.key" 33 | } 34 | 35 | ] 36 | } 37 | }, 38 | 39 | "Server": { 40 | "Turn": false, 41 | 42 | "Port": [ 43 | { 44 | "Tls": { 45 | "Turn":false, 46 | "Tcp_encrypt":false, 47 | "Server_cert_path":"cert/serv/server.crt", 48 | "Server_private_key_path":"cert/serv/server.key", 49 | "Client_cert_paths":[ 50 | "cert/client/client.crt" 51 | ] 52 | }, 53 | "Listen_port": 443, 54 | "Enc_method": "aes-256-cfb", 55 | "Password": " miku chann wa yichibann kawaii " 56 | } 57 | ] 58 | }, 59 | 60 | "Ulimit": 1024000, 61 | "Connection_log": false, 62 | "Udp_timeout": 30 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/go_proxy/go_client/tcp_client.go: -------------------------------------------------------------------------------- 1 | package go_client 2 | 3 | import ( 4 | "net" 5 | "go_proxy/util" 6 | "encoding/binary" 7 | "fmt" 8 | "log" 9 | "time" 10 | ) 11 | 12 | func Start_TCPclient() { 13 | defer util.Group.Done() 14 | 15 | tcp_crypt := util.Get_crypt(util.Config.Client.Enc_method, util.Config.Client.Password) 16 | if util.Config.Client.Tls.Turn && !util.Config.Client.Tls.Tcp_encrypt { 17 | tcp_crypt = util.Get_none_crypt() 18 | } 19 | 20 | tcp_listen, err := net.ListenTCP("tcp", &net.TCPAddr{ 21 | IP: net.ParseIP(util.Config.Client.Local_addr), 22 | Port: util.Config.Client.Local_port, 23 | Zone: "", 24 | }) 25 | if err != nil { 26 | log.Fatal(err) 27 | 28 | } 29 | _l := fmt.Sprintf("tcp client listen on %s:%d,remote server %s:%d \r\ncrypt method:%s", 30 | util.Config.Client.Local_addr, 31 | util.Config.Client.Local_port, 32 | util.Config.Client.Server_addr, 33 | util.Config.Client.Server_port, 34 | tcp_crypt.String()) 35 | 36 | util.Print_log(_l) 37 | fmt.Println(_l) 38 | 39 | for { 40 | tcp_con, err := tcp_listen.AcceptTCP() 41 | if err != nil { 42 | util.Print_log("tcp accept error " + err.Error()) 43 | continue 44 | } 45 | 46 | go handle_con(tcp_con, tcp_crypt) 47 | 48 | } 49 | } 50 | 51 | func handle_con(con *net.TCPConn, crypt util.Crypt_interface) { 52 | 53 | defer func() { 54 | util.Handle_panic() 55 | util.Close_tcp(con) 56 | 57 | }() 58 | 59 | con.SetKeepAlive(true) 60 | con.SetKeepAlivePeriod(10 * time.Second) 61 | addr, err := util.Get_tcp_origin_dest(con) 62 | if err != nil { 63 | util.Print_log("tcp can not read the origin dest:" + err.Error()) 64 | return 65 | } 66 | 67 | dest := addr.Multiaddr[2:8] 68 | 69 | if util.Config.Connection_log { 70 | _dest := &net.TCPAddr{ 71 | IP: dest[2:], 72 | Port: int(binary.BigEndian.Uint16(dest[:2])), 73 | } 74 | util.Print_log("connection log:%s connect to %s", con.RemoteAddr().String(), _dest.String()) 75 | } 76 | 77 | //connect to the proxy server 78 | remote, raw_socket, err := util.Connect_to_server(crypt, util.Tcp_conn, int(binary.BigEndian.Uint16(dest[:2])), dest[2:]) 79 | if err != nil { 80 | util.Print_log("connection to remote error:" + err.Error()) 81 | return 82 | } 83 | 84 | defer util.Close_tcp(raw_socket) 85 | 86 | util.Connection_loop(con, remote, crypt) 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/go_proxy/local_proxy/connection_handler.go: -------------------------------------------------------------------------------- 1 | package local_proxy 2 | 3 | import ( 4 | "go_proxy/util" 5 | "net" 6 | "io" 7 | "fmt" 8 | "time" 9 | 10 | ) 11 | 12 | func handle_connection(local *net.TCPConn, ip *net.IPAddr, dest_port int, prefix_data []byte, ack_data []byte, is_cn bool) { 13 | var remote net.Conn 14 | var err error 15 | 16 | if is_cn { 17 | 18 | remote, err = net.DialTCP("tcp", nil, &net.TCPAddr{ 19 | IP: ip.IP, 20 | Port: dest_port, 21 | Zone: "", 22 | }) 23 | 24 | if err != nil { 25 | util.Print_log(fmt.Sprintf("can not connect to %s:%s",ip.String(),err.Error())) 26 | return 27 | } 28 | remote.(*net.TCPConn).SetKeepAlive(true) 29 | remote.(*net.TCPConn).SetKeepAlivePeriod(10*time.Second) 30 | defer util.Close_tcp(remote.(*net.TCPConn)) 31 | } else { 32 | var raw_socket *net.TCPConn 33 | remote,raw_socket, err = util.Connect_to_server(tcp_crypt, util.Tcp_conn,dest_port, ip.IP) 34 | 35 | if err != nil { 36 | util.Print_log("can not connect to server : " + err.Error()) 37 | return 38 | } 39 | defer util.Close_tcp(raw_socket) 40 | } 41 | 42 | 43 | 44 | if prefix_data != nil { 45 | if is_cn { 46 | if _, werr := remote.Write(prefix_data); werr != nil { 47 | return 48 | } 49 | } else { 50 | 51 | err := tcp_crypt.Write(remote, prefix_data) 52 | if err != nil { 53 | return 54 | } 55 | } 56 | } 57 | 58 | if ack_data != nil { 59 | if _, werr := local.Write(ack_data); werr != nil { 60 | return 61 | } 62 | } 63 | 64 | //loop 65 | if is_cn { 66 | 67 | go func() { 68 | defer util.Close_tcp(local) 69 | defer util.Close_tcp(remote.(*net.TCPConn)) 70 | io.Copy(local, remote) 71 | }() 72 | 73 | io.Copy(remote, local) 74 | 75 | 76 | } else { 77 | 78 | util.Connection_loop(local, remote, tcp_crypt) 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/go_proxy/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "go_proxy/util" 5 | "go_proxy/go_server" 6 | "go_proxy/local_proxy" 7 | "syscall" 8 | "go_proxy/go_client" 9 | "crypto/tls" 10 | "crypto/x509" 11 | "io/ioutil" 12 | "log" 13 | ) 14 | 15 | func main() { 16 | 17 | syscall.Setrlimit(syscall.RLIMIT_NOFILE, &syscall.Rlimit{ 18 | Cur: util.Config.Ulimit, 19 | Max: util.Config.Ulimit, 20 | }) 21 | 22 | if util.Config.Client.Turn { 23 | 24 | util.Group.Add(2) 25 | go go_client.Start_TCPclient() 26 | go go_client.Start_UDPclien() 27 | 28 | } 29 | 30 | if util.Config.Client.Local_proxy { 31 | 32 | util.Group.Add(1) 33 | go local_proxy.Start_local_proxy_client() 34 | } 35 | 36 | if util.Config.Server.Turn { 37 | 38 | for _, port := range util.Config.Server.Port { 39 | if !port.Tls.Turn && port.Enc_method == "None" { 40 | log.Fatal("enc method must not none when tls disable") 41 | } 42 | var tls_conf *tls.Config 43 | tcp_crypt:=util.Get_crypt(port.Enc_method, port.Password) 44 | if port.Tls.Turn { 45 | 46 | if !port.Tls.Tcp_encrypt{ 47 | tcp_crypt=util.Get_none_crypt() 48 | } 49 | 50 | if len(port.Tls.Client_cert_paths) == 0 { 51 | log.Fatal("client cert paths list can not null") 52 | } 53 | 54 | cert, err := tls.LoadX509KeyPair(port.Tls.Server_cert_path, port.Tls.Server_private_key_path) 55 | if err != nil { 56 | log.Fatal("load server cert and private key error:" + err.Error()) 57 | } 58 | cli_cert := x509.NewCertPool() 59 | for _, v := range port.Tls.Client_cert_paths { 60 | b, err := ioutil.ReadFile(v) 61 | if err != nil { 62 | log.Fatal("load client cert fail : " + err.Error()) 63 | } 64 | cli_cert.AppendCertsFromPEM(b) 65 | 66 | } 67 | tls_conf = &tls.Config{ 68 | 69 | Certificates: []tls.Certificate{cert}, 70 | ClientAuth: tls.RequireAndVerifyClientCert, 71 | ClientCAs: cli_cert, 72 | } 73 | } 74 | util.Group.Add(2) 75 | go go_server.Start_TCPserver(port.Listen_port, tcp_crypt, tls_conf) 76 | go go_server.Start_UDPserver(port.Listen_port, util.Get_crypt(port.Enc_method, port.Password)) 77 | 78 | } 79 | 80 | } 81 | 82 | util.Group.Wait() 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/go_proxy/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | } 5 | -------------------------------------------------------------------------------- /src/go_proxy/util/logger.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "runtime/debug" 7 | "fmt" 8 | "time" 9 | ) 10 | 11 | 12 | var Log = log.Logger{} 13 | 14 | 15 | func Print_log(log string,v... interface{}){ 16 | 17 | file, err := os.OpenFile("go_proxy.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) 18 | if err!=nil{ 19 | fmt.Println("can not open log file:"+err.Error()) 20 | fmt.Println("==============================") 21 | return 22 | } 23 | Log.SetOutput(file) 24 | Log.Printf(time.Now().Format(time.RFC3339)+" "+log,v...) 25 | } 26 | 27 | 28 | func Handle_panic() { 29 | err := recover() 30 | 31 | if err != nil { 32 | Log.Print("panic : ") 33 | Log.Println(err) 34 | 35 | debug.PrintStack() 36 | fmt.Println("==============================") 37 | 38 | 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/acme/autocert/cache_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package autocert 6 | 7 | import ( 8 | "context" 9 | "io/ioutil" 10 | "os" 11 | "path/filepath" 12 | "reflect" 13 | "testing" 14 | ) 15 | 16 | // make sure DirCache satisfies Cache interface 17 | var _ Cache = DirCache("/") 18 | 19 | func TestDirCache(t *testing.T) { 20 | dir, err := ioutil.TempDir("", "autocert") 21 | if err != nil { 22 | t.Fatal(err) 23 | } 24 | defer os.RemoveAll(dir) 25 | dir = filepath.Join(dir, "certs") // a nonexistent dir 26 | cache := DirCache(dir) 27 | ctx := context.Background() 28 | 29 | // test cache miss 30 | if _, err := cache.Get(ctx, "nonexistent"); err != ErrCacheMiss { 31 | t.Errorf("get: %v; want ErrCacheMiss", err) 32 | } 33 | 34 | // test put/get 35 | b1 := []byte{1} 36 | if err := cache.Put(ctx, "dummy", b1); err != nil { 37 | t.Fatalf("put: %v", err) 38 | } 39 | b2, err := cache.Get(ctx, "dummy") 40 | if err != nil { 41 | t.Fatalf("get: %v", err) 42 | } 43 | if !reflect.DeepEqual(b1, b2) { 44 | t.Errorf("b1 = %v; want %v", b1, b2) 45 | } 46 | name := filepath.Join(dir, "dummy") 47 | if _, err := os.Stat(name); err != nil { 48 | t.Error(err) 49 | } 50 | 51 | // test delete 52 | if err := cache.Delete(ctx, "dummy"); err != nil { 53 | t.Fatalf("delete: %v", err) 54 | } 55 | if _, err := cache.Get(ctx, "dummy"); err != ErrCacheMiss { 56 | t.Errorf("get: %v; want ErrCacheMiss", err) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/acme/autocert/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package autocert_test 6 | 7 | import ( 8 | "crypto/tls" 9 | "fmt" 10 | "log" 11 | "net/http" 12 | 13 | "golang.org/x/crypto/acme/autocert" 14 | ) 15 | 16 | func ExampleNewListener() { 17 | mux := http.NewServeMux() 18 | mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 19 | fmt.Fprintf(w, "Hello, TLS user! Your config: %+v", r.TLS) 20 | }) 21 | log.Fatal(http.Serve(autocert.NewListener("example.com"), mux)) 22 | } 23 | 24 | func ExampleManager() { 25 | m := autocert.Manager{ 26 | Cache: autocert.DirCache("secret-dir"), 27 | Prompt: autocert.AcceptTOS, 28 | HostPolicy: autocert.HostWhitelist("example.org"), 29 | } 30 | s := &http.Server{ 31 | Addr: ":https", 32 | TLSConfig: &tls.Config{GetCertificate: m.GetCertificate}, 33 | } 34 | s.ListenAndServeTLS("", "") 35 | } 36 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/acme/types_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package acme 6 | 7 | import ( 8 | "errors" 9 | "net/http" 10 | "testing" 11 | "time" 12 | ) 13 | 14 | func TestRateLimit(t *testing.T) { 15 | now := time.Date(2017, 04, 27, 10, 0, 0, 0, time.UTC) 16 | f := timeNow 17 | defer func() { timeNow = f }() 18 | timeNow = func() time.Time { return now } 19 | 20 | h120, hTime := http.Header{}, http.Header{} 21 | h120.Set("Retry-After", "120") 22 | hTime.Set("Retry-After", "Tue Apr 27 11:00:00 2017") 23 | 24 | err1 := &Error{ 25 | ProblemType: "urn:ietf:params:acme:error:nolimit", 26 | Header: h120, 27 | } 28 | err2 := &Error{ 29 | ProblemType: "urn:ietf:params:acme:error:rateLimited", 30 | Header: h120, 31 | } 32 | err3 := &Error{ 33 | ProblemType: "urn:ietf:params:acme:error:rateLimited", 34 | Header: nil, 35 | } 36 | err4 := &Error{ 37 | ProblemType: "urn:ietf:params:acme:error:rateLimited", 38 | Header: hTime, 39 | } 40 | 41 | tt := []struct { 42 | err error 43 | res time.Duration 44 | ok bool 45 | }{ 46 | {nil, 0, false}, 47 | {errors.New("dummy"), 0, false}, 48 | {err1, 0, false}, 49 | {err2, 2 * time.Minute, true}, 50 | {err3, 0, true}, 51 | {err4, time.Hour, true}, 52 | } 53 | for i, test := range tt { 54 | res, ok := RateLimit(test.err) 55 | if ok != test.ok { 56 | t.Errorf("%d: RateLimit(%+v): ok = %v; want %v", i, test.err, ok, test.ok) 57 | continue 58 | } 59 | if res != test.res { 60 | t.Errorf("%d: RateLimit(%+v) = %v; want %v", i, test.err, res, test.res) 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/bcrypt/base64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package bcrypt 6 | 7 | import "encoding/base64" 8 | 9 | const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" 10 | 11 | var bcEncoding = base64.NewEncoding(alphabet) 12 | 13 | func base64Encode(src []byte) []byte { 14 | n := bcEncoding.EncodedLen(len(src)) 15 | dst := make([]byte, n) 16 | bcEncoding.Encode(dst, src) 17 | for dst[n-1] == '=' { 18 | n-- 19 | } 20 | return dst[:n] 21 | } 22 | 23 | func base64Decode(src []byte) ([]byte, error) { 24 | numOfEquals := 4 - (len(src) % 4) 25 | for i := 0; i < numOfEquals; i++ { 26 | src = append(src, '=') 27 | } 28 | 29 | dst := make([]byte, bcEncoding.DecodedLen(len(src))) 30 | n, err := bcEncoding.Decode(dst, src) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return dst[:n], nil 35 | } 36 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.7,amd64,!gccgo,!appengine 6 | 7 | package blake2b 8 | 9 | func init() { 10 | useAVX2 = supportsAVX2() 11 | useAVX = supportsAVX() 12 | useSSE4 = supportsSSE4() 13 | } 14 | 15 | //go:noescape 16 | func supportsSSE4() bool 17 | 18 | //go:noescape 19 | func supportsAVX() bool 20 | 21 | //go:noescape 22 | func supportsAVX2() bool 23 | 24 | //go:noescape 25 | func hashBlocksAVX2(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) 26 | 27 | //go:noescape 28 | func hashBlocksAVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) 29 | 30 | //go:noescape 31 | func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) 32 | 33 | func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { 34 | if useAVX2 { 35 | hashBlocksAVX2(h, c, flag, blocks) 36 | } else if useAVX { 37 | hashBlocksAVX(h, c, flag, blocks) 38 | } else if useSSE4 { 39 | hashBlocksSSE4(h, c, flag, blocks) 40 | } else { 41 | hashBlocksGeneric(h, c, flag, blocks) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/blake2b/blake2b_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !go1.7,amd64,!gccgo,!appengine 6 | 7 | package blake2b 8 | 9 | func init() { 10 | useSSE4 = supportsSSE4() 11 | } 12 | 13 | //go:noescape 14 | func supportsSSE4() bool 15 | 16 | //go:noescape 17 | func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) 18 | 19 | func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { 20 | if useSSE4 { 21 | hashBlocksSSE4(h, c, flag, blocks) 22 | } else { 23 | hashBlocksGeneric(h, c, flag, blocks) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/blake2b/blake2b_ref.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !amd64 appengine gccgo 6 | 7 | package blake2b 8 | 9 | func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { 10 | hashBlocksGeneric(h, c, flag, blocks) 11 | } 12 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/blake2b/register.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.9 6 | 7 | package blake2b 8 | 9 | import ( 10 | "crypto" 11 | "hash" 12 | ) 13 | 14 | func init() { 15 | newHash256 := func() hash.Hash { 16 | h, _ := New256(nil) 17 | return h 18 | } 19 | newHash384 := func() hash.Hash { 20 | h, _ := New384(nil) 21 | return h 22 | } 23 | 24 | newHash512 := func() hash.Hash { 25 | h, _ := New512(nil) 26 | return h 27 | } 28 | 29 | crypto.RegisterHash(crypto.BLAKE2b_256, newHash256) 30 | crypto.RegisterHash(crypto.BLAKE2b_384, newHash384) 31 | crypto.RegisterHash(crypto.BLAKE2b_512, newHash512) 32 | } 33 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/blake2s/blake2s_386.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build 386,!gccgo,!appengine 6 | 7 | package blake2s 8 | 9 | var ( 10 | useSSE4 = false 11 | useSSSE3 = supportSSSE3() 12 | useSSE2 = supportSSE2() 13 | ) 14 | 15 | //go:noescape 16 | func supportSSE2() bool 17 | 18 | //go:noescape 19 | func supportSSSE3() bool 20 | 21 | //go:noescape 22 | func hashBlocksSSE2(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) 23 | 24 | //go:noescape 25 | func hashBlocksSSSE3(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) 26 | 27 | func hashBlocks(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) { 28 | if useSSSE3 { 29 | hashBlocksSSSE3(h, c, flag, blocks) 30 | } else if useSSE2 { 31 | hashBlocksSSE2(h, c, flag, blocks) 32 | } else { 33 | hashBlocksGeneric(h, c, flag, blocks) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/blake2s/blake2s_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build amd64,!gccgo,!appengine 6 | 7 | package blake2s 8 | 9 | var ( 10 | useSSE4 = supportSSE4() 11 | useSSSE3 = supportSSSE3() 12 | useSSE2 = true // Always available on amd64 13 | ) 14 | 15 | //go:noescape 16 | func supportSSSE3() bool 17 | 18 | //go:noescape 19 | func supportSSE4() bool 20 | 21 | //go:noescape 22 | func hashBlocksSSE2(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) 23 | 24 | //go:noescape 25 | func hashBlocksSSSE3(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) 26 | 27 | //go:noescape 28 | func hashBlocksSSE4(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) 29 | 30 | func hashBlocks(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) { 31 | if useSSE4 { 32 | hashBlocksSSE4(h, c, flag, blocks) 33 | } else if useSSSE3 { 34 | hashBlocksSSSE3(h, c, flag, blocks) 35 | } else if useSSE2 { 36 | hashBlocksSSE2(h, c, flag, blocks) 37 | } else { 38 | hashBlocksGeneric(h, c, flag, blocks) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/blake2s/blake2s_ref.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !amd64,!386 gccgo appengine 6 | 7 | package blake2s 8 | 9 | var ( 10 | useSSE4 = false 11 | useSSSE3 = false 12 | useSSE2 = false 13 | ) 14 | 15 | func hashBlocks(h *[8]uint32, c *[2]uint32, flag uint32, blocks []byte) { 16 | hashBlocksGeneric(h, c, flag, blocks) 17 | } 18 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/blake2s/register.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.9 6 | 7 | package blake2s 8 | 9 | import ( 10 | "crypto" 11 | "hash" 12 | ) 13 | 14 | func init() { 15 | newHash256 := func() hash.Hash { 16 | h, _ := New256(nil) 17 | return h 18 | } 19 | 20 | crypto.RegisterHash(crypto.BLAKE2s_256, newHash256) 21 | } 22 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/blowfish/cipher.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package blowfish implements Bruce Schneier's Blowfish encryption algorithm. 6 | package blowfish // import "golang.org/x/crypto/blowfish" 7 | 8 | // The code is a port of Bruce Schneier's C implementation. 9 | // See https://www.schneier.com/blowfish.html. 10 | 11 | import "strconv" 12 | 13 | // The Blowfish block size in bytes. 14 | const BlockSize = 8 15 | 16 | // A Cipher is an instance of Blowfish encryption using a particular key. 17 | type Cipher struct { 18 | p [18]uint32 19 | s0, s1, s2, s3 [256]uint32 20 | } 21 | 22 | type KeySizeError int 23 | 24 | func (k KeySizeError) Error() string { 25 | return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k)) 26 | } 27 | 28 | // NewCipher creates and returns a Cipher. 29 | // The key argument should be the Blowfish key, from 1 to 56 bytes. 30 | func NewCipher(key []byte) (*Cipher, error) { 31 | var result Cipher 32 | if k := len(key); k < 1 || k > 56 { 33 | return nil, KeySizeError(k) 34 | } 35 | initCipher(&result) 36 | ExpandKey(key, &result) 37 | return &result, nil 38 | } 39 | 40 | // NewSaltedCipher creates a returns a Cipher that folds a salt into its key 41 | // schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is 42 | // sufficient and desirable. For bcrypt compatibility, the key can be over 56 43 | // bytes. 44 | func NewSaltedCipher(key, salt []byte) (*Cipher, error) { 45 | if len(salt) == 0 { 46 | return NewCipher(key) 47 | } 48 | var result Cipher 49 | if k := len(key); k < 1 { 50 | return nil, KeySizeError(k) 51 | } 52 | initCipher(&result) 53 | expandKeyWithSalt(key, salt, &result) 54 | return &result, nil 55 | } 56 | 57 | // BlockSize returns the Blowfish block size, 8 bytes. 58 | // It is necessary to satisfy the Block interface in the 59 | // package "crypto/cipher". 60 | func (c *Cipher) BlockSize() int { return BlockSize } 61 | 62 | // Encrypt encrypts the 8-byte buffer src using the key k 63 | // and stores the result in dst. 64 | // Note that for amounts of data larger than a block, 65 | // it is not safe to just call Encrypt on successive blocks; 66 | // instead, use an encryption mode like CBC (see crypto/cipher/cbc.go). 67 | func (c *Cipher) Encrypt(dst, src []byte) { 68 | l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) 69 | r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) 70 | l, r = encryptBlock(l, r, c) 71 | dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l) 72 | dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r) 73 | } 74 | 75 | // Decrypt decrypts the 8-byte buffer src using the key k 76 | // and stores the result in dst. 77 | func (c *Cipher) Decrypt(dst, src []byte) { 78 | l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) 79 | r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) 80 | l, r = decryptBlock(l, r, c) 81 | dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l) 82 | dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r) 83 | } 84 | 85 | func initCipher(c *Cipher) { 86 | copy(c.p[0:], p[0:]) 87 | copy(c.s0[0:], s0[0:]) 88 | copy(c.s1[0:], s1[0:]) 89 | copy(c.s2[0:], s2[0:]) 90 | copy(c.s3[0:], s3[0:]) 91 | } 92 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/bn256/constants.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package bn256 6 | 7 | import ( 8 | "math/big" 9 | ) 10 | 11 | func bigFromBase10(s string) *big.Int { 12 | n, _ := new(big.Int).SetString(s, 10) 13 | return n 14 | } 15 | 16 | // u is the BN parameter that determines the prime: 1868033³. 17 | var u = bigFromBase10("6518589491078791937") 18 | 19 | // p is a prime over which we form a basic field: 36u⁴+36u³+24u²+6u+1. 20 | var p = bigFromBase10("65000549695646603732796438742359905742825358107623003571877145026864184071783") 21 | 22 | // Order is the number of elements in both G₁ and G₂: 36u⁴+36u³+18u²+6u+1. 23 | var Order = bigFromBase10("65000549695646603732796438742359905742570406053903786389881062969044166799969") 24 | 25 | // xiToPMinus1Over6 is ξ^((p-1)/6) where ξ = i+3. 26 | var xiToPMinus1Over6 = &gfP2{bigFromBase10("8669379979083712429711189836753509758585994370025260553045152614783263110636"), bigFromBase10("19998038925833620163537568958541907098007303196759855091367510456613536016040")} 27 | 28 | // xiToPMinus1Over3 is ξ^((p-1)/3) where ξ = i+3. 29 | var xiToPMinus1Over3 = &gfP2{bigFromBase10("26098034838977895781559542626833399156321265654106457577426020397262786167059"), bigFromBase10("15931493369629630809226283458085260090334794394361662678240713231519278691715")} 30 | 31 | // xiToPMinus1Over2 is ξ^((p-1)/2) where ξ = i+3. 32 | var xiToPMinus1Over2 = &gfP2{bigFromBase10("50997318142241922852281555961173165965672272825141804376761836765206060036244"), bigFromBase10("38665955945962842195025998234511023902832543644254935982879660597356748036009")} 33 | 34 | // xiToPSquaredMinus1Over3 is ξ^((p²-1)/3) where ξ = i+3. 35 | var xiToPSquaredMinus1Over3 = bigFromBase10("65000549695646603727810655408050771481677621702948236658134783353303381437752") 36 | 37 | // xiTo2PSquaredMinus2Over3 is ξ^((2p²-2)/3) where ξ = i+3 (a cubic root of unity, mod p). 38 | var xiTo2PSquaredMinus2Over3 = bigFromBase10("4985783334309134261147736404674766913742361673560802634030") 39 | 40 | // xiToPSquaredMinus1Over6 is ξ^((1p²-1)/6) where ξ = i+3 (a cubic root of -1, mod p). 41 | var xiToPSquaredMinus1Over6 = bigFromBase10("65000549695646603727810655408050771481677621702948236658134783353303381437753") 42 | 43 | // xiTo2PMinus2Over3 is ξ^((2p-2)/3) where ξ = i+3. 44 | var xiTo2PMinus2Over3 = &gfP2{bigFromBase10("19885131339612776214803633203834694332692106372356013117629940868870585019582"), bigFromBase10("21645619881471562101905880913352894726728173167203616652430647841922248593627")} 45 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/bn256/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package bn256 6 | 7 | import ( 8 | "crypto/rand" 9 | ) 10 | 11 | func ExamplePair() { 12 | // This implements the tripartite Diffie-Hellman algorithm from "A One 13 | // Round Protocol for Tripartite Diffie-Hellman", A. Joux. 14 | // http://www.springerlink.com/content/cddc57yyva0hburb/fulltext.pdf 15 | 16 | // Each of three parties, a, b and c, generate a private value. 17 | a, _ := rand.Int(rand.Reader, Order) 18 | b, _ := rand.Int(rand.Reader, Order) 19 | c, _ := rand.Int(rand.Reader, Order) 20 | 21 | // Then each party calculates g₁ and g₂ times their private value. 22 | pa := new(G1).ScalarBaseMult(a) 23 | qa := new(G2).ScalarBaseMult(a) 24 | 25 | pb := new(G1).ScalarBaseMult(b) 26 | qb := new(G2).ScalarBaseMult(b) 27 | 28 | pc := new(G1).ScalarBaseMult(c) 29 | qc := new(G2).ScalarBaseMult(c) 30 | 31 | // Now each party exchanges its public values with the other two and 32 | // all parties can calculate the shared key. 33 | k1 := Pair(pb, qc) 34 | k1.ScalarMult(k1, a) 35 | 36 | k2 := Pair(pc, qa) 37 | k2.ScalarMult(k2, b) 38 | 39 | k3 := Pair(pa, qb) 40 | k3.ScalarMult(k3, c) 41 | 42 | // k1, k2 and k3 will all be equal. 43 | } 44 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/cast5/cast5_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package cast5 6 | 7 | import ( 8 | "bytes" 9 | "encoding/hex" 10 | "testing" 11 | ) 12 | 13 | // This test vector is taken from RFC 2144, App B.1. 14 | // Since the other two test vectors are for reduced-round variants, we can't 15 | // use them. 16 | var basicTests = []struct { 17 | key, plainText, cipherText string 18 | }{ 19 | { 20 | "0123456712345678234567893456789a", 21 | "0123456789abcdef", 22 | "238b4fe5847e44b2", 23 | }, 24 | } 25 | 26 | func TestBasic(t *testing.T) { 27 | for i, test := range basicTests { 28 | key, _ := hex.DecodeString(test.key) 29 | plainText, _ := hex.DecodeString(test.plainText) 30 | expected, _ := hex.DecodeString(test.cipherText) 31 | 32 | c, err := NewCipher(key) 33 | if err != nil { 34 | t.Errorf("#%d: failed to create Cipher: %s", i, err) 35 | continue 36 | } 37 | var cipherText [BlockSize]byte 38 | c.Encrypt(cipherText[:], plainText) 39 | if !bytes.Equal(cipherText[:], expected) { 40 | t.Errorf("#%d: got:%x want:%x", i, cipherText, expected) 41 | } 42 | 43 | var plainTextAgain [BlockSize]byte 44 | c.Decrypt(plainTextAgain[:], cipherText[:]) 45 | if !bytes.Equal(plainTextAgain[:], plainText) { 46 | t.Errorf("#%d: got:%x want:%x", i, plainTextAgain, plainText) 47 | } 48 | } 49 | } 50 | 51 | // TestFull performs the test specified in RFC 2144, App B.2. 52 | // However, due to the length of time taken, it's disabled here and a more 53 | // limited version is included, below. 54 | func TestFull(t *testing.T) { 55 | if testing.Short() { 56 | // This is too slow for normal testing 57 | return 58 | } 59 | 60 | a, b := iterate(1000000) 61 | 62 | const expectedA = "eea9d0a249fd3ba6b3436fb89d6dca92" 63 | const expectedB = "b2c95eb00c31ad7180ac05b8e83d696e" 64 | 65 | if hex.EncodeToString(a) != expectedA { 66 | t.Errorf("a: got:%x want:%s", a, expectedA) 67 | } 68 | if hex.EncodeToString(b) != expectedB { 69 | t.Errorf("b: got:%x want:%s", b, expectedB) 70 | } 71 | } 72 | 73 | func iterate(iterations int) ([]byte, []byte) { 74 | const initValueHex = "0123456712345678234567893456789a" 75 | 76 | initValue, _ := hex.DecodeString(initValueHex) 77 | 78 | var a, b [16]byte 79 | copy(a[:], initValue) 80 | copy(b[:], initValue) 81 | 82 | for i := 0; i < iterations; i++ { 83 | c, _ := NewCipher(b[:]) 84 | c.Encrypt(a[:8], a[:8]) 85 | c.Encrypt(a[8:], a[8:]) 86 | c, _ = NewCipher(a[:]) 87 | c.Encrypt(b[:8], b[:8]) 88 | c.Encrypt(b[8:], b[8:]) 89 | } 90 | 91 | return a[:], b[:] 92 | } 93 | 94 | func TestLimited(t *testing.T) { 95 | a, b := iterate(1000) 96 | 97 | const expectedA = "23f73b14b02a2ad7dfb9f2c35644798d" 98 | const expectedB = "e5bf37eff14c456a40b21ce369370a9f" 99 | 100 | if hex.EncodeToString(a) != expectedA { 101 | t.Errorf("a: got:%x want:%s", a, expectedA) 102 | } 103 | if hex.EncodeToString(b) != expectedB { 104 | t.Errorf("b: got:%x want:%s", b, expectedB) 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/chacha20poly1305/chacha20poly1305.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package chacha20poly1305 implements the ChaCha20-Poly1305 AEAD as specified in RFC 7539. 6 | package chacha20poly1305 // import "golang.org/x/crypto/chacha20poly1305" 7 | 8 | import ( 9 | "crypto/cipher" 10 | "errors" 11 | ) 12 | 13 | const ( 14 | // KeySize is the size of the key used by this AEAD, in bytes. 15 | KeySize = 32 16 | // NonceSize is the size of the nonce used with this AEAD, in bytes. 17 | NonceSize = 12 18 | ) 19 | 20 | type chacha20poly1305 struct { 21 | key [32]byte 22 | } 23 | 24 | // New returns a ChaCha20-Poly1305 AEAD that uses the given, 256-bit key. 25 | func New(key []byte) (cipher.AEAD, error) { 26 | if len(key) != KeySize { 27 | return nil, errors.New("chacha20poly1305: bad key length") 28 | } 29 | ret := new(chacha20poly1305) 30 | copy(ret.key[:], key) 31 | return ret, nil 32 | } 33 | 34 | func (c *chacha20poly1305) NonceSize() int { 35 | return NonceSize 36 | } 37 | 38 | func (c *chacha20poly1305) Overhead() int { 39 | return 16 40 | } 41 | 42 | func (c *chacha20poly1305) Seal(dst, nonce, plaintext, additionalData []byte) []byte { 43 | if len(nonce) != NonceSize { 44 | panic("chacha20poly1305: bad nonce length passed to Seal") 45 | } 46 | 47 | if uint64(len(plaintext)) > (1<<38)-64 { 48 | panic("chacha20poly1305: plaintext too large") 49 | } 50 | 51 | return c.seal(dst, nonce, plaintext, additionalData) 52 | } 53 | 54 | var errOpen = errors.New("chacha20poly1305: message authentication failed") 55 | 56 | func (c *chacha20poly1305) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { 57 | if len(nonce) != NonceSize { 58 | panic("chacha20poly1305: bad nonce length passed to Open") 59 | } 60 | if len(ciphertext) < 16 { 61 | return nil, errOpen 62 | } 63 | if uint64(len(ciphertext)) > (1<<38)-48 { 64 | panic("chacha20poly1305: ciphertext too large") 65 | } 66 | 67 | return c.open(dst, nonce, ciphertext, additionalData) 68 | } 69 | 70 | // sliceForAppend takes a slice and a requested number of bytes. It returns a 71 | // slice with the contents of the given slice followed by that many bytes and a 72 | // second slice that aliases into it and contains only the extra bytes. If the 73 | // original slice has sufficient capacity then no allocation is performed. 74 | func sliceForAppend(in []byte, n int) (head, tail []byte) { 75 | if total := len(in) + n; cap(in) >= total { 76 | head = in[:total] 77 | } else { 78 | head = make([]byte, total) 79 | copy(head, in) 80 | } 81 | tail = head[len(in):] 82 | return 83 | } 84 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/chacha20poly1305/chacha20poly1305_generic.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package chacha20poly1305 6 | 7 | import ( 8 | "encoding/binary" 9 | 10 | "golang.org/x/crypto/chacha20poly1305/internal/chacha20" 11 | "golang.org/x/crypto/poly1305" 12 | ) 13 | 14 | func roundTo16(n int) int { 15 | return 16 * ((n + 15) / 16) 16 | } 17 | 18 | func (c *chacha20poly1305) sealGeneric(dst, nonce, plaintext, additionalData []byte) []byte { 19 | var counter [16]byte 20 | copy(counter[4:], nonce) 21 | 22 | var polyKey [32]byte 23 | chacha20.XORKeyStream(polyKey[:], polyKey[:], &counter, &c.key) 24 | 25 | ret, out := sliceForAppend(dst, len(plaintext)+poly1305.TagSize) 26 | counter[0] = 1 27 | chacha20.XORKeyStream(out, plaintext, &counter, &c.key) 28 | 29 | polyInput := make([]byte, roundTo16(len(additionalData))+roundTo16(len(plaintext))+8+8) 30 | copy(polyInput, additionalData) 31 | copy(polyInput[roundTo16(len(additionalData)):], out[:len(plaintext)]) 32 | binary.LittleEndian.PutUint64(polyInput[len(polyInput)-16:], uint64(len(additionalData))) 33 | binary.LittleEndian.PutUint64(polyInput[len(polyInput)-8:], uint64(len(plaintext))) 34 | 35 | var tag [poly1305.TagSize]byte 36 | poly1305.Sum(&tag, polyInput, &polyKey) 37 | copy(out[len(plaintext):], tag[:]) 38 | 39 | return ret 40 | } 41 | 42 | func (c *chacha20poly1305) openGeneric(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { 43 | var tag [poly1305.TagSize]byte 44 | copy(tag[:], ciphertext[len(ciphertext)-16:]) 45 | ciphertext = ciphertext[:len(ciphertext)-16] 46 | 47 | var counter [16]byte 48 | copy(counter[4:], nonce) 49 | 50 | var polyKey [32]byte 51 | chacha20.XORKeyStream(polyKey[:], polyKey[:], &counter, &c.key) 52 | 53 | polyInput := make([]byte, roundTo16(len(additionalData))+roundTo16(len(ciphertext))+8+8) 54 | copy(polyInput, additionalData) 55 | copy(polyInput[roundTo16(len(additionalData)):], ciphertext) 56 | binary.LittleEndian.PutUint64(polyInput[len(polyInput)-16:], uint64(len(additionalData))) 57 | binary.LittleEndian.PutUint64(polyInput[len(polyInput)-8:], uint64(len(ciphertext))) 58 | 59 | ret, out := sliceForAppend(dst, len(ciphertext)) 60 | if !poly1305.Verify(&tag, polyInput, &polyKey) { 61 | for i := range out { 62 | out[i] = 0 63 | } 64 | return nil, errOpen 65 | } 66 | 67 | counter[0] = 1 68 | chacha20.XORKeyStream(out, ciphertext, &counter, &c.key) 69 | return ret, nil 70 | } 71 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/chacha20poly1305/chacha20poly1305_noasm.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !amd64 !go1.7 gccgo appengine 6 | 7 | package chacha20poly1305 8 | 9 | func (c *chacha20poly1305) seal(dst, nonce, plaintext, additionalData []byte) []byte { 10 | return c.sealGeneric(dst, nonce, plaintext, additionalData) 11 | } 12 | 13 | func (c *chacha20poly1305) open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { 14 | return c.openGeneric(dst, nonce, ciphertext, additionalData) 15 | } 16 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/chacha20poly1305/internal/chacha20/chacha_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package chacha20 6 | 7 | import ( 8 | "encoding/hex" 9 | "testing" 10 | ) 11 | 12 | func TestCore(t *testing.T) { 13 | // This is just a smoke test that checks the example from 14 | // https://tools.ietf.org/html/rfc7539#section-2.3.2. The 15 | // chacha20poly1305 package contains much more extensive tests of this 16 | // code. 17 | var key [32]byte 18 | for i := range key { 19 | key[i] = byte(i) 20 | } 21 | 22 | var input [16]byte 23 | input[0] = 1 24 | input[7] = 9 25 | input[11] = 0x4a 26 | 27 | var out [64]byte 28 | XORKeyStream(out[:], out[:], &input, &key) 29 | const expected = "10f1e7e4d13b5915500fdd1fa32071c4c7d1f4c733c068030422aa9ac3d46c4ed2826446079faa0914c2d705d98b02a2b5129cd1de164eb9cbd083e8a2503c4e" 30 | if result := hex.EncodeToString(out[:]); result != expected { 31 | t.Errorf("wanted %x but got %x", expected, result) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/cryptobyte/asn1/asn1.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package asn1 contains supporting types for parsing and building ASN.1 6 | // messages with the cryptobyte package. 7 | package asn1 // import "golang.org/x/crypto/cryptobyte/asn1" 8 | 9 | // Tag represents an ASN.1 identifier octet, consisting of a tag number 10 | // (indicating a type) and class (such as context-specific or constructed). 11 | // 12 | // Methods in the cryptobyte package only support the low-tag-number form, i.e. 13 | // a single identifier octet with bits 7-8 encoding the class and bits 1-6 14 | // encoding the tag number. 15 | type Tag uint8 16 | 17 | const ( 18 | classConstructed = 0x20 19 | classContextSpecific = 0x80 20 | ) 21 | 22 | // Constructed returns t with the constructed class bit set. 23 | func (t Tag) Constructed() Tag { return t | classConstructed } 24 | 25 | // ContextSpecific returns t with the context-specific class bit set. 26 | func (t Tag) ContextSpecific() Tag { return t | classContextSpecific } 27 | 28 | // The following is a list of standard tag and class combinations. 29 | const ( 30 | BOOLEAN = Tag(1) 31 | INTEGER = Tag(2) 32 | BIT_STRING = Tag(3) 33 | OCTET_STRING = Tag(4) 34 | NULL = Tag(5) 35 | OBJECT_IDENTIFIER = Tag(6) 36 | ENUM = Tag(10) 37 | UTF8String = Tag(12) 38 | SEQUENCE = Tag(16 | classConstructed) 39 | SET = Tag(17 | classConstructed) 40 | PrintableString = Tag(19) 41 | T61String = Tag(20) 42 | IA5String = Tag(22) 43 | UTCTime = Tag(23) 44 | GeneralizedTime = Tag(24) 45 | GeneralString = Tag(27) 46 | ) 47 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/curve25519/const_amd64.h: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // This code was translated into a form compatible with 6a from the public 6 | // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html 7 | 8 | #define REDMASK51 0x0007FFFFFFFFFFFF 9 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/curve25519/const_amd64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // This code was translated into a form compatible with 6a from the public 6 | // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html 7 | 8 | // +build amd64,!gccgo,!appengine 9 | 10 | // These constants cannot be encoded in non-MOVQ immediates. 11 | // We access them directly from memory instead. 12 | 13 | DATA ·_121666_213(SB)/8, $996687872 14 | GLOBL ·_121666_213(SB), 8, $8 15 | 16 | DATA ·_2P0(SB)/8, $0xFFFFFFFFFFFDA 17 | GLOBL ·_2P0(SB), 8, $8 18 | 19 | DATA ·_2P1234(SB)/8, $0xFFFFFFFFFFFFE 20 | GLOBL ·_2P1234(SB), 8, $8 21 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/curve25519/cswap_amd64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build amd64,!gccgo,!appengine 6 | 7 | // func cswap(inout *[4][5]uint64, v uint64) 8 | TEXT ·cswap(SB),7,$0 9 | MOVQ inout+0(FP),DI 10 | MOVQ v+8(FP),SI 11 | 12 | SUBQ $1, SI 13 | NOTQ SI 14 | MOVQ SI, X15 15 | PSHUFD $0x44, X15, X15 16 | 17 | MOVOU 0(DI), X0 18 | MOVOU 16(DI), X2 19 | MOVOU 32(DI), X4 20 | MOVOU 48(DI), X6 21 | MOVOU 64(DI), X8 22 | MOVOU 80(DI), X1 23 | MOVOU 96(DI), X3 24 | MOVOU 112(DI), X5 25 | MOVOU 128(DI), X7 26 | MOVOU 144(DI), X9 27 | 28 | MOVO X1, X10 29 | MOVO X3, X11 30 | MOVO X5, X12 31 | MOVO X7, X13 32 | MOVO X9, X14 33 | 34 | PXOR X0, X10 35 | PXOR X2, X11 36 | PXOR X4, X12 37 | PXOR X6, X13 38 | PXOR X8, X14 39 | PAND X15, X10 40 | PAND X15, X11 41 | PAND X15, X12 42 | PAND X15, X13 43 | PAND X15, X14 44 | PXOR X10, X0 45 | PXOR X10, X1 46 | PXOR X11, X2 47 | PXOR X11, X3 48 | PXOR X12, X4 49 | PXOR X12, X5 50 | PXOR X13, X6 51 | PXOR X13, X7 52 | PXOR X14, X8 53 | PXOR X14, X9 54 | 55 | MOVOU X0, 0(DI) 56 | MOVOU X2, 16(DI) 57 | MOVOU X4, 32(DI) 58 | MOVOU X6, 48(DI) 59 | MOVOU X8, 64(DI) 60 | MOVOU X1, 80(DI) 61 | MOVOU X3, 96(DI) 62 | MOVOU X5, 112(DI) 63 | MOVOU X7, 128(DI) 64 | MOVOU X9, 144(DI) 65 | RET 66 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/curve25519/curve25519_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package curve25519 6 | 7 | import ( 8 | "fmt" 9 | "testing" 10 | ) 11 | 12 | const expectedHex = "89161fde887b2b53de549af483940106ecc114d6982daa98256de23bdf77661a" 13 | 14 | func TestBaseScalarMult(t *testing.T) { 15 | var a, b [32]byte 16 | in := &a 17 | out := &b 18 | a[0] = 1 19 | 20 | for i := 0; i < 200; i++ { 21 | ScalarBaseMult(out, in) 22 | in, out = out, in 23 | } 24 | 25 | result := fmt.Sprintf("%x", in[:]) 26 | if result != expectedHex { 27 | t.Errorf("incorrect result: got %s, want %s", result, expectedHex) 28 | } 29 | } 30 | 31 | func BenchmarkScalarBaseMult(b *testing.B) { 32 | var in, out [32]byte 33 | in[0] = 1 34 | 35 | b.SetBytes(32) 36 | for i := 0; i < b.N; i++ { 37 | ScalarBaseMult(&out, &in) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/curve25519/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package curve25519 provides an implementation of scalar multiplication on 6 | // the elliptic curve known as curve25519. See https://cr.yp.to/ecdh.html 7 | package curve25519 // import "golang.org/x/crypto/curve25519" 8 | 9 | // basePoint is the x coordinate of the generator of the curve. 10 | var basePoint = [32]byte{9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} 11 | 12 | // ScalarMult sets dst to the product in*base where dst and base are the x 13 | // coordinates of group points and all values are in little-endian form. 14 | func ScalarMult(dst, in, base *[32]byte) { 15 | scalarMult(dst, in, base) 16 | } 17 | 18 | // ScalarBaseMult sets dst to the product in*base where dst and base are the x 19 | // coordinates of group points, base is the standard generator and all values 20 | // are in little-endian form. 21 | func ScalarBaseMult(dst, in *[32]byte) { 22 | ScalarMult(dst, in, &basePoint) 23 | } 24 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/curve25519/freeze_amd64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // This code was translated into a form compatible with 6a from the public 6 | // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html 7 | 8 | // +build amd64,!gccgo,!appengine 9 | 10 | #include "const_amd64.h" 11 | 12 | // func freeze(inout *[5]uint64) 13 | TEXT ·freeze(SB),7,$0-8 14 | MOVQ inout+0(FP), DI 15 | 16 | MOVQ 0(DI),SI 17 | MOVQ 8(DI),DX 18 | MOVQ 16(DI),CX 19 | MOVQ 24(DI),R8 20 | MOVQ 32(DI),R9 21 | MOVQ $REDMASK51,AX 22 | MOVQ AX,R10 23 | SUBQ $18,R10 24 | MOVQ $3,R11 25 | REDUCELOOP: 26 | MOVQ SI,R12 27 | SHRQ $51,R12 28 | ANDQ AX,SI 29 | ADDQ R12,DX 30 | MOVQ DX,R12 31 | SHRQ $51,R12 32 | ANDQ AX,DX 33 | ADDQ R12,CX 34 | MOVQ CX,R12 35 | SHRQ $51,R12 36 | ANDQ AX,CX 37 | ADDQ R12,R8 38 | MOVQ R8,R12 39 | SHRQ $51,R12 40 | ANDQ AX,R8 41 | ADDQ R12,R9 42 | MOVQ R9,R12 43 | SHRQ $51,R12 44 | ANDQ AX,R9 45 | IMUL3Q $19,R12,R12 46 | ADDQ R12,SI 47 | SUBQ $1,R11 48 | JA REDUCELOOP 49 | MOVQ $1,R12 50 | CMPQ R10,SI 51 | CMOVQLT R11,R12 52 | CMPQ AX,DX 53 | CMOVQNE R11,R12 54 | CMPQ AX,CX 55 | CMOVQNE R11,R12 56 | CMPQ AX,R8 57 | CMOVQNE R11,R12 58 | CMPQ AX,R9 59 | CMOVQNE R11,R12 60 | NEGQ R12 61 | ANDQ R12,AX 62 | ANDQ R12,R10 63 | SUBQ R10,SI 64 | SUBQ AX,DX 65 | SUBQ AX,CX 66 | SUBQ AX,R8 67 | SUBQ AX,R9 68 | MOVQ SI,0(DI) 69 | MOVQ DX,8(DI) 70 | MOVQ CX,16(DI) 71 | MOVQ R8,24(DI) 72 | MOVQ R9,32(DI) 73 | RET 74 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/curve25519/mul_amd64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // This code was translated into a form compatible with 6a from the public 6 | // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html 7 | 8 | // +build amd64,!gccgo,!appengine 9 | 10 | #include "const_amd64.h" 11 | 12 | // func mul(dest, a, b *[5]uint64) 13 | TEXT ·mul(SB),0,$16-24 14 | MOVQ dest+0(FP), DI 15 | MOVQ a+8(FP), SI 16 | MOVQ b+16(FP), DX 17 | 18 | MOVQ DX,CX 19 | MOVQ 24(SI),DX 20 | IMUL3Q $19,DX,AX 21 | MOVQ AX,0(SP) 22 | MULQ 16(CX) 23 | MOVQ AX,R8 24 | MOVQ DX,R9 25 | MOVQ 32(SI),DX 26 | IMUL3Q $19,DX,AX 27 | MOVQ AX,8(SP) 28 | MULQ 8(CX) 29 | ADDQ AX,R8 30 | ADCQ DX,R9 31 | MOVQ 0(SI),AX 32 | MULQ 0(CX) 33 | ADDQ AX,R8 34 | ADCQ DX,R9 35 | MOVQ 0(SI),AX 36 | MULQ 8(CX) 37 | MOVQ AX,R10 38 | MOVQ DX,R11 39 | MOVQ 0(SI),AX 40 | MULQ 16(CX) 41 | MOVQ AX,R12 42 | MOVQ DX,R13 43 | MOVQ 0(SI),AX 44 | MULQ 24(CX) 45 | MOVQ AX,R14 46 | MOVQ DX,R15 47 | MOVQ 0(SI),AX 48 | MULQ 32(CX) 49 | MOVQ AX,BX 50 | MOVQ DX,BP 51 | MOVQ 8(SI),AX 52 | MULQ 0(CX) 53 | ADDQ AX,R10 54 | ADCQ DX,R11 55 | MOVQ 8(SI),AX 56 | MULQ 8(CX) 57 | ADDQ AX,R12 58 | ADCQ DX,R13 59 | MOVQ 8(SI),AX 60 | MULQ 16(CX) 61 | ADDQ AX,R14 62 | ADCQ DX,R15 63 | MOVQ 8(SI),AX 64 | MULQ 24(CX) 65 | ADDQ AX,BX 66 | ADCQ DX,BP 67 | MOVQ 8(SI),DX 68 | IMUL3Q $19,DX,AX 69 | MULQ 32(CX) 70 | ADDQ AX,R8 71 | ADCQ DX,R9 72 | MOVQ 16(SI),AX 73 | MULQ 0(CX) 74 | ADDQ AX,R12 75 | ADCQ DX,R13 76 | MOVQ 16(SI),AX 77 | MULQ 8(CX) 78 | ADDQ AX,R14 79 | ADCQ DX,R15 80 | MOVQ 16(SI),AX 81 | MULQ 16(CX) 82 | ADDQ AX,BX 83 | ADCQ DX,BP 84 | MOVQ 16(SI),DX 85 | IMUL3Q $19,DX,AX 86 | MULQ 24(CX) 87 | ADDQ AX,R8 88 | ADCQ DX,R9 89 | MOVQ 16(SI),DX 90 | IMUL3Q $19,DX,AX 91 | MULQ 32(CX) 92 | ADDQ AX,R10 93 | ADCQ DX,R11 94 | MOVQ 24(SI),AX 95 | MULQ 0(CX) 96 | ADDQ AX,R14 97 | ADCQ DX,R15 98 | MOVQ 24(SI),AX 99 | MULQ 8(CX) 100 | ADDQ AX,BX 101 | ADCQ DX,BP 102 | MOVQ 0(SP),AX 103 | MULQ 24(CX) 104 | ADDQ AX,R10 105 | ADCQ DX,R11 106 | MOVQ 0(SP),AX 107 | MULQ 32(CX) 108 | ADDQ AX,R12 109 | ADCQ DX,R13 110 | MOVQ 32(SI),AX 111 | MULQ 0(CX) 112 | ADDQ AX,BX 113 | ADCQ DX,BP 114 | MOVQ 8(SP),AX 115 | MULQ 16(CX) 116 | ADDQ AX,R10 117 | ADCQ DX,R11 118 | MOVQ 8(SP),AX 119 | MULQ 24(CX) 120 | ADDQ AX,R12 121 | ADCQ DX,R13 122 | MOVQ 8(SP),AX 123 | MULQ 32(CX) 124 | ADDQ AX,R14 125 | ADCQ DX,R15 126 | MOVQ $REDMASK51,SI 127 | SHLQ $13,R9:R8 128 | ANDQ SI,R8 129 | SHLQ $13,R11:R10 130 | ANDQ SI,R10 131 | ADDQ R9,R10 132 | SHLQ $13,R13:R12 133 | ANDQ SI,R12 134 | ADDQ R11,R12 135 | SHLQ $13,R15:R14 136 | ANDQ SI,R14 137 | ADDQ R13,R14 138 | SHLQ $13,BP:BX 139 | ANDQ SI,BX 140 | ADDQ R15,BX 141 | IMUL3Q $19,BP,DX 142 | ADDQ DX,R8 143 | MOVQ R8,DX 144 | SHRQ $51,DX 145 | ADDQ R10,DX 146 | MOVQ DX,CX 147 | SHRQ $51,DX 148 | ANDQ SI,R8 149 | ADDQ R12,DX 150 | MOVQ DX,R9 151 | SHRQ $51,DX 152 | ANDQ SI,CX 153 | ADDQ R14,DX 154 | MOVQ DX,AX 155 | SHRQ $51,DX 156 | ANDQ SI,R9 157 | ADDQ BX,DX 158 | MOVQ DX,R10 159 | SHRQ $51,DX 160 | ANDQ SI,AX 161 | IMUL3Q $19,DX,DX 162 | ADDQ DX,R8 163 | ANDQ SI,R10 164 | MOVQ R8,0(DI) 165 | MOVQ CX,8(DI) 166 | MOVQ R9,16(DI) 167 | MOVQ AX,24(DI) 168 | MOVQ R10,32(DI) 169 | RET 170 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/curve25519/square_amd64.s: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // This code was translated into a form compatible with 6a from the public 6 | // domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html 7 | 8 | // +build amd64,!gccgo,!appengine 9 | 10 | #include "const_amd64.h" 11 | 12 | // func square(out, in *[5]uint64) 13 | TEXT ·square(SB),7,$0-16 14 | MOVQ out+0(FP), DI 15 | MOVQ in+8(FP), SI 16 | 17 | MOVQ 0(SI),AX 18 | MULQ 0(SI) 19 | MOVQ AX,CX 20 | MOVQ DX,R8 21 | MOVQ 0(SI),AX 22 | SHLQ $1,AX 23 | MULQ 8(SI) 24 | MOVQ AX,R9 25 | MOVQ DX,R10 26 | MOVQ 0(SI),AX 27 | SHLQ $1,AX 28 | MULQ 16(SI) 29 | MOVQ AX,R11 30 | MOVQ DX,R12 31 | MOVQ 0(SI),AX 32 | SHLQ $1,AX 33 | MULQ 24(SI) 34 | MOVQ AX,R13 35 | MOVQ DX,R14 36 | MOVQ 0(SI),AX 37 | SHLQ $1,AX 38 | MULQ 32(SI) 39 | MOVQ AX,R15 40 | MOVQ DX,BX 41 | MOVQ 8(SI),AX 42 | MULQ 8(SI) 43 | ADDQ AX,R11 44 | ADCQ DX,R12 45 | MOVQ 8(SI),AX 46 | SHLQ $1,AX 47 | MULQ 16(SI) 48 | ADDQ AX,R13 49 | ADCQ DX,R14 50 | MOVQ 8(SI),AX 51 | SHLQ $1,AX 52 | MULQ 24(SI) 53 | ADDQ AX,R15 54 | ADCQ DX,BX 55 | MOVQ 8(SI),DX 56 | IMUL3Q $38,DX,AX 57 | MULQ 32(SI) 58 | ADDQ AX,CX 59 | ADCQ DX,R8 60 | MOVQ 16(SI),AX 61 | MULQ 16(SI) 62 | ADDQ AX,R15 63 | ADCQ DX,BX 64 | MOVQ 16(SI),DX 65 | IMUL3Q $38,DX,AX 66 | MULQ 24(SI) 67 | ADDQ AX,CX 68 | ADCQ DX,R8 69 | MOVQ 16(SI),DX 70 | IMUL3Q $38,DX,AX 71 | MULQ 32(SI) 72 | ADDQ AX,R9 73 | ADCQ DX,R10 74 | MOVQ 24(SI),DX 75 | IMUL3Q $19,DX,AX 76 | MULQ 24(SI) 77 | ADDQ AX,R9 78 | ADCQ DX,R10 79 | MOVQ 24(SI),DX 80 | IMUL3Q $38,DX,AX 81 | MULQ 32(SI) 82 | ADDQ AX,R11 83 | ADCQ DX,R12 84 | MOVQ 32(SI),DX 85 | IMUL3Q $19,DX,AX 86 | MULQ 32(SI) 87 | ADDQ AX,R13 88 | ADCQ DX,R14 89 | MOVQ $REDMASK51,SI 90 | SHLQ $13,R8:CX 91 | ANDQ SI,CX 92 | SHLQ $13,R10:R9 93 | ANDQ SI,R9 94 | ADDQ R8,R9 95 | SHLQ $13,R12:R11 96 | ANDQ SI,R11 97 | ADDQ R10,R11 98 | SHLQ $13,R14:R13 99 | ANDQ SI,R13 100 | ADDQ R12,R13 101 | SHLQ $13,BX:R15 102 | ANDQ SI,R15 103 | ADDQ R14,R15 104 | IMUL3Q $19,BX,DX 105 | ADDQ DX,CX 106 | MOVQ CX,DX 107 | SHRQ $51,DX 108 | ADDQ R9,DX 109 | ANDQ SI,CX 110 | MOVQ DX,R8 111 | SHRQ $51,DX 112 | ADDQ R11,DX 113 | ANDQ SI,R8 114 | MOVQ DX,R9 115 | SHRQ $51,DX 116 | ADDQ R13,DX 117 | ANDQ SI,R9 118 | MOVQ DX,AX 119 | SHRQ $51,DX 120 | ADDQ R15,DX 121 | ANDQ SI,AX 122 | MOVQ DX,R10 123 | SHRQ $51,DX 124 | IMUL3Q $19,DX,DX 125 | ADDQ DX,CX 126 | ANDQ SI,R10 127 | MOVQ CX,0(DI) 128 | MOVQ R8,8(DI) 129 | MOVQ R9,16(DI) 130 | MOVQ AX,24(DI) 131 | MOVQ R10,32(DI) 132 | RET 133 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ed25519/testdata/sign.input.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qq906907952/go_proxy/d750932506068316b6031e68699c160e87361b59/src/golang.org/x/crypto/ed25519/testdata/sign.input.gz -------------------------------------------------------------------------------- /src/golang.org/x/crypto/hkdf/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package hkdf_test 6 | 7 | import ( 8 | "bytes" 9 | "crypto/rand" 10 | "crypto/sha256" 11 | "fmt" 12 | "golang.org/x/crypto/hkdf" 13 | "io" 14 | ) 15 | 16 | // Usage example that expands one master key into three other cryptographically 17 | // secure keys. 18 | func Example_usage() { 19 | // Underlying hash function to use 20 | hash := sha256.New 21 | 22 | // Cryptographically secure master key. 23 | master := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this. 24 | 25 | // Non secret salt, optional (can be nil) 26 | // Recommended: hash-length sized random 27 | salt := make([]byte, hash().Size()) 28 | n, err := io.ReadFull(rand.Reader, salt) 29 | if n != len(salt) || err != nil { 30 | fmt.Println("error:", err) 31 | return 32 | } 33 | 34 | // Non secret context specific info, optional (can be nil). 35 | // Note, independent from the master key. 36 | info := []byte{0x03, 0x14, 0x15, 0x92, 0x65} 37 | 38 | // Create the key derivation function 39 | hkdf := hkdf.New(hash, master, salt, info) 40 | 41 | // Generate the required keys 42 | keys := make([][]byte, 3) 43 | for i := 0; i < len(keys); i++ { 44 | keys[i] = make([]byte, 24) 45 | n, err := io.ReadFull(hkdf, keys[i]) 46 | if n != len(keys[i]) || err != nil { 47 | fmt.Println("error:", err) 48 | return 49 | } 50 | } 51 | 52 | // Keys should contain 192 bit random keys 53 | for i := 1; i <= len(keys); i++ { 54 | fmt.Printf("Key #%d: %v\n", i, !bytes.Equal(keys[i-1], make([]byte, 24))) 55 | } 56 | 57 | // Output: 58 | // Key #1: true 59 | // Key #2: true 60 | // Key #3: true 61 | } 62 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/hkdf/hkdf.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package hkdf implements the HMAC-based Extract-and-Expand Key Derivation 6 | // Function (HKDF) as defined in RFC 5869. 7 | // 8 | // HKDF is a cryptographic key derivation function (KDF) with the goal of 9 | // expanding limited input keying material into one or more cryptographically 10 | // strong secret keys. 11 | // 12 | // RFC 5869: https://tools.ietf.org/html/rfc5869 13 | package hkdf // import "golang.org/x/crypto/hkdf" 14 | 15 | import ( 16 | "crypto/hmac" 17 | "errors" 18 | "hash" 19 | "io" 20 | ) 21 | 22 | type hkdf struct { 23 | expander hash.Hash 24 | size int 25 | 26 | info []byte 27 | counter byte 28 | 29 | prev []byte 30 | cache []byte 31 | } 32 | 33 | func (f *hkdf) Read(p []byte) (int, error) { 34 | // Check whether enough data can be generated 35 | need := len(p) 36 | remains := len(f.cache) + int(255-f.counter+1)*f.size 37 | if remains < need { 38 | return 0, errors.New("hkdf: entropy limit reached") 39 | } 40 | // Read from the cache, if enough data is present 41 | n := copy(p, f.cache) 42 | p = p[n:] 43 | 44 | // Fill the buffer 45 | for len(p) > 0 { 46 | f.expander.Reset() 47 | f.expander.Write(f.prev) 48 | f.expander.Write(f.info) 49 | f.expander.Write([]byte{f.counter}) 50 | f.prev = f.expander.Sum(f.prev[:0]) 51 | f.counter++ 52 | 53 | // Copy the new batch into p 54 | f.cache = f.prev 55 | n = copy(p, f.cache) 56 | p = p[n:] 57 | } 58 | // Save leftovers for next run 59 | f.cache = f.cache[n:] 60 | 61 | return need, nil 62 | } 63 | 64 | // New returns a new HKDF using the given hash, the secret keying material to expand 65 | // and optional salt and info fields. 66 | func New(hash func() hash.Hash, secret, salt, info []byte) io.Reader { 67 | if salt == nil { 68 | salt = make([]byte, hash().Size()) 69 | } 70 | extractor := hmac.New(hash, salt) 71 | extractor.Write(secret) 72 | prk := extractor.Sum(nil) 73 | 74 | return &hkdf{hmac.New(hash, prk), extractor.Size(), info, 1, nil, nil} 75 | } 76 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/md4/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package md4_test 6 | 7 | import ( 8 | "fmt" 9 | "io" 10 | 11 | "golang.org/x/crypto/md4" 12 | ) 13 | 14 | func ExampleNew() { 15 | h := md4.New() 16 | data := "These pretzels are making me thirsty." 17 | io.WriteString(h, data) 18 | fmt.Printf("%x", h.Sum(nil)) 19 | // Output: 48c4e365090b30a32f084c4888deceaa 20 | } 21 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/md4/md4.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package md4 implements the MD4 hash algorithm as defined in RFC 1320. 6 | package md4 // import "golang.org/x/crypto/md4" 7 | 8 | import ( 9 | "crypto" 10 | "hash" 11 | ) 12 | 13 | func init() { 14 | crypto.RegisterHash(crypto.MD4, New) 15 | } 16 | 17 | // The size of an MD4 checksum in bytes. 18 | const Size = 16 19 | 20 | // The blocksize of MD4 in bytes. 21 | const BlockSize = 64 22 | 23 | const ( 24 | _Chunk = 64 25 | _Init0 = 0x67452301 26 | _Init1 = 0xEFCDAB89 27 | _Init2 = 0x98BADCFE 28 | _Init3 = 0x10325476 29 | ) 30 | 31 | // digest represents the partial evaluation of a checksum. 32 | type digest struct { 33 | s [4]uint32 34 | x [_Chunk]byte 35 | nx int 36 | len uint64 37 | } 38 | 39 | func (d *digest) Reset() { 40 | d.s[0] = _Init0 41 | d.s[1] = _Init1 42 | d.s[2] = _Init2 43 | d.s[3] = _Init3 44 | d.nx = 0 45 | d.len = 0 46 | } 47 | 48 | // New returns a new hash.Hash computing the MD4 checksum. 49 | func New() hash.Hash { 50 | d := new(digest) 51 | d.Reset() 52 | return d 53 | } 54 | 55 | func (d *digest) Size() int { return Size } 56 | 57 | func (d *digest) BlockSize() int { return BlockSize } 58 | 59 | func (d *digest) Write(p []byte) (nn int, err error) { 60 | nn = len(p) 61 | d.len += uint64(nn) 62 | if d.nx > 0 { 63 | n := len(p) 64 | if n > _Chunk-d.nx { 65 | n = _Chunk - d.nx 66 | } 67 | for i := 0; i < n; i++ { 68 | d.x[d.nx+i] = p[i] 69 | } 70 | d.nx += n 71 | if d.nx == _Chunk { 72 | _Block(d, d.x[0:]) 73 | d.nx = 0 74 | } 75 | p = p[n:] 76 | } 77 | n := _Block(d, p) 78 | p = p[n:] 79 | if len(p) > 0 { 80 | d.nx = copy(d.x[:], p) 81 | } 82 | return 83 | } 84 | 85 | func (d0 *digest) Sum(in []byte) []byte { 86 | // Make a copy of d0, so that caller can keep writing and summing. 87 | d := new(digest) 88 | *d = *d0 89 | 90 | // Padding. Add a 1 bit and 0 bits until 56 bytes mod 64. 91 | len := d.len 92 | var tmp [64]byte 93 | tmp[0] = 0x80 94 | if len%64 < 56 { 95 | d.Write(tmp[0 : 56-len%64]) 96 | } else { 97 | d.Write(tmp[0 : 64+56-len%64]) 98 | } 99 | 100 | // Length in bits. 101 | len <<= 3 102 | for i := uint(0); i < 8; i++ { 103 | tmp[i] = byte(len >> (8 * i)) 104 | } 105 | d.Write(tmp[0:8]) 106 | 107 | if d.nx != 0 { 108 | panic("d.nx != 0") 109 | } 110 | 111 | for _, s := range d.s { 112 | in = append(in, byte(s>>0)) 113 | in = append(in, byte(s>>8)) 114 | in = append(in, byte(s>>16)) 115 | in = append(in, byte(s>>24)) 116 | } 117 | return in 118 | } 119 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/md4/md4_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package md4 6 | 7 | import ( 8 | "fmt" 9 | "io" 10 | "testing" 11 | ) 12 | 13 | type md4Test struct { 14 | out string 15 | in string 16 | } 17 | 18 | var golden = []md4Test{ 19 | {"31d6cfe0d16ae931b73c59d7e0c089c0", ""}, 20 | {"bde52cb31de33e46245e05fbdbd6fb24", "a"}, 21 | {"ec388dd78999dfc7cf4632465693b6bf", "ab"}, 22 | {"a448017aaf21d8525fc10ae87aa6729d", "abc"}, 23 | {"41decd8f579255c5200f86a4bb3ba740", "abcd"}, 24 | {"9803f4a34e8eb14f96adba49064a0c41", "abcde"}, 25 | {"804e7f1c2586e50b49ac65db5b645131", "abcdef"}, 26 | {"752f4adfe53d1da0241b5bc216d098fc", "abcdefg"}, 27 | {"ad9daf8d49d81988590a6f0e745d15dd", "abcdefgh"}, 28 | {"1e4e28b05464316b56402b3815ed2dfd", "abcdefghi"}, 29 | {"dc959c6f5d6f9e04e4380777cc964b3d", "abcdefghij"}, 30 | {"1b5701e265778898ef7de5623bbe7cc0", "Discard medicine more than two years old."}, 31 | {"d7f087e090fe7ad4a01cb59dacc9a572", "He who has a shady past knows that nice guys finish last."}, 32 | {"a6f8fd6df617c72837592fc3570595c9", "I wouldn't marry him with a ten foot pole."}, 33 | {"c92a84a9526da8abc240c05d6b1a1ce0", "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"}, 34 | {"f6013160c4dcb00847069fee3bb09803", "The days of the digital watch are numbered. -Tom Stoppard"}, 35 | {"2c3bb64f50b9107ed57640fe94bec09f", "Nepal premier won't resign."}, 36 | {"45b7d8a32c7806f2f7f897332774d6e4", "For every action there is an equal and opposite government program."}, 37 | {"b5b4f9026b175c62d7654bdc3a1cd438", "His money is twice tainted: 'taint yours and 'taint mine."}, 38 | {"caf44e80f2c20ce19b5ba1cab766e7bd", "There is no reason for any individual to have a computer in their home. -Ken Olsen, 1977"}, 39 | {"191fae6707f496aa54a6bce9f2ecf74d", "It's a tiny change to the code and not completely disgusting. - Bob Manchek"}, 40 | {"9ddc753e7a4ccee6081cd1b45b23a834", "size: a.out: bad magic"}, 41 | {"8d050f55b1cadb9323474564be08a521", "The major problem is with sendmail. -Mark Horton"}, 42 | {"ad6e2587f74c3e3cc19146f6127fa2e3", "Give me a rock, paper and scissors and I will move the world. CCFestoon"}, 43 | {"1d616d60a5fabe85589c3f1566ca7fca", "If the enemy is within range, then so are you."}, 44 | {"aec3326a4f496a2ced65a1963f84577f", "It's well we cannot hear the screams/That we create in others' dreams."}, 45 | {"77b4fd762d6b9245e61c50bf6ebf118b", "You remind me of a TV show, but that's all right: I watch it anyway."}, 46 | {"e8f48c726bae5e516f6ddb1a4fe62438", "C is as portable as Stonehedge!!"}, 47 | {"a3a84366e7219e887423b01f9be7166e", "Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley"}, 48 | {"a6b7aa35157e984ef5d9b7f32e5fbb52", "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"}, 49 | {"75661f0545955f8f9abeeb17845f3fd6", "How can you write a big system without C++? -Paul Glick"}, 50 | } 51 | 52 | func TestGolden(t *testing.T) { 53 | for i := 0; i < len(golden); i++ { 54 | g := golden[i] 55 | c := New() 56 | for j := 0; j < 3; j++ { 57 | if j < 2 { 58 | io.WriteString(c, g.in) 59 | } else { 60 | io.WriteString(c, g.in[0:len(g.in)/2]) 61 | c.Sum(nil) 62 | io.WriteString(c, g.in[len(g.in)/2:]) 63 | } 64 | s := fmt.Sprintf("%x", c.Sum(nil)) 65 | if s != g.out { 66 | t.Fatalf("md4[%d](%s) = %s want %s", j, g.in, s, g.out) 67 | } 68 | c.Reset() 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/md4/md4block.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // MD4 block step. 6 | // In its own file so that a faster assembly or C version 7 | // can be substituted easily. 8 | 9 | package md4 10 | 11 | var shift1 = []uint{3, 7, 11, 19} 12 | var shift2 = []uint{3, 5, 9, 13} 13 | var shift3 = []uint{3, 9, 11, 15} 14 | 15 | var xIndex2 = []uint{0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15} 16 | var xIndex3 = []uint{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15} 17 | 18 | func _Block(dig *digest, p []byte) int { 19 | a := dig.s[0] 20 | b := dig.s[1] 21 | c := dig.s[2] 22 | d := dig.s[3] 23 | n := 0 24 | var X [16]uint32 25 | for len(p) >= _Chunk { 26 | aa, bb, cc, dd := a, b, c, d 27 | 28 | j := 0 29 | for i := 0; i < 16; i++ { 30 | X[i] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24 31 | j += 4 32 | } 33 | 34 | // If this needs to be made faster in the future, 35 | // the usual trick is to unroll each of these 36 | // loops by a factor of 4; that lets you replace 37 | // the shift[] lookups with constants and, 38 | // with suitable variable renaming in each 39 | // unrolled body, delete the a, b, c, d = d, a, b, c 40 | // (or you can let the optimizer do the renaming). 41 | // 42 | // The index variables are uint so that % by a power 43 | // of two can be optimized easily by a compiler. 44 | 45 | // Round 1. 46 | for i := uint(0); i < 16; i++ { 47 | x := i 48 | s := shift1[i%4] 49 | f := ((c ^ d) & b) ^ d 50 | a += f + X[x] 51 | a = a<>(32-s) 52 | a, b, c, d = d, a, b, c 53 | } 54 | 55 | // Round 2. 56 | for i := uint(0); i < 16; i++ { 57 | x := xIndex2[i] 58 | s := shift2[i%4] 59 | g := (b & c) | (b & d) | (c & d) 60 | a += g + X[x] + 0x5a827999 61 | a = a<>(32-s) 62 | a, b, c, d = d, a, b, c 63 | } 64 | 65 | // Round 3. 66 | for i := uint(0); i < 16; i++ { 67 | x := xIndex3[i] 68 | s := shift3[i%4] 69 | h := b ^ c ^ d 70 | a += h + X[x] + 0x6ed9eba1 71 | a = a<>(32-s) 72 | a, b, c, d = d, a, b, c 73 | } 74 | 75 | a += aa 76 | b += bb 77 | c += cc 78 | d += dd 79 | 80 | p = p[_Chunk:] 81 | n += _Chunk 82 | } 83 | 84 | dig.s[0] = a 85 | dig.s[1] = b 86 | dig.s[2] = c 87 | dig.s[3] = d 88 | return n 89 | } 90 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/nacl/auth/auth.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package auth authenticates a message using a secret key. 7 | 8 | The Sum function, viewed as a function of the message for a uniform random 9 | key, is designed to meet the standard notion of unforgeability. This means 10 | that an attacker cannot find authenticators for any messages not authenticated 11 | by the sender, even if the attacker has adaptively influenced the messages 12 | authenticated by the sender. For a formal definition see, e.g., Section 2.4 13 | of Bellare, Kilian, and Rogaway, "The security of the cipher block chaining 14 | message authentication code," Journal of Computer and System Sciences 61 (2000), 15 | 362–399; http://www-cse.ucsd.edu/~mihir/papers/cbc.html. 16 | 17 | auth does not make any promises regarding "strong" unforgeability; perhaps 18 | one valid authenticator can be converted into another valid authenticator for 19 | the same message. NaCl also does not make any promises regarding "truncated 20 | unforgeability." 21 | 22 | This package is interoperable with NaCl: https://nacl.cr.yp.to/auth.html. 23 | */ 24 | package auth 25 | 26 | import ( 27 | "crypto/hmac" 28 | "crypto/sha512" 29 | ) 30 | 31 | const ( 32 | // Size is the size, in bytes, of an authenticated digest. 33 | Size = 32 34 | // KeySize is the size, in bytes, of an authentication key. 35 | KeySize = 32 36 | ) 37 | 38 | // Sum generates an authenticator for m using a secret key and returns the 39 | // 32-byte digest. 40 | func Sum(m []byte, key *[KeySize]byte) *[Size]byte { 41 | mac := hmac.New(sha512.New, key[:]) 42 | mac.Write(m) 43 | out := new([KeySize]byte) 44 | copy(out[:], mac.Sum(nil)[:Size]) 45 | return out 46 | } 47 | 48 | // Verify checks that digest is a valid authenticator of message m under the 49 | // given secret key. Verify does not leak timing information. 50 | func Verify(digest []byte, m []byte, key *[32]byte) bool { 51 | if len(digest) != Size { 52 | return false 53 | } 54 | mac := hmac.New(sha512.New, key[:]) 55 | mac.Write(m) 56 | expectedMAC := mac.Sum(nil) // first 256 bits of 512-bit sum 57 | return hmac.Equal(digest, expectedMAC[:Size]) 58 | } 59 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/nacl/auth/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package auth_test 6 | 7 | import ( 8 | "encoding/hex" 9 | "fmt" 10 | 11 | "golang.org/x/crypto/nacl/auth" 12 | ) 13 | 14 | func Example() { 15 | // Load your secret key from a safe place and reuse it across multiple 16 | // Sum calls. (Obviously don't use this example key for anything 17 | // real.) If you want to convert a passphrase to a key, use a suitable 18 | // package like bcrypt or scrypt. 19 | secretKeyBytes, err := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574") 20 | if err != nil { 21 | panic(err) 22 | } 23 | 24 | var secretKey [32]byte 25 | copy(secretKey[:], secretKeyBytes) 26 | 27 | mac := auth.Sum([]byte("hello world"), &secretKey) 28 | fmt.Printf("%x\n", *mac) 29 | result := auth.Verify(mac[:], []byte("hello world"), &secretKey) 30 | fmt.Println(result) 31 | badResult := auth.Verify(mac[:], []byte("different message"), &secretKey) 32 | fmt.Println(badResult) 33 | // Output: eca5a521f3d77b63f567fb0cb6f5f2d200641bc8dada42f60c5f881260c30317 34 | // true 35 | // false 36 | } 37 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/nacl/box/box_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package box 6 | 7 | import ( 8 | "bytes" 9 | "crypto/rand" 10 | "encoding/hex" 11 | "testing" 12 | 13 | "golang.org/x/crypto/curve25519" 14 | ) 15 | 16 | func TestSealOpen(t *testing.T) { 17 | publicKey1, privateKey1, _ := GenerateKey(rand.Reader) 18 | publicKey2, privateKey2, _ := GenerateKey(rand.Reader) 19 | 20 | if *privateKey1 == *privateKey2 { 21 | t.Fatalf("private keys are equal!") 22 | } 23 | if *publicKey1 == *publicKey2 { 24 | t.Fatalf("public keys are equal!") 25 | } 26 | message := []byte("test message") 27 | var nonce [24]byte 28 | 29 | box := Seal(nil, message, &nonce, publicKey1, privateKey2) 30 | opened, ok := Open(nil, box, &nonce, publicKey2, privateKey1) 31 | if !ok { 32 | t.Fatalf("failed to open box") 33 | } 34 | 35 | if !bytes.Equal(opened, message) { 36 | t.Fatalf("got %x, want %x", opened, message) 37 | } 38 | 39 | for i := range box { 40 | box[i] ^= 0x40 41 | _, ok := Open(nil, box, &nonce, publicKey2, privateKey1) 42 | if ok { 43 | t.Fatalf("opened box with byte %d corrupted", i) 44 | } 45 | box[i] ^= 0x40 46 | } 47 | } 48 | 49 | func TestBox(t *testing.T) { 50 | var privateKey1, privateKey2 [32]byte 51 | for i := range privateKey1[:] { 52 | privateKey1[i] = 1 53 | } 54 | for i := range privateKey2[:] { 55 | privateKey2[i] = 2 56 | } 57 | 58 | var publicKey1 [32]byte 59 | curve25519.ScalarBaseMult(&publicKey1, &privateKey1) 60 | var message [64]byte 61 | for i := range message[:] { 62 | message[i] = 3 63 | } 64 | 65 | var nonce [24]byte 66 | for i := range nonce[:] { 67 | nonce[i] = 4 68 | } 69 | 70 | box := Seal(nil, message[:], &nonce, &publicKey1, &privateKey2) 71 | 72 | // expected was generated using the C implementation of NaCl. 73 | expected, _ := hex.DecodeString("78ea30b19d2341ebbdba54180f821eec265cf86312549bea8a37652a8bb94f07b78a73ed1708085e6ddd0e943bbdeb8755079a37eb31d86163ce241164a47629c0539f330b4914cd135b3855bc2a2dfc") 74 | 75 | if !bytes.Equal(box, expected) { 76 | t.Fatalf("box didn't match, got\n%x\n, expected\n%x", box, expected) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/nacl/secretbox/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package secretbox_test 6 | 7 | import ( 8 | "crypto/rand" 9 | "encoding/hex" 10 | "fmt" 11 | "io" 12 | 13 | "golang.org/x/crypto/nacl/secretbox" 14 | ) 15 | 16 | func Example() { 17 | // Load your secret key from a safe place and reuse it across multiple 18 | // Seal calls. (Obviously don't use this example key for anything 19 | // real.) If you want to convert a passphrase to a key, use a suitable 20 | // package like bcrypt or scrypt. 21 | secretKeyBytes, err := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574") 22 | if err != nil { 23 | panic(err) 24 | } 25 | 26 | var secretKey [32]byte 27 | copy(secretKey[:], secretKeyBytes) 28 | 29 | // You must use a different nonce for each message you encrypt with the 30 | // same key. Since the nonce here is 192 bits long, a random value 31 | // provides a sufficiently small probability of repeats. 32 | var nonce [24]byte 33 | if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil { 34 | panic(err) 35 | } 36 | 37 | // This encrypts "hello world" and appends the result to the nonce. 38 | encrypted := secretbox.Seal(nonce[:], []byte("hello world"), &nonce, &secretKey) 39 | 40 | // When you decrypt, you must use the same nonce and key you used to 41 | // encrypt the message. One way to achieve this is to store the nonce 42 | // alongside the encrypted message. Above, we stored the nonce in the first 43 | // 24 bytes of the encrypted text. 44 | var decryptNonce [24]byte 45 | copy(decryptNonce[:], encrypted[:24]) 46 | decrypted, ok := secretbox.Open(nil, encrypted[24:], &decryptNonce, &secretKey) 47 | if !ok { 48 | panic("decryption error") 49 | } 50 | 51 | fmt.Println(string(decrypted)) 52 | // Output: hello world 53 | } 54 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/armor/armor_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package armor 6 | 7 | import ( 8 | "bytes" 9 | "hash/adler32" 10 | "io/ioutil" 11 | "testing" 12 | ) 13 | 14 | func TestDecodeEncode(t *testing.T) { 15 | buf := bytes.NewBuffer([]byte(armorExample1)) 16 | result, err := Decode(buf) 17 | if err != nil { 18 | t.Error(err) 19 | } 20 | expectedType := "PGP SIGNATURE" 21 | if result.Type != expectedType { 22 | t.Errorf("result.Type: got:%s want:%s", result.Type, expectedType) 23 | } 24 | if len(result.Header) != 1 { 25 | t.Errorf("len(result.Header): got:%d want:1", len(result.Header)) 26 | } 27 | v, ok := result.Header["Version"] 28 | if !ok || v != "GnuPG v1.4.10 (GNU/Linux)" { 29 | t.Errorf("result.Header: got:%#v", result.Header) 30 | } 31 | 32 | contents, err := ioutil.ReadAll(result.Body) 33 | if err != nil { 34 | t.Error(err) 35 | } 36 | 37 | if adler32.Checksum(contents) != 0x27b144be { 38 | t.Errorf("contents: got: %x", contents) 39 | } 40 | 41 | buf = bytes.NewBuffer(nil) 42 | w, err := Encode(buf, result.Type, result.Header) 43 | if err != nil { 44 | t.Error(err) 45 | } 46 | _, err = w.Write(contents) 47 | if err != nil { 48 | t.Error(err) 49 | } 50 | w.Close() 51 | 52 | if !bytes.Equal(buf.Bytes(), []byte(armorExample1)) { 53 | t.Errorf("got: %s\nwant: %s", string(buf.Bytes()), armorExample1) 54 | } 55 | } 56 | 57 | func TestLongHeader(t *testing.T) { 58 | buf := bytes.NewBuffer([]byte(armorLongLine)) 59 | result, err := Decode(buf) 60 | if err != nil { 61 | t.Error(err) 62 | return 63 | } 64 | value, ok := result.Header["Version"] 65 | if !ok { 66 | t.Errorf("missing Version header") 67 | } 68 | if value != longValueExpected { 69 | t.Errorf("got: %s want: %s", value, longValueExpected) 70 | } 71 | } 72 | 73 | const armorExample1 = `-----BEGIN PGP SIGNATURE----- 74 | Version: GnuPG v1.4.10 (GNU/Linux) 75 | 76 | iJwEAAECAAYFAk1Fv/0ACgkQo01+GMIMMbsYTwQAiAw+QAaNfY6WBdplZ/uMAccm 77 | 4g+81QPmTSGHnetSb6WBiY13kVzK4HQiZH8JSkmmroMLuGeJwsRTEL4wbjRyUKEt 78 | p1xwUZDECs234F1xiG5enc5SGlRtP7foLBz9lOsjx+LEcA4sTl5/2eZR9zyFZqWW 79 | TxRjs+fJCIFuo71xb1g= 80 | =/teI 81 | -----END PGP SIGNATURE-----` 82 | 83 | const armorLongLine = `-----BEGIN PGP SIGNATURE----- 84 | Version: 0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz 85 | 86 | iQEcBAABAgAGBQJMtFESAAoJEKsQXJGvOPsVj40H/1WW6jaMXv4BW+1ueDSMDwM8 87 | kx1fLOXbVM5/Kn5LStZNt1jWWnpxdz7eq3uiqeCQjmqUoRde3YbB2EMnnwRbAhpp 88 | cacnAvy9ZQ78OTxUdNW1mhX5bS6q1MTEJnl+DcyigD70HG/yNNQD7sOPMdYQw0TA 89 | byQBwmLwmTsuZsrYqB68QyLHI+DUugn+kX6Hd2WDB62DKa2suoIUIHQQCd/ofwB3 90 | WfCYInXQKKOSxu2YOg2Eb4kLNhSMc1i9uKUWAH+sdgJh7NBgdoE4MaNtBFkHXRvv 91 | okWuf3+xA9ksp1npSY/mDvgHijmjvtpRDe6iUeqfCn8N9u9CBg8geANgaG8+QA4= 92 | =wfQG 93 | -----END PGP SIGNATURE-----` 94 | 95 | const longValueExpected = "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz" 96 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/canonical_text.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package openpgp 6 | 7 | import "hash" 8 | 9 | // NewCanonicalTextHash reformats text written to it into the canonical 10 | // form and then applies the hash h. See RFC 4880, section 5.2.1. 11 | func NewCanonicalTextHash(h hash.Hash) hash.Hash { 12 | return &canonicalTextHash{h, 0} 13 | } 14 | 15 | type canonicalTextHash struct { 16 | h hash.Hash 17 | s int 18 | } 19 | 20 | var newline = []byte{'\r', '\n'} 21 | 22 | func (cth *canonicalTextHash) Write(buf []byte) (int, error) { 23 | start := 0 24 | 25 | for i, c := range buf { 26 | switch cth.s { 27 | case 0: 28 | if c == '\r' { 29 | cth.s = 1 30 | } else if c == '\n' { 31 | cth.h.Write(buf[start:i]) 32 | cth.h.Write(newline) 33 | start = i + 1 34 | } 35 | case 1: 36 | cth.s = 0 37 | } 38 | } 39 | 40 | cth.h.Write(buf[start:]) 41 | return len(buf), nil 42 | } 43 | 44 | func (cth *canonicalTextHash) Sum(in []byte) []byte { 45 | return cth.h.Sum(in) 46 | } 47 | 48 | func (cth *canonicalTextHash) Reset() { 49 | cth.h.Reset() 50 | cth.s = 0 51 | } 52 | 53 | func (cth *canonicalTextHash) Size() int { 54 | return cth.h.Size() 55 | } 56 | 57 | func (cth *canonicalTextHash) BlockSize() int { 58 | return cth.h.BlockSize() 59 | } 60 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/canonical_text_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package openpgp 6 | 7 | import ( 8 | "bytes" 9 | "testing" 10 | ) 11 | 12 | type recordingHash struct { 13 | buf *bytes.Buffer 14 | } 15 | 16 | func (r recordingHash) Write(b []byte) (n int, err error) { 17 | return r.buf.Write(b) 18 | } 19 | 20 | func (r recordingHash) Sum(in []byte) []byte { 21 | return append(in, r.buf.Bytes()...) 22 | } 23 | 24 | func (r recordingHash) Reset() { 25 | panic("shouldn't be called") 26 | } 27 | 28 | func (r recordingHash) Size() int { 29 | panic("shouldn't be called") 30 | } 31 | 32 | func (r recordingHash) BlockSize() int { 33 | panic("shouldn't be called") 34 | } 35 | 36 | func testCanonicalText(t *testing.T, input, expected string) { 37 | r := recordingHash{bytes.NewBuffer(nil)} 38 | c := NewCanonicalTextHash(r) 39 | c.Write([]byte(input)) 40 | result := c.Sum(nil) 41 | if expected != string(result) { 42 | t.Errorf("input: %x got: %x want: %x", input, result, expected) 43 | } 44 | } 45 | 46 | func TestCanonicalText(t *testing.T) { 47 | testCanonicalText(t, "foo\n", "foo\r\n") 48 | testCanonicalText(t, "foo", "foo") 49 | testCanonicalText(t, "foo\r\n", "foo\r\n") 50 | testCanonicalText(t, "foo\r\nbar", "foo\r\nbar") 51 | testCanonicalText(t, "foo\r\nbar\n\n", "foo\r\nbar\r\n\r\n") 52 | } 53 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/elgamal/elgamal_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package elgamal 6 | 7 | import ( 8 | "bytes" 9 | "crypto/rand" 10 | "math/big" 11 | "testing" 12 | ) 13 | 14 | // This is the 1024-bit MODP group from RFC 5114, section 2.1: 15 | const primeHex = "B10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C69A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C013ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD7098488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708DF1FB2BC2E4A4371" 16 | 17 | const generatorHex = "A4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507FD6406CFF14266D31266FEA1E5C41564B777E690F5504F213160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28AD662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24855E6EEB22B3B2E5" 18 | 19 | func fromHex(hex string) *big.Int { 20 | n, ok := new(big.Int).SetString(hex, 16) 21 | if !ok { 22 | panic("failed to parse hex number") 23 | } 24 | return n 25 | } 26 | 27 | func TestEncryptDecrypt(t *testing.T) { 28 | priv := &PrivateKey{ 29 | PublicKey: PublicKey{ 30 | G: fromHex(generatorHex), 31 | P: fromHex(primeHex), 32 | }, 33 | X: fromHex("42"), 34 | } 35 | priv.Y = new(big.Int).Exp(priv.G, priv.X, priv.P) 36 | 37 | message := []byte("hello world") 38 | c1, c2, err := Encrypt(rand.Reader, &priv.PublicKey, message) 39 | if err != nil { 40 | t.Errorf("error encrypting: %s", err) 41 | } 42 | message2, err := Decrypt(priv, c1, c2) 43 | if err != nil { 44 | t.Errorf("error decrypting: %s", err) 45 | } 46 | if !bytes.Equal(message2, message) { 47 | t.Errorf("decryption failed, got: %x, want: %x", message2, message) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/errors/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package errors contains common error types for the OpenPGP packages. 6 | package errors // import "golang.org/x/crypto/openpgp/errors" 7 | 8 | import ( 9 | "strconv" 10 | ) 11 | 12 | // A StructuralError is returned when OpenPGP data is found to be syntactically 13 | // invalid. 14 | type StructuralError string 15 | 16 | func (s StructuralError) Error() string { 17 | return "openpgp: invalid data: " + string(s) 18 | } 19 | 20 | // UnsupportedError indicates that, although the OpenPGP data is valid, it 21 | // makes use of currently unimplemented features. 22 | type UnsupportedError string 23 | 24 | func (s UnsupportedError) Error() string { 25 | return "openpgp: unsupported feature: " + string(s) 26 | } 27 | 28 | // InvalidArgumentError indicates that the caller is in error and passed an 29 | // incorrect value. 30 | type InvalidArgumentError string 31 | 32 | func (i InvalidArgumentError) Error() string { 33 | return "openpgp: invalid argument: " + string(i) 34 | } 35 | 36 | // SignatureError indicates that a syntactically valid signature failed to 37 | // validate. 38 | type SignatureError string 39 | 40 | func (b SignatureError) Error() string { 41 | return "openpgp: invalid signature: " + string(b) 42 | } 43 | 44 | type keyIncorrectError int 45 | 46 | func (ki keyIncorrectError) Error() string { 47 | return "openpgp: incorrect key" 48 | } 49 | 50 | var ErrKeyIncorrect error = keyIncorrectError(0) 51 | 52 | type unknownIssuerError int 53 | 54 | func (unknownIssuerError) Error() string { 55 | return "openpgp: signature made by unknown entity" 56 | } 57 | 58 | var ErrUnknownIssuer error = unknownIssuerError(0) 59 | 60 | type keyRevokedError int 61 | 62 | func (keyRevokedError) Error() string { 63 | return "openpgp: signature made by revoked key" 64 | } 65 | 66 | var ErrKeyRevoked error = keyRevokedError(0) 67 | 68 | type UnknownPacketTypeError uint8 69 | 70 | func (upte UnknownPacketTypeError) Error() string { 71 | return "openpgp: unknown packet type: " + strconv.Itoa(int(upte)) 72 | } 73 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/compressed_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "bytes" 9 | "encoding/hex" 10 | "io" 11 | "io/ioutil" 12 | "testing" 13 | ) 14 | 15 | func TestCompressed(t *testing.T) { 16 | packet, err := Read(readerFromHex(compressedHex)) 17 | if err != nil { 18 | t.Errorf("failed to read Compressed: %s", err) 19 | return 20 | } 21 | 22 | c, ok := packet.(*Compressed) 23 | if !ok { 24 | t.Error("didn't find Compressed packet") 25 | return 26 | } 27 | 28 | contents, err := ioutil.ReadAll(c.Body) 29 | if err != nil && err != io.EOF { 30 | t.Error(err) 31 | return 32 | } 33 | 34 | expected, _ := hex.DecodeString(compressedExpectedHex) 35 | if !bytes.Equal(expected, contents) { 36 | t.Errorf("got:%x want:%x", contents, expected) 37 | } 38 | } 39 | 40 | const compressedHex = "a3013b2d90c4e02b72e25f727e5e496a5e49b11e1700" 41 | const compressedExpectedHex = "cb1062004d14c8fe636f6e74656e74732e0a" 42 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/config.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "crypto" 9 | "crypto/rand" 10 | "io" 11 | "time" 12 | ) 13 | 14 | // Config collects a number of parameters along with sensible defaults. 15 | // A nil *Config is valid and results in all default values. 16 | type Config struct { 17 | // Rand provides the source of entropy. 18 | // If nil, the crypto/rand Reader is used. 19 | Rand io.Reader 20 | // DefaultHash is the default hash function to be used. 21 | // If zero, SHA-256 is used. 22 | DefaultHash crypto.Hash 23 | // DefaultCipher is the cipher to be used. 24 | // If zero, AES-128 is used. 25 | DefaultCipher CipherFunction 26 | // Time returns the current time as the number of seconds since the 27 | // epoch. If Time is nil, time.Now is used. 28 | Time func() time.Time 29 | // DefaultCompressionAlgo is the compression algorithm to be 30 | // applied to the plaintext before encryption. If zero, no 31 | // compression is done. 32 | DefaultCompressionAlgo CompressionAlgo 33 | // CompressionConfig configures the compression settings. 34 | CompressionConfig *CompressionConfig 35 | // S2KCount is only used for symmetric encryption. It 36 | // determines the strength of the passphrase stretching when 37 | // the said passphrase is hashed to produce a key. S2KCount 38 | // should be between 1024 and 65011712, inclusive. If Config 39 | // is nil or S2KCount is 0, the value 65536 used. Not all 40 | // values in the above range can be represented. S2KCount will 41 | // be rounded up to the next representable value if it cannot 42 | // be encoded exactly. When set, it is strongly encrouraged to 43 | // use a value that is at least 65536. See RFC 4880 Section 44 | // 3.7.1.3. 45 | S2KCount int 46 | // RSABits is the number of bits in new RSA keys made with NewEntity. 47 | // If zero, then 2048 bit keys are created. 48 | RSABits int 49 | } 50 | 51 | func (c *Config) Random() io.Reader { 52 | if c == nil || c.Rand == nil { 53 | return rand.Reader 54 | } 55 | return c.Rand 56 | } 57 | 58 | func (c *Config) Hash() crypto.Hash { 59 | if c == nil || uint(c.DefaultHash) == 0 { 60 | return crypto.SHA256 61 | } 62 | return c.DefaultHash 63 | } 64 | 65 | func (c *Config) Cipher() CipherFunction { 66 | if c == nil || uint8(c.DefaultCipher) == 0 { 67 | return CipherAES128 68 | } 69 | return c.DefaultCipher 70 | } 71 | 72 | func (c *Config) Now() time.Time { 73 | if c == nil || c.Time == nil { 74 | return time.Now() 75 | } 76 | return c.Time() 77 | } 78 | 79 | func (c *Config) Compression() CompressionAlgo { 80 | if c == nil { 81 | return CompressionNone 82 | } 83 | return c.DefaultCompressionAlgo 84 | } 85 | 86 | func (c *Config) PasswordHashIterations() int { 87 | if c == nil || c.S2KCount == 0 { 88 | return 0 89 | } 90 | return c.S2KCount 91 | } 92 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/literal.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "encoding/binary" 9 | "io" 10 | ) 11 | 12 | // LiteralData represents an encrypted file. See RFC 4880, section 5.9. 13 | type LiteralData struct { 14 | IsBinary bool 15 | FileName string 16 | Time uint32 // Unix epoch time. Either creation time or modification time. 0 means undefined. 17 | Body io.Reader 18 | } 19 | 20 | // ForEyesOnly returns whether the contents of the LiteralData have been marked 21 | // as especially sensitive. 22 | func (l *LiteralData) ForEyesOnly() bool { 23 | return l.FileName == "_CONSOLE" 24 | } 25 | 26 | func (l *LiteralData) parse(r io.Reader) (err error) { 27 | var buf [256]byte 28 | 29 | _, err = readFull(r, buf[:2]) 30 | if err != nil { 31 | return 32 | } 33 | 34 | l.IsBinary = buf[0] == 'b' 35 | fileNameLen := int(buf[1]) 36 | 37 | _, err = readFull(r, buf[:fileNameLen]) 38 | if err != nil { 39 | return 40 | } 41 | 42 | l.FileName = string(buf[:fileNameLen]) 43 | 44 | _, err = readFull(r, buf[:4]) 45 | if err != nil { 46 | return 47 | } 48 | 49 | l.Time = binary.BigEndian.Uint32(buf[:4]) 50 | l.Body = r 51 | return 52 | } 53 | 54 | // SerializeLiteral serializes a literal data packet to w and returns a 55 | // WriteCloser to which the data itself can be written and which MUST be closed 56 | // on completion. The fileName is truncated to 255 bytes. 57 | func SerializeLiteral(w io.WriteCloser, isBinary bool, fileName string, time uint32) (plaintext io.WriteCloser, err error) { 58 | var buf [4]byte 59 | buf[0] = 't' 60 | if isBinary { 61 | buf[0] = 'b' 62 | } 63 | if len(fileName) > 255 { 64 | fileName = fileName[:255] 65 | } 66 | buf[1] = byte(len(fileName)) 67 | 68 | inner, err := serializeStreamHeader(w, packetTypeLiteralData) 69 | if err != nil { 70 | return 71 | } 72 | 73 | _, err = inner.Write(buf[:2]) 74 | if err != nil { 75 | return 76 | } 77 | _, err = inner.Write([]byte(fileName)) 78 | if err != nil { 79 | return 80 | } 81 | binary.BigEndian.PutUint32(buf[:], time) 82 | _, err = inner.Write(buf[:]) 83 | if err != nil { 84 | return 85 | } 86 | 87 | plaintext = inner 88 | return 89 | } 90 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/ocfb_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "bytes" 9 | "crypto/aes" 10 | "crypto/rand" 11 | "testing" 12 | ) 13 | 14 | var commonKey128 = []byte{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c} 15 | 16 | func testOCFB(t *testing.T, resync OCFBResyncOption) { 17 | block, err := aes.NewCipher(commonKey128) 18 | if err != nil { 19 | t.Error(err) 20 | return 21 | } 22 | 23 | plaintext := []byte("this is the plaintext, which is long enough to span several blocks.") 24 | randData := make([]byte, block.BlockSize()) 25 | rand.Reader.Read(randData) 26 | ocfb, prefix := NewOCFBEncrypter(block, randData, resync) 27 | ciphertext := make([]byte, len(plaintext)) 28 | ocfb.XORKeyStream(ciphertext, plaintext) 29 | 30 | ocfbdec := NewOCFBDecrypter(block, prefix, resync) 31 | if ocfbdec == nil { 32 | t.Errorf("NewOCFBDecrypter failed (resync: %t)", resync) 33 | return 34 | } 35 | plaintextCopy := make([]byte, len(plaintext)) 36 | ocfbdec.XORKeyStream(plaintextCopy, ciphertext) 37 | 38 | if !bytes.Equal(plaintextCopy, plaintext) { 39 | t.Errorf("got: %x, want: %x (resync: %t)", plaintextCopy, plaintext, resync) 40 | } 41 | } 42 | 43 | func TestOCFB(t *testing.T) { 44 | testOCFB(t, OCFBNoResync) 45 | testOCFB(t, OCFBResync) 46 | } 47 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/one_pass_signature.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "crypto" 9 | "encoding/binary" 10 | "golang.org/x/crypto/openpgp/errors" 11 | "golang.org/x/crypto/openpgp/s2k" 12 | "io" 13 | "strconv" 14 | ) 15 | 16 | // OnePassSignature represents a one-pass signature packet. See RFC 4880, 17 | // section 5.4. 18 | type OnePassSignature struct { 19 | SigType SignatureType 20 | Hash crypto.Hash 21 | PubKeyAlgo PublicKeyAlgorithm 22 | KeyId uint64 23 | IsLast bool 24 | } 25 | 26 | const onePassSignatureVersion = 3 27 | 28 | func (ops *OnePassSignature) parse(r io.Reader) (err error) { 29 | var buf [13]byte 30 | 31 | _, err = readFull(r, buf[:]) 32 | if err != nil { 33 | return 34 | } 35 | if buf[0] != onePassSignatureVersion { 36 | err = errors.UnsupportedError("one-pass-signature packet version " + strconv.Itoa(int(buf[0]))) 37 | } 38 | 39 | var ok bool 40 | ops.Hash, ok = s2k.HashIdToHash(buf[2]) 41 | if !ok { 42 | return errors.UnsupportedError("hash function: " + strconv.Itoa(int(buf[2]))) 43 | } 44 | 45 | ops.SigType = SignatureType(buf[1]) 46 | ops.PubKeyAlgo = PublicKeyAlgorithm(buf[3]) 47 | ops.KeyId = binary.BigEndian.Uint64(buf[4:12]) 48 | ops.IsLast = buf[12] != 0 49 | return 50 | } 51 | 52 | // Serialize marshals the given OnePassSignature to w. 53 | func (ops *OnePassSignature) Serialize(w io.Writer) error { 54 | var buf [13]byte 55 | buf[0] = onePassSignatureVersion 56 | buf[1] = uint8(ops.SigType) 57 | var ok bool 58 | buf[2], ok = s2k.HashToHashId(ops.Hash) 59 | if !ok { 60 | return errors.UnsupportedError("hash type: " + strconv.Itoa(int(ops.Hash))) 61 | } 62 | buf[3] = uint8(ops.PubKeyAlgo) 63 | binary.BigEndian.PutUint64(buf[4:12], ops.KeyId) 64 | if ops.IsLast { 65 | buf[12] = 1 66 | } 67 | 68 | if err := serializeHeader(w, packetTypeOnePassSignature, len(buf)); err != nil { 69 | return err 70 | } 71 | _, err := w.Write(buf[:]) 72 | return err 73 | } 74 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/opaque_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "bytes" 9 | "encoding/hex" 10 | "io" 11 | "testing" 12 | ) 13 | 14 | // Test packet.Read error handling in OpaquePacket.Parse, 15 | // which attempts to re-read an OpaquePacket as a supported 16 | // Packet type. 17 | func TestOpaqueParseReason(t *testing.T) { 18 | buf, err := hex.DecodeString(UnsupportedKeyHex) 19 | if err != nil { 20 | t.Fatal(err) 21 | } 22 | or := NewOpaqueReader(bytes.NewBuffer(buf)) 23 | count := 0 24 | badPackets := 0 25 | var uid *UserId 26 | for { 27 | op, err := or.Next() 28 | if err == io.EOF { 29 | break 30 | } else if err != nil { 31 | t.Errorf("#%d: opaque read error: %v", count, err) 32 | break 33 | } 34 | // try to parse opaque packet 35 | p, err := op.Parse() 36 | switch pkt := p.(type) { 37 | case *UserId: 38 | uid = pkt 39 | case *OpaquePacket: 40 | // If an OpaquePacket can't re-parse, packet.Read 41 | // certainly had its reasons. 42 | if pkt.Reason == nil { 43 | t.Errorf("#%d: opaque packet, no reason", count) 44 | } else { 45 | badPackets++ 46 | } 47 | } 48 | count++ 49 | } 50 | 51 | const expectedBad = 3 52 | // Test post-conditions, make sure we actually parsed packets as expected. 53 | if badPackets != expectedBad { 54 | t.Errorf("unexpected # unparseable packets: %d (want %d)", badPackets, expectedBad) 55 | } 56 | if uid == nil { 57 | t.Errorf("failed to find expected UID in unsupported keyring") 58 | } else if uid.Id != "Armin M. Warda " { 59 | t.Errorf("unexpected UID: %v", uid.Id) 60 | } 61 | } 62 | 63 | // This key material has public key and signature packet versions modified to 64 | // an unsupported value (1), so that trying to parse the OpaquePacket to 65 | // a typed packet will get an error. It also contains a GnuPG trust packet. 66 | // (Created with: od -An -t x1 pubring.gpg | xargs | sed 's/ //g') 67 | const UnsupportedKeyHex = `988d012e7a18a20000010400d6ac00d92b89c1f4396c243abb9b76d2e9673ad63483291fed88e22b82e255e441c078c6abbbf7d2d195e50b62eeaa915b85b0ec20c225ce2c64c167cacb6e711daf2e45da4a8356a059b8160e3b3628ac0dd8437b31f06d53d6e8ea4214d4a26406a6b63e1001406ef23e0bb3069fac9a99a91f77dfafd5de0f188a5da5e3c9000511b42741726d696e204d2e205761726461203c7761726461406e657068696c696d2e727568722e64653e8900950105102e8936c705d1eb399e58489901013f0e03ff5a0c4f421e34fcfa388129166420c08cd76987bcdec6f01bd0271459a85cc22048820dd4e44ac2c7d23908d540f54facf1b36b0d9c20488781ce9dca856531e76e2e846826e9951338020a03a09b57aa5faa82e9267458bd76105399885ac35af7dc1cbb6aaed7c39e1039f3b5beda2c0e916bd38560509bab81235d1a0ead83b0020000` 68 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/public_key_v3_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "bytes" 9 | "encoding/hex" 10 | "testing" 11 | "time" 12 | ) 13 | 14 | var pubKeyV3Test = struct { 15 | hexFingerprint string 16 | creationTime time.Time 17 | pubKeyAlgo PublicKeyAlgorithm 18 | keyId uint64 19 | keyIdString string 20 | keyIdShort string 21 | }{ 22 | "103BECF5BD1E837C89D19E98487767F7", 23 | time.Unix(779753634, 0), 24 | PubKeyAlgoRSA, 25 | 0xDE0F188A5DA5E3C9, 26 | "DE0F188A5DA5E3C9", 27 | "5DA5E3C9"} 28 | 29 | func TestPublicKeyV3Read(t *testing.T) { 30 | i, test := 0, pubKeyV3Test 31 | packet, err := Read(v3KeyReader(t)) 32 | if err != nil { 33 | t.Fatalf("#%d: Read error: %s", i, err) 34 | } 35 | pk, ok := packet.(*PublicKeyV3) 36 | if !ok { 37 | t.Fatalf("#%d: failed to parse, got: %#v", i, packet) 38 | } 39 | if pk.PubKeyAlgo != test.pubKeyAlgo { 40 | t.Errorf("#%d: bad public key algorithm got:%x want:%x", i, pk.PubKeyAlgo, test.pubKeyAlgo) 41 | } 42 | if !pk.CreationTime.Equal(test.creationTime) { 43 | t.Errorf("#%d: bad creation time got:%v want:%v", i, pk.CreationTime, test.creationTime) 44 | } 45 | expectedFingerprint, _ := hex.DecodeString(test.hexFingerprint) 46 | if !bytes.Equal(expectedFingerprint, pk.Fingerprint[:]) { 47 | t.Errorf("#%d: bad fingerprint got:%x want:%x", i, pk.Fingerprint[:], expectedFingerprint) 48 | } 49 | if pk.KeyId != test.keyId { 50 | t.Errorf("#%d: bad keyid got:%x want:%x", i, pk.KeyId, test.keyId) 51 | } 52 | if g, e := pk.KeyIdString(), test.keyIdString; g != e { 53 | t.Errorf("#%d: bad KeyIdString got:%q want:%q", i, g, e) 54 | } 55 | if g, e := pk.KeyIdShortString(), test.keyIdShort; g != e { 56 | t.Errorf("#%d: bad KeyIdShortString got:%q want:%q", i, g, e) 57 | } 58 | } 59 | 60 | func TestPublicKeyV3Serialize(t *testing.T) { 61 | //for i, test := range pubKeyV3Tests { 62 | i := 0 63 | packet, err := Read(v3KeyReader(t)) 64 | if err != nil { 65 | t.Fatalf("#%d: Read error: %s", i, err) 66 | } 67 | pk, ok := packet.(*PublicKeyV3) 68 | if !ok { 69 | t.Fatalf("#%d: failed to parse, got: %#v", i, packet) 70 | } 71 | var serializeBuf bytes.Buffer 72 | if err = pk.Serialize(&serializeBuf); err != nil { 73 | t.Fatalf("#%d: failed to serialize: %s", i, err) 74 | } 75 | 76 | if packet, err = Read(bytes.NewBuffer(serializeBuf.Bytes())); err != nil { 77 | t.Fatalf("#%d: Read error (from serialized data): %s", i, err) 78 | } 79 | if pk, ok = packet.(*PublicKeyV3); !ok { 80 | t.Fatalf("#%d: failed to parse serialized data, got: %#v", i, packet) 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/reader.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "golang.org/x/crypto/openpgp/errors" 9 | "io" 10 | ) 11 | 12 | // Reader reads packets from an io.Reader and allows packets to be 'unread' so 13 | // that they result from the next call to Next. 14 | type Reader struct { 15 | q []Packet 16 | readers []io.Reader 17 | } 18 | 19 | // New io.Readers are pushed when a compressed or encrypted packet is processed 20 | // and recursively treated as a new source of packets. However, a carefully 21 | // crafted packet can trigger an infinite recursive sequence of packets. See 22 | // http://mumble.net/~campbell/misc/pgp-quine 23 | // https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2013-4402 24 | // This constant limits the number of recursive packets that may be pushed. 25 | const maxReaders = 32 26 | 27 | // Next returns the most recently unread Packet, or reads another packet from 28 | // the top-most io.Reader. Unknown packet types are skipped. 29 | func (r *Reader) Next() (p Packet, err error) { 30 | if len(r.q) > 0 { 31 | p = r.q[len(r.q)-1] 32 | r.q = r.q[:len(r.q)-1] 33 | return 34 | } 35 | 36 | for len(r.readers) > 0 { 37 | p, err = Read(r.readers[len(r.readers)-1]) 38 | if err == nil { 39 | return 40 | } 41 | if err == io.EOF { 42 | r.readers = r.readers[:len(r.readers)-1] 43 | continue 44 | } 45 | if _, ok := err.(errors.UnknownPacketTypeError); !ok { 46 | return nil, err 47 | } 48 | } 49 | 50 | return nil, io.EOF 51 | } 52 | 53 | // Push causes the Reader to start reading from a new io.Reader. When an EOF 54 | // error is seen from the new io.Reader, it is popped and the Reader continues 55 | // to read from the next most recent io.Reader. Push returns a StructuralError 56 | // if pushing the reader would exceed the maximum recursion level, otherwise it 57 | // returns nil. 58 | func (r *Reader) Push(reader io.Reader) (err error) { 59 | if len(r.readers) >= maxReaders { 60 | return errors.StructuralError("too many layers of packets") 61 | } 62 | r.readers = append(r.readers, reader) 63 | return nil 64 | } 65 | 66 | // Unread causes the given Packet to be returned from the next call to Next. 67 | func (r *Reader) Unread(p Packet) { 68 | r.q = append(r.q, p) 69 | } 70 | 71 | func NewReader(r io.Reader) *Reader { 72 | return &Reader{ 73 | q: nil, 74 | readers: []io.Reader{r}, 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/signature_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "bytes" 9 | "crypto" 10 | "encoding/hex" 11 | "testing" 12 | ) 13 | 14 | func TestSignatureRead(t *testing.T) { 15 | packet, err := Read(readerFromHex(signatureDataHex)) 16 | if err != nil { 17 | t.Error(err) 18 | return 19 | } 20 | sig, ok := packet.(*Signature) 21 | if !ok || sig.SigType != SigTypeBinary || sig.PubKeyAlgo != PubKeyAlgoRSA || sig.Hash != crypto.SHA1 { 22 | t.Errorf("failed to parse, got: %#v", packet) 23 | } 24 | } 25 | 26 | func TestSignatureReserialize(t *testing.T) { 27 | packet, _ := Read(readerFromHex(signatureDataHex)) 28 | sig := packet.(*Signature) 29 | out := new(bytes.Buffer) 30 | err := sig.Serialize(out) 31 | if err != nil { 32 | t.Errorf("error reserializing: %s", err) 33 | return 34 | } 35 | 36 | expected, _ := hex.DecodeString(signatureDataHex) 37 | if !bytes.Equal(expected, out.Bytes()) { 38 | t.Errorf("output doesn't match input (got vs expected):\n%s\n%s", hex.Dump(out.Bytes()), hex.Dump(expected)) 39 | } 40 | } 41 | 42 | func TestSignUserId(t *testing.T) { 43 | sig := &Signature{ 44 | SigType: SigTypeGenericCert, 45 | PubKeyAlgo: PubKeyAlgoRSA, 46 | Hash: 0, // invalid hash function 47 | } 48 | 49 | packet, err := Read(readerFromHex(rsaPkDataHex)) 50 | if err != nil { 51 | t.Fatalf("failed to deserialize public key: %v", err) 52 | } 53 | pubKey := packet.(*PublicKey) 54 | 55 | packet, err = Read(readerFromHex(privKeyRSAHex)) 56 | if err != nil { 57 | t.Fatalf("failed to deserialize private key: %v", err) 58 | } 59 | privKey := packet.(*PrivateKey) 60 | 61 | err = sig.SignUserId("", pubKey, privKey, nil) 62 | if err == nil { 63 | t.Errorf("did not receive an error when expected") 64 | } 65 | 66 | sig.Hash = crypto.SHA256 67 | err = privKey.Decrypt([]byte("testing")) 68 | if err != nil { 69 | t.Fatalf("failed to decrypt private key: %v", err) 70 | } 71 | 72 | err = sig.SignUserId("", pubKey, privKey, nil) 73 | if err != nil { 74 | t.Errorf("failed to sign user id: %v", err) 75 | } 76 | } 77 | 78 | const signatureDataHex = "c2c05c04000102000605024cb45112000a0910ab105c91af38fb158f8d07ff5596ea368c5efe015bed6e78348c0f033c931d5f2ce5db54ce7f2a7e4b4ad64db758d65a7a71773edeab7ba2a9e0908e6a94a1175edd86c1d843279f045b021a6971a72702fcbd650efc393c5474d5b59a15f96d2eaad4c4c426797e0dcca2803ef41c6ff234d403eec38f31d610c344c06f2401c262f0993b2e66cad8a81ebc4322c723e0d4ba09fe917e8777658307ad8329adacba821420741009dfe87f007759f0982275d028a392c6ed983a0d846f890b36148c7358bdb8a516007fac760261ecd06076813831a36d0459075d1befa245ae7f7fb103d92ca759e9498fe60ef8078a39a3beda510deea251ea9f0a7f0df6ef42060f20780360686f3e400e" 79 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/signature_v3_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "bytes" 9 | "crypto" 10 | "encoding/hex" 11 | "io" 12 | "io/ioutil" 13 | "testing" 14 | 15 | "golang.org/x/crypto/openpgp/armor" 16 | ) 17 | 18 | func TestSignatureV3Read(t *testing.T) { 19 | r := v3KeyReader(t) 20 | Read(r) // Skip public key 21 | Read(r) // Skip uid 22 | packet, err := Read(r) // Signature 23 | if err != nil { 24 | t.Error(err) 25 | return 26 | } 27 | sig, ok := packet.(*SignatureV3) 28 | if !ok || sig.SigType != SigTypeGenericCert || sig.PubKeyAlgo != PubKeyAlgoRSA || sig.Hash != crypto.MD5 { 29 | t.Errorf("failed to parse, got: %#v", packet) 30 | } 31 | } 32 | 33 | func TestSignatureV3Reserialize(t *testing.T) { 34 | r := v3KeyReader(t) 35 | Read(r) // Skip public key 36 | Read(r) // Skip uid 37 | packet, err := Read(r) 38 | if err != nil { 39 | t.Error(err) 40 | return 41 | } 42 | sig := packet.(*SignatureV3) 43 | out := new(bytes.Buffer) 44 | if err = sig.Serialize(out); err != nil { 45 | t.Errorf("error reserializing: %s", err) 46 | return 47 | } 48 | expected, err := ioutil.ReadAll(v3KeyReader(t)) 49 | if err != nil { 50 | t.Error(err) 51 | return 52 | } 53 | expected = expected[4+141+4+39:] // See pgpdump offsets below, this is where the sig starts 54 | if !bytes.Equal(expected, out.Bytes()) { 55 | t.Errorf("output doesn't match input (got vs expected):\n%s\n%s", hex.Dump(out.Bytes()), hex.Dump(expected)) 56 | } 57 | } 58 | 59 | func v3KeyReader(t *testing.T) io.Reader { 60 | armorBlock, err := armor.Decode(bytes.NewBufferString(keySigV3Armor)) 61 | if err != nil { 62 | t.Fatalf("armor Decode failed: %v", err) 63 | } 64 | return armorBlock.Body 65 | } 66 | 67 | // keySigV3Armor is some V3 public key I found in an SKS dump. 68 | // Old: Public Key Packet(tag 6)(141 bytes) 69 | // Ver 4 - new 70 | // Public key creation time - Fri Sep 16 17:13:54 CDT 1994 71 | // Pub alg - unknown(pub 0) 72 | // Unknown public key(pub 0) 73 | // Old: User ID Packet(tag 13)(39 bytes) 74 | // User ID - Armin M. Warda 75 | // Old: Signature Packet(tag 2)(149 bytes) 76 | // Ver 4 - new 77 | // Sig type - unknown(05) 78 | // Pub alg - ElGamal Encrypt-Only(pub 16) 79 | // Hash alg - unknown(hash 46) 80 | // Hashed Sub: unknown(sub 81, critical)(1988 bytes) 81 | const keySigV3Armor = `-----BEGIN PGP PUBLIC KEY BLOCK----- 82 | Version: SKS 1.0.10 83 | 84 | mI0CLnoYogAAAQQA1qwA2SuJwfQ5bCQ6u5t20ulnOtY0gykf7YjiK4LiVeRBwHjGq7v30tGV 85 | 5Qti7qqRW4Ww7CDCJc4sZMFnystucR2vLkXaSoNWoFm4Fg47NiisDdhDezHwbVPW6OpCFNSi 86 | ZAamtj4QAUBu8j4LswafrJqZqR9336/V3g8Yil2l48kABRG0J0FybWluIE0uIFdhcmRhIDx3 87 | YXJkYUBuZXBoaWxpbS5ydWhyLmRlPoiVAgUQLok2xwXR6zmeWEiZAQE/DgP/WgxPQh40/Po4 88 | gSkWZCDAjNdph7zexvAb0CcUWahcwiBIgg3U5ErCx9I5CNVA9U+s8bNrDZwgSIeBzp3KhWUx 89 | 524uhGgm6ZUTOAIKA6CbV6pfqoLpJnRYvXYQU5mIWsNa99wcu2qu18OeEDnztb7aLA6Ra9OF 90 | YFCbq4EjXRoOrYM= 91 | =LPjs 92 | -----END PGP PUBLIC KEY BLOCK-----` 93 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/symmetrically_encrypted_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "bytes" 9 | "crypto/sha1" 10 | "encoding/hex" 11 | "golang.org/x/crypto/openpgp/errors" 12 | "io" 13 | "io/ioutil" 14 | "testing" 15 | ) 16 | 17 | // TestReader wraps a []byte and returns reads of a specific length. 18 | type testReader struct { 19 | data []byte 20 | stride int 21 | } 22 | 23 | func (t *testReader) Read(buf []byte) (n int, err error) { 24 | n = t.stride 25 | if n > len(t.data) { 26 | n = len(t.data) 27 | } 28 | if n > len(buf) { 29 | n = len(buf) 30 | } 31 | copy(buf, t.data) 32 | t.data = t.data[n:] 33 | if len(t.data) == 0 { 34 | err = io.EOF 35 | } 36 | return 37 | } 38 | 39 | func testMDCReader(t *testing.T) { 40 | mdcPlaintext, _ := hex.DecodeString(mdcPlaintextHex) 41 | 42 | for stride := 1; stride < len(mdcPlaintext)/2; stride++ { 43 | r := &testReader{data: mdcPlaintext, stride: stride} 44 | mdcReader := &seMDCReader{in: r, h: sha1.New()} 45 | body, err := ioutil.ReadAll(mdcReader) 46 | if err != nil { 47 | t.Errorf("stride: %d, error: %s", stride, err) 48 | continue 49 | } 50 | if !bytes.Equal(body, mdcPlaintext[:len(mdcPlaintext)-22]) { 51 | t.Errorf("stride: %d: bad contents %x", stride, body) 52 | continue 53 | } 54 | 55 | err = mdcReader.Close() 56 | if err != nil { 57 | t.Errorf("stride: %d, error on Close: %s", stride, err) 58 | } 59 | } 60 | 61 | mdcPlaintext[15] ^= 80 62 | 63 | r := &testReader{data: mdcPlaintext, stride: 2} 64 | mdcReader := &seMDCReader{in: r, h: sha1.New()} 65 | _, err := ioutil.ReadAll(mdcReader) 66 | if err != nil { 67 | t.Errorf("corruption test, error: %s", err) 68 | return 69 | } 70 | err = mdcReader.Close() 71 | if err == nil { 72 | t.Error("corruption: no error") 73 | } else if _, ok := err.(*errors.SignatureError); !ok { 74 | t.Errorf("corruption: expected SignatureError, got: %s", err) 75 | } 76 | } 77 | 78 | const mdcPlaintextHex = "a302789c3b2d93c4e0eb9aba22283539b3203335af44a134afb800c849cb4c4de10200aff40b45d31432c80cb384299a0655966d6939dfdeed1dddf980" 79 | 80 | func TestSerialize(t *testing.T) { 81 | buf := bytes.NewBuffer(nil) 82 | c := CipherAES128 83 | key := make([]byte, c.KeySize()) 84 | 85 | w, err := SerializeSymmetricallyEncrypted(buf, c, key, nil) 86 | if err != nil { 87 | t.Errorf("error from SerializeSymmetricallyEncrypted: %s", err) 88 | return 89 | } 90 | 91 | contents := []byte("hello world\n") 92 | 93 | w.Write(contents) 94 | w.Close() 95 | 96 | p, err := Read(buf) 97 | if err != nil { 98 | t.Errorf("error from Read: %s", err) 99 | return 100 | } 101 | 102 | se, ok := p.(*SymmetricallyEncrypted) 103 | if !ok { 104 | t.Errorf("didn't read a *SymmetricallyEncrypted") 105 | return 106 | } 107 | 108 | r, err := se.Decrypt(c, key) 109 | if err != nil { 110 | t.Errorf("error from Decrypt: %s", err) 111 | return 112 | } 113 | 114 | contentsCopy := bytes.NewBuffer(nil) 115 | _, err = io.Copy(contentsCopy, r) 116 | if err != nil { 117 | t.Errorf("error from io.Copy: %s", err) 118 | return 119 | } 120 | if !bytes.Equal(contentsCopy.Bytes(), contents) { 121 | t.Errorf("contents not equal got: %x want: %x", contentsCopy.Bytes(), contents) 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/userattribute.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "bytes" 9 | "image" 10 | "image/jpeg" 11 | "io" 12 | "io/ioutil" 13 | ) 14 | 15 | const UserAttrImageSubpacket = 1 16 | 17 | // UserAttribute is capable of storing other types of data about a user 18 | // beyond name, email and a text comment. In practice, user attributes are typically used 19 | // to store a signed thumbnail photo JPEG image of the user. 20 | // See RFC 4880, section 5.12. 21 | type UserAttribute struct { 22 | Contents []*OpaqueSubpacket 23 | } 24 | 25 | // NewUserAttributePhoto creates a user attribute packet 26 | // containing the given images. 27 | func NewUserAttributePhoto(photos ...image.Image) (uat *UserAttribute, err error) { 28 | uat = new(UserAttribute) 29 | for _, photo := range photos { 30 | var buf bytes.Buffer 31 | // RFC 4880, Section 5.12.1. 32 | data := []byte{ 33 | 0x10, 0x00, // Little-endian image header length (16 bytes) 34 | 0x01, // Image header version 1 35 | 0x01, // JPEG 36 | 0, 0, 0, 0, // 12 reserved octets, must be all zero. 37 | 0, 0, 0, 0, 38 | 0, 0, 0, 0} 39 | if _, err = buf.Write(data); err != nil { 40 | return 41 | } 42 | if err = jpeg.Encode(&buf, photo, nil); err != nil { 43 | return 44 | } 45 | uat.Contents = append(uat.Contents, &OpaqueSubpacket{ 46 | SubType: UserAttrImageSubpacket, 47 | Contents: buf.Bytes()}) 48 | } 49 | return 50 | } 51 | 52 | // NewUserAttribute creates a new user attribute packet containing the given subpackets. 53 | func NewUserAttribute(contents ...*OpaqueSubpacket) *UserAttribute { 54 | return &UserAttribute{Contents: contents} 55 | } 56 | 57 | func (uat *UserAttribute) parse(r io.Reader) (err error) { 58 | // RFC 4880, section 5.13 59 | b, err := ioutil.ReadAll(r) 60 | if err != nil { 61 | return 62 | } 63 | uat.Contents, err = OpaqueSubpackets(b) 64 | return 65 | } 66 | 67 | // Serialize marshals the user attribute to w in the form of an OpenPGP packet, including 68 | // header. 69 | func (uat *UserAttribute) Serialize(w io.Writer) (err error) { 70 | var buf bytes.Buffer 71 | for _, sp := range uat.Contents { 72 | sp.Serialize(&buf) 73 | } 74 | if err = serializeHeader(w, packetTypeUserAttribute, buf.Len()); err != nil { 75 | return err 76 | } 77 | _, err = w.Write(buf.Bytes()) 78 | return 79 | } 80 | 81 | // ImageData returns zero or more byte slices, each containing 82 | // JPEG File Interchange Format (JFIF), for each photo in the 83 | // the user attribute packet. 84 | func (uat *UserAttribute) ImageData() (imageData [][]byte) { 85 | for _, sp := range uat.Contents { 86 | if sp.SubType == UserAttrImageSubpacket && len(sp.Contents) > 16 { 87 | imageData = append(imageData, sp.Contents[16:]) 88 | } 89 | } 90 | return 91 | } 92 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/openpgp/packet/userid_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packet 6 | 7 | import ( 8 | "testing" 9 | ) 10 | 11 | var userIdTests = []struct { 12 | id string 13 | name, comment, email string 14 | }{ 15 | {"", "", "", ""}, 16 | {"John Smith", "John Smith", "", ""}, 17 | {"John Smith ()", "John Smith", "", ""}, 18 | {"John Smith () <>", "John Smith", "", ""}, 19 | {"(comment", "", "comment", ""}, 20 | {"(comment)", "", "comment", ""}, 21 | {" sdfk", "", "", "email"}, 23 | {" John Smith ( Comment ) asdkflj < email > lksdfj", "John Smith", "Comment", "email"}, 24 | {" John Smith < email > lksdfj", "John Smith", "", "email"}, 25 | {"("}, 50 | {"foo", "bar", "", "foo (bar)"}, 51 | {"foo", "", "baz", "foo "}, 52 | {"", "bar", "baz", "(bar) "}, 53 | {"foo", "bar", "baz", "foo (bar) "}, 54 | } 55 | 56 | func TestNewUserId(t *testing.T) { 57 | for i, test := range newUserIdTests { 58 | uid := NewUserId(test.name, test.comment, test.email) 59 | if uid == nil { 60 | t.Errorf("#%d: returned nil", i) 61 | continue 62 | } 63 | if uid.Id != test.id { 64 | t.Errorf("#%d: got '%s', want '%s'", i, uid.Id, test.id) 65 | } 66 | } 67 | } 68 | 69 | var invalidNewUserIdTests = []struct { 70 | name, comment, email string 71 | }{ 72 | {"foo(", "", ""}, 73 | {"foo<", "", ""}, 74 | {"", "bar)", ""}, 75 | {"", "bar<", ""}, 76 | {"", "", "baz>"}, 77 | {"", "", "baz)"}, 78 | {"", "", "baz\x00"}, 79 | } 80 | 81 | func TestNewUserIdWithInvalidInput(t *testing.T) { 82 | for i, test := range invalidNewUserIdTests { 83 | if uid := NewUserId(test.name, test.comment, test.email); uid != nil { 84 | t.Errorf("#%d: returned non-nil value: %#v", i, uid) 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/pbkdf2/pbkdf2.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package pbkdf2 implements the key derivation function PBKDF2 as defined in RFC 7 | 2898 / PKCS #5 v2.0. 8 | 9 | A key derivation function is useful when encrypting data based on a password 10 | or any other not-fully-random data. It uses a pseudorandom function to derive 11 | a secure encryption key based on the password. 12 | 13 | While v2.0 of the standard defines only one pseudorandom function to use, 14 | HMAC-SHA1, the drafted v2.1 specification allows use of all five FIPS Approved 15 | Hash Functions SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512 for HMAC. To 16 | choose, you can pass the `New` functions from the different SHA packages to 17 | pbkdf2.Key. 18 | */ 19 | package pbkdf2 // import "golang.org/x/crypto/pbkdf2" 20 | 21 | import ( 22 | "crypto/hmac" 23 | "hash" 24 | ) 25 | 26 | // Key derives a key from the password, salt and iteration count, returning a 27 | // []byte of length keylen that can be used as cryptographic key. The key is 28 | // derived based on the method described as PBKDF2 with the HMAC variant using 29 | // the supplied hash function. 30 | // 31 | // For example, to use a HMAC-SHA-1 based PBKDF2 key derivation function, you 32 | // can get a derived key for e.g. AES-256 (which needs a 32-byte key) by 33 | // doing: 34 | // 35 | // dk := pbkdf2.Key([]byte("some password"), salt, 4096, 32, sha1.New) 36 | // 37 | // Remember to get a good random salt. At least 8 bytes is recommended by the 38 | // RFC. 39 | // 40 | // Using a higher iteration count will increase the cost of an exhaustive 41 | // search but will also make derivation proportionally slower. 42 | func Key(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte { 43 | prf := hmac.New(h, password) 44 | hashLen := prf.Size() 45 | numBlocks := (keyLen + hashLen - 1) / hashLen 46 | 47 | var buf [4]byte 48 | dk := make([]byte, 0, numBlocks*hashLen) 49 | U := make([]byte, hashLen) 50 | for block := 1; block <= numBlocks; block++ { 51 | // N.B.: || means concatenation, ^ means XOR 52 | // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter 53 | // U_1 = PRF(password, salt || uint(i)) 54 | prf.Reset() 55 | prf.Write(salt) 56 | buf[0] = byte(block >> 24) 57 | buf[1] = byte(block >> 16) 58 | buf[2] = byte(block >> 8) 59 | buf[3] = byte(block) 60 | prf.Write(buf[:4]) 61 | dk = prf.Sum(dk) 62 | T := dk[len(dk)-hashLen:] 63 | copy(U, T) 64 | 65 | // U_n = PRF(password, U_(n-1)) 66 | for n := 2; n <= iter; n++ { 67 | prf.Reset() 68 | prf.Write(U) 69 | U = U[:0] 70 | U = prf.Sum(U) 71 | for x := range U { 72 | T[x] ^= U[x] 73 | } 74 | } 75 | } 76 | return dk[:keyLen] 77 | } 78 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/pkcs12/bmp-string.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkcs12 6 | 7 | import ( 8 | "errors" 9 | "unicode/utf16" 10 | ) 11 | 12 | // bmpString returns s encoded in UCS-2 with a zero terminator. 13 | func bmpString(s string) ([]byte, error) { 14 | // References: 15 | // https://tools.ietf.org/html/rfc7292#appendix-B.1 16 | // https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane 17 | // - non-BMP characters are encoded in UTF 16 by using a surrogate pair of 16-bit codes 18 | // EncodeRune returns 0xfffd if the rune does not need special encoding 19 | // - the above RFC provides the info that BMPStrings are NULL terminated. 20 | 21 | ret := make([]byte, 0, 2*len(s)+2) 22 | 23 | for _, r := range s { 24 | if t, _ := utf16.EncodeRune(r); t != 0xfffd { 25 | return nil, errors.New("pkcs12: string contains characters that cannot be encoded in UCS-2") 26 | } 27 | ret = append(ret, byte(r/256), byte(r%256)) 28 | } 29 | 30 | return append(ret, 0, 0), nil 31 | } 32 | 33 | func decodeBMPString(bmpString []byte) (string, error) { 34 | if len(bmpString)%2 != 0 { 35 | return "", errors.New("pkcs12: odd-length BMP string") 36 | } 37 | 38 | // strip terminator if present 39 | if l := len(bmpString); l >= 2 && bmpString[l-1] == 0 && bmpString[l-2] == 0 { 40 | bmpString = bmpString[:l-2] 41 | } 42 | 43 | s := make([]uint16, 0, len(bmpString)/2) 44 | for len(bmpString) > 0 { 45 | s = append(s, uint16(bmpString[0])<<8+uint16(bmpString[1])) 46 | bmpString = bmpString[2:] 47 | } 48 | 49 | return string(utf16.Decode(s)), nil 50 | } 51 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/pkcs12/bmp-string_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkcs12 6 | 7 | import ( 8 | "bytes" 9 | "encoding/hex" 10 | "testing" 11 | ) 12 | 13 | var bmpStringTests = []struct { 14 | in string 15 | expectedHex string 16 | shouldFail bool 17 | }{ 18 | {"", "0000", false}, 19 | // Example from https://tools.ietf.org/html/rfc7292#appendix-B. 20 | {"Beavis", "0042006500610076006900730000", false}, 21 | // Some characters from the "Letterlike Symbols Unicode block". 22 | {"\u2115 - Double-struck N", "21150020002d00200044006f00750062006c0065002d00730074007200750063006b0020004e0000", false}, 23 | // any character outside the BMP should trigger an error. 24 | {"\U0001f000 East wind (Mahjong)", "", true}, 25 | } 26 | 27 | func TestBMPString(t *testing.T) { 28 | for i, test := range bmpStringTests { 29 | expected, err := hex.DecodeString(test.expectedHex) 30 | if err != nil { 31 | t.Fatalf("#%d: failed to decode expectation", i) 32 | } 33 | 34 | out, err := bmpString(test.in) 35 | if err == nil && test.shouldFail { 36 | t.Errorf("#%d: expected to fail, but produced %x", i, out) 37 | continue 38 | } 39 | 40 | if err != nil && !test.shouldFail { 41 | t.Errorf("#%d: failed unexpectedly: %s", i, err) 42 | continue 43 | } 44 | 45 | if !test.shouldFail { 46 | if !bytes.Equal(out, expected) { 47 | t.Errorf("#%d: expected %s, got %x", i, test.expectedHex, out) 48 | continue 49 | } 50 | 51 | roundTrip, err := decodeBMPString(out) 52 | if err != nil { 53 | t.Errorf("#%d: decoding output gave an error: %s", i, err) 54 | continue 55 | } 56 | 57 | if roundTrip != test.in { 58 | t.Errorf("#%d: decoding output resulted in %q, but it should have been %q", i, roundTrip, test.in) 59 | continue 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/pkcs12/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkcs12 6 | 7 | import "errors" 8 | 9 | var ( 10 | // ErrDecryption represents a failure to decrypt the input. 11 | ErrDecryption = errors.New("pkcs12: decryption error, incorrect padding") 12 | 13 | // ErrIncorrectPassword is returned when an incorrect password is detected. 14 | // Usually, P12/PFX data is signed to be able to verify the password. 15 | ErrIncorrectPassword = errors.New("pkcs12: decryption password incorrect") 16 | ) 17 | 18 | // NotImplementedError indicates that the input is not currently supported. 19 | type NotImplementedError string 20 | 21 | func (e NotImplementedError) Error() string { 22 | return "pkcs12: " + string(e) 23 | } 24 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/pkcs12/internal/rc2/bench_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package rc2 6 | 7 | import ( 8 | "testing" 9 | ) 10 | 11 | func BenchmarkEncrypt(b *testing.B) { 12 | r, _ := New([]byte{0, 0, 0, 0, 0, 0, 0, 0}, 64) 13 | b.ResetTimer() 14 | var src [8]byte 15 | for i := 0; i < b.N; i++ { 16 | r.Encrypt(src[:], src[:]) 17 | } 18 | } 19 | 20 | func BenchmarkDecrypt(b *testing.B) { 21 | r, _ := New([]byte{0, 0, 0, 0, 0, 0, 0, 0}, 64) 22 | b.ResetTimer() 23 | var src [8]byte 24 | for i := 0; i < b.N; i++ { 25 | r.Decrypt(src[:], src[:]) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/pkcs12/internal/rc2/rc2_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package rc2 6 | 7 | import ( 8 | "bytes" 9 | "encoding/hex" 10 | "testing" 11 | ) 12 | 13 | func TestEncryptDecrypt(t *testing.T) { 14 | 15 | // TODO(dgryski): add the rest of the test vectors from the RFC 16 | var tests = []struct { 17 | key string 18 | plain string 19 | cipher string 20 | t1 int 21 | }{ 22 | { 23 | "0000000000000000", 24 | "0000000000000000", 25 | "ebb773f993278eff", 26 | 63, 27 | }, 28 | { 29 | "ffffffffffffffff", 30 | "ffffffffffffffff", 31 | "278b27e42e2f0d49", 32 | 64, 33 | }, 34 | { 35 | "3000000000000000", 36 | "1000000000000001", 37 | "30649edf9be7d2c2", 38 | 64, 39 | }, 40 | { 41 | "88", 42 | "0000000000000000", 43 | "61a8a244adacccf0", 44 | 64, 45 | }, 46 | { 47 | "88bca90e90875a", 48 | "0000000000000000", 49 | "6ccf4308974c267f", 50 | 64, 51 | }, 52 | { 53 | "88bca90e90875a7f0f79c384627bafb2", 54 | "0000000000000000", 55 | "1a807d272bbe5db1", 56 | 64, 57 | }, 58 | { 59 | "88bca90e90875a7f0f79c384627bafb2", 60 | "0000000000000000", 61 | "2269552ab0f85ca6", 62 | 128, 63 | }, 64 | { 65 | "88bca90e90875a7f0f79c384627bafb216f80a6f85920584c42fceb0be255daf1e", 66 | "0000000000000000", 67 | "5b78d3a43dfff1f1", 68 | 129, 69 | }, 70 | } 71 | 72 | for _, tt := range tests { 73 | k, _ := hex.DecodeString(tt.key) 74 | p, _ := hex.DecodeString(tt.plain) 75 | c, _ := hex.DecodeString(tt.cipher) 76 | 77 | b, _ := New(k, tt.t1) 78 | 79 | var dst [8]byte 80 | 81 | b.Encrypt(dst[:], p) 82 | 83 | if !bytes.Equal(dst[:], c) { 84 | t.Errorf("encrypt failed: got % 2x wanted % 2x\n", dst, c) 85 | } 86 | 87 | b.Decrypt(dst[:], c) 88 | 89 | if !bytes.Equal(dst[:], p) { 90 | t.Errorf("decrypt failed: got % 2x wanted % 2x\n", dst, p) 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/pkcs12/mac.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkcs12 6 | 7 | import ( 8 | "crypto/hmac" 9 | "crypto/sha1" 10 | "crypto/x509/pkix" 11 | "encoding/asn1" 12 | ) 13 | 14 | type macData struct { 15 | Mac digestInfo 16 | MacSalt []byte 17 | Iterations int `asn1:"optional,default:1"` 18 | } 19 | 20 | // from PKCS#7: 21 | type digestInfo struct { 22 | Algorithm pkix.AlgorithmIdentifier 23 | Digest []byte 24 | } 25 | 26 | var ( 27 | oidSHA1 = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26}) 28 | ) 29 | 30 | func verifyMac(macData *macData, message, password []byte) error { 31 | if !macData.Mac.Algorithm.Algorithm.Equal(oidSHA1) { 32 | return NotImplementedError("unknown digest algorithm: " + macData.Mac.Algorithm.Algorithm.String()) 33 | } 34 | 35 | key := pbkdf(sha1Sum, 20, 64, macData.MacSalt, password, macData.Iterations, 3, 20) 36 | 37 | mac := hmac.New(sha1.New, key) 38 | mac.Write(message) 39 | expectedMAC := mac.Sum(nil) 40 | 41 | if !hmac.Equal(macData.Mac.Digest, expectedMAC) { 42 | return ErrIncorrectPassword 43 | } 44 | return nil 45 | } 46 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/pkcs12/mac_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkcs12 6 | 7 | import ( 8 | "encoding/asn1" 9 | "testing" 10 | ) 11 | 12 | func TestVerifyMac(t *testing.T) { 13 | td := macData{ 14 | Mac: digestInfo{ 15 | Digest: []byte{0x18, 0x20, 0x3d, 0xff, 0x1e, 0x16, 0xf4, 0x92, 0xf2, 0xaf, 0xc8, 0x91, 0xa9, 0xba, 0xd6, 0xca, 0x9d, 0xee, 0x51, 0x93}, 16 | }, 17 | MacSalt: []byte{1, 2, 3, 4, 5, 6, 7, 8}, 18 | Iterations: 2048, 19 | } 20 | 21 | message := []byte{11, 12, 13, 14, 15} 22 | password, _ := bmpString("") 23 | 24 | td.Mac.Algorithm.Algorithm = asn1.ObjectIdentifier([]int{1, 2, 3}) 25 | err := verifyMac(&td, message, password) 26 | if _, ok := err.(NotImplementedError); !ok { 27 | t.Errorf("err: %v", err) 28 | } 29 | 30 | td.Mac.Algorithm.Algorithm = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26}) 31 | err = verifyMac(&td, message, password) 32 | if err != ErrIncorrectPassword { 33 | t.Errorf("Expected incorrect password, got err: %v", err) 34 | } 35 | 36 | password, _ = bmpString("Sesame open") 37 | err = verifyMac(&td, message, password) 38 | if err != nil { 39 | t.Errorf("err: %v", err) 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/pkcs12/pbkdf_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkcs12 6 | 7 | import ( 8 | "bytes" 9 | "testing" 10 | ) 11 | 12 | func TestThatPBKDFWorksCorrectlyForLongKeys(t *testing.T) { 13 | cipherInfo := shaWithTripleDESCBC{} 14 | 15 | salt := []byte("\xff\xff\xff\xff\xff\xff\xff\xff") 16 | password, _ := bmpString("sesame") 17 | key := cipherInfo.deriveKey(salt, password, 2048) 18 | 19 | if expected := []byte("\x7c\xd9\xfd\x3e\x2b\x3b\xe7\x69\x1a\x44\xe3\xbe\xf0\xf9\xea\x0f\xb9\xb8\x97\xd4\xe3\x25\xd9\xd1"); bytes.Compare(key, expected) != 0 { 20 | t.Fatalf("expected key '%x', but found '%x'", expected, key) 21 | } 22 | } 23 | 24 | func TestThatPBKDFHandlesLeadingZeros(t *testing.T) { 25 | // This test triggers a case where I_j (in step 6C) ends up with leading zero 26 | // byte, meaning that len(Ijb) < v (leading zeros get stripped by big.Int). 27 | // This was previously causing bug whereby certain inputs would break the 28 | // derivation and produce the wrong output. 29 | key := pbkdf(sha1Sum, 20, 64, []byte("\xf3\x7e\x05\xb5\x18\x32\x4b\x4b"), []byte("\x00\x00"), 2048, 1, 24) 30 | expected := []byte("\x00\xf7\x59\xff\x47\xd1\x4d\xd0\x36\x65\xd5\x94\x3c\xb3\xc4\xa3\x9a\x25\x55\xc0\x2a\xed\x66\xe1") 31 | if bytes.Compare(key, expected) != 0 { 32 | t.Fatalf("expected key '%x', but found '%x'", expected, key) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/pkcs12/safebags.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkcs12 6 | 7 | import ( 8 | "crypto/x509" 9 | "encoding/asn1" 10 | "errors" 11 | ) 12 | 13 | var ( 14 | // see https://tools.ietf.org/html/rfc7292#appendix-D 15 | oidCertTypeX509Certificate = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 22, 1}) 16 | oidPKCS8ShroundedKeyBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 2}) 17 | oidCertBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 3}) 18 | ) 19 | 20 | type certBag struct { 21 | Id asn1.ObjectIdentifier 22 | Data []byte `asn1:"tag:0,explicit"` 23 | } 24 | 25 | func decodePkcs8ShroudedKeyBag(asn1Data, password []byte) (privateKey interface{}, err error) { 26 | pkinfo := new(encryptedPrivateKeyInfo) 27 | if err = unmarshal(asn1Data, pkinfo); err != nil { 28 | return nil, errors.New("pkcs12: error decoding PKCS#8 shrouded key bag: " + err.Error()) 29 | } 30 | 31 | pkData, err := pbDecrypt(pkinfo, password) 32 | if err != nil { 33 | return nil, errors.New("pkcs12: error decrypting PKCS#8 shrouded key bag: " + err.Error()) 34 | } 35 | 36 | ret := new(asn1.RawValue) 37 | if err = unmarshal(pkData, ret); err != nil { 38 | return nil, errors.New("pkcs12: error unmarshaling decrypted private key: " + err.Error()) 39 | } 40 | 41 | if privateKey, err = x509.ParsePKCS8PrivateKey(pkData); err != nil { 42 | return nil, errors.New("pkcs12: error parsing PKCS#8 private key: " + err.Error()) 43 | } 44 | 45 | return privateKey, nil 46 | } 47 | 48 | func decodeCertBag(asn1Data []byte) (x509Certificates []byte, err error) { 49 | bag := new(certBag) 50 | if err := unmarshal(asn1Data, bag); err != nil { 51 | return nil, errors.New("pkcs12: error decoding cert bag: " + err.Error()) 52 | } 53 | if !bag.Id.Equal(oidCertTypeX509Certificate) { 54 | return nil, NotImplementedError("only X509 certificates are supported") 55 | } 56 | return bag.Data, nil 57 | } 58 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/poly1305/poly1305.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package poly1305 implements Poly1305 one-time message authentication code as 7 | specified in https://cr.yp.to/mac/poly1305-20050329.pdf. 8 | 9 | Poly1305 is a fast, one-time authentication function. It is infeasible for an 10 | attacker to generate an authenticator for a message without the key. However, a 11 | key must only be used for a single message. Authenticating two different 12 | messages with the same key allows an attacker to forge authenticators for other 13 | messages with the same key. 14 | 15 | Poly1305 was originally coupled with AES in order to make Poly1305-AES. AES was 16 | used with a fixed key in order to generate one-time keys from an nonce. 17 | However, in this package AES isn't used and the one-time key is specified 18 | directly. 19 | */ 20 | package poly1305 // import "golang.org/x/crypto/poly1305" 21 | 22 | import "crypto/subtle" 23 | 24 | // TagSize is the size, in bytes, of a poly1305 authenticator. 25 | const TagSize = 16 26 | 27 | // Verify returns true if mac is a valid authenticator for m with the given 28 | // key. 29 | func Verify(mac *[16]byte, m []byte, key *[32]byte) bool { 30 | var tmp [16]byte 31 | Sum(&tmp, m, key) 32 | return subtle.ConstantTimeCompare(tmp[:], mac[:]) == 1 33 | } 34 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/poly1305/sum_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build amd64,!gccgo,!appengine 6 | 7 | package poly1305 8 | 9 | // This function is implemented in sum_amd64.s 10 | //go:noescape 11 | func poly1305(out *[16]byte, m *byte, mlen uint64, key *[32]byte) 12 | 13 | // Sum generates an authenticator for m using a one-time key and puts the 14 | // 16-byte result into out. Authenticating two different messages with the same 15 | // key allows an attacker to forge messages at will. 16 | func Sum(out *[16]byte, m []byte, key *[32]byte) { 17 | var mPtr *byte 18 | if len(m) > 0 { 19 | mPtr = &m[0] 20 | } 21 | poly1305(out, mPtr, uint64(len(m)), key) 22 | } 23 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/poly1305/sum_arm.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build arm,!gccgo,!appengine,!nacl 6 | 7 | package poly1305 8 | 9 | // This function is implemented in sum_arm.s 10 | //go:noescape 11 | func poly1305_auth_armv6(out *[16]byte, m *byte, mlen uint32, key *[32]byte) 12 | 13 | // Sum generates an authenticator for m using a one-time key and puts the 14 | // 16-byte result into out. Authenticating two different messages with the same 15 | // key allows an attacker to forge messages at will. 16 | func Sum(out *[16]byte, m []byte, key *[32]byte) { 17 | var mPtr *byte 18 | if len(m) > 0 { 19 | mPtr = &m[0] 20 | } 21 | poly1305_auth_armv6(out, mPtr, uint32(len(m)), key) 22 | } 23 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ripemd160/ripemd160.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package ripemd160 implements the RIPEMD-160 hash algorithm. 6 | package ripemd160 // import "golang.org/x/crypto/ripemd160" 7 | 8 | // RIPEMD-160 is designed by by Hans Dobbertin, Antoon Bosselaers, and Bart 9 | // Preneel with specifications available at: 10 | // http://homes.esat.kuleuven.be/~cosicart/pdf/AB-9601/AB-9601.pdf. 11 | 12 | import ( 13 | "crypto" 14 | "hash" 15 | ) 16 | 17 | func init() { 18 | crypto.RegisterHash(crypto.RIPEMD160, New) 19 | } 20 | 21 | // The size of the checksum in bytes. 22 | const Size = 20 23 | 24 | // The block size of the hash algorithm in bytes. 25 | const BlockSize = 64 26 | 27 | const ( 28 | _s0 = 0x67452301 29 | _s1 = 0xefcdab89 30 | _s2 = 0x98badcfe 31 | _s3 = 0x10325476 32 | _s4 = 0xc3d2e1f0 33 | ) 34 | 35 | // digest represents the partial evaluation of a checksum. 36 | type digest struct { 37 | s [5]uint32 // running context 38 | x [BlockSize]byte // temporary buffer 39 | nx int // index into x 40 | tc uint64 // total count of bytes processed 41 | } 42 | 43 | func (d *digest) Reset() { 44 | d.s[0], d.s[1], d.s[2], d.s[3], d.s[4] = _s0, _s1, _s2, _s3, _s4 45 | d.nx = 0 46 | d.tc = 0 47 | } 48 | 49 | // New returns a new hash.Hash computing the checksum. 50 | func New() hash.Hash { 51 | result := new(digest) 52 | result.Reset() 53 | return result 54 | } 55 | 56 | func (d *digest) Size() int { return Size } 57 | 58 | func (d *digest) BlockSize() int { return BlockSize } 59 | 60 | func (d *digest) Write(p []byte) (nn int, err error) { 61 | nn = len(p) 62 | d.tc += uint64(nn) 63 | if d.nx > 0 { 64 | n := len(p) 65 | if n > BlockSize-d.nx { 66 | n = BlockSize - d.nx 67 | } 68 | for i := 0; i < n; i++ { 69 | d.x[d.nx+i] = p[i] 70 | } 71 | d.nx += n 72 | if d.nx == BlockSize { 73 | _Block(d, d.x[0:]) 74 | d.nx = 0 75 | } 76 | p = p[n:] 77 | } 78 | n := _Block(d, p) 79 | p = p[n:] 80 | if len(p) > 0 { 81 | d.nx = copy(d.x[:], p) 82 | } 83 | return 84 | } 85 | 86 | func (d0 *digest) Sum(in []byte) []byte { 87 | // Make a copy of d0 so that caller can keep writing and summing. 88 | d := *d0 89 | 90 | // Padding. Add a 1 bit and 0 bits until 56 bytes mod 64. 91 | tc := d.tc 92 | var tmp [64]byte 93 | tmp[0] = 0x80 94 | if tc%64 < 56 { 95 | d.Write(tmp[0 : 56-tc%64]) 96 | } else { 97 | d.Write(tmp[0 : 64+56-tc%64]) 98 | } 99 | 100 | // Length in bits. 101 | tc <<= 3 102 | for i := uint(0); i < 8; i++ { 103 | tmp[i] = byte(tc >> (8 * i)) 104 | } 105 | d.Write(tmp[0:8]) 106 | 107 | if d.nx != 0 { 108 | panic("d.nx != 0") 109 | } 110 | 111 | var digest [Size]byte 112 | for i, s := range d.s { 113 | digest[i*4] = byte(s) 114 | digest[i*4+1] = byte(s >> 8) 115 | digest[i*4+2] = byte(s >> 16) 116 | digest[i*4+3] = byte(s >> 24) 117 | } 118 | 119 | return append(in, digest[:]...) 120 | } 121 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ripemd160/ripemd160_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package ripemd160 6 | 7 | // Test vectors are from: 8 | // http://homes.esat.kuleuven.be/~bosselae/ripemd160.html 9 | 10 | import ( 11 | "fmt" 12 | "io" 13 | "testing" 14 | ) 15 | 16 | type mdTest struct { 17 | out string 18 | in string 19 | } 20 | 21 | var vectors = [...]mdTest{ 22 | {"9c1185a5c5e9fc54612808977ee8f548b2258d31", ""}, 23 | {"0bdc9d2d256b3ee9daae347be6f4dc835a467ffe", "a"}, 24 | {"8eb208f7e05d987a9b044a8e98c6b087f15a0bfc", "abc"}, 25 | {"5d0689ef49d2fae572b881b123a85ffa21595f36", "message digest"}, 26 | {"f71c27109c692c1b56bbdceb5b9d2865b3708dbc", "abcdefghijklmnopqrstuvwxyz"}, 27 | {"12a053384a9c0c88e405a06c27dcf49ada62eb2b", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"}, 28 | {"b0e20b6e3116640286ed3a87a5713079b21f5189", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"}, 29 | {"9b752e45573d4b39f4dbd3323cab82bf63326bfb", "12345678901234567890123456789012345678901234567890123456789012345678901234567890"}, 30 | } 31 | 32 | func TestVectors(t *testing.T) { 33 | for i := 0; i < len(vectors); i++ { 34 | tv := vectors[i] 35 | md := New() 36 | for j := 0; j < 3; j++ { 37 | if j < 2 { 38 | io.WriteString(md, tv.in) 39 | } else { 40 | io.WriteString(md, tv.in[0:len(tv.in)/2]) 41 | md.Sum(nil) 42 | io.WriteString(md, tv.in[len(tv.in)/2:]) 43 | } 44 | s := fmt.Sprintf("%x", md.Sum(nil)) 45 | if s != tv.out { 46 | t.Fatalf("RIPEMD-160[%d](%s) = %s, expected %s", j, tv.in, s, tv.out) 47 | } 48 | md.Reset() 49 | } 50 | } 51 | } 52 | 53 | func TestMillionA(t *testing.T) { 54 | md := New() 55 | for i := 0; i < 100000; i++ { 56 | io.WriteString(md, "aaaaaaaaaa") 57 | } 58 | out := "52783243c1697bdbe16d37f97f68f08325dc1528" 59 | s := fmt.Sprintf("%x", md.Sum(nil)) 60 | if s != out { 61 | t.Fatalf("RIPEMD-160 (1 million 'a') = %s, expected %s", s, out) 62 | } 63 | md.Reset() 64 | } 65 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build amd64,!appengine,!gccgo 6 | 7 | package salsa 8 | 9 | // This function is implemented in salsa2020_amd64.s. 10 | 11 | //go:noescape 12 | 13 | func salsa2020XORKeyStream(out, in *byte, n uint64, nonce, key *byte) 14 | 15 | // XORKeyStream crypts bytes from in to out using the given key and counters. 16 | // In and out must overlap entirely or not at all. Counter 17 | // contains the raw salsa20 counter bytes (both nonce and block counter). 18 | func XORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) { 19 | if len(in) == 0 { 20 | return 21 | } 22 | _ = out[len(in)-1] 23 | salsa2020XORKeyStream(&out[0], &in[0], uint64(len(in)), &counter[0], &key[0]) 24 | } 25 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/salsa20/salsa/salsa_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package salsa 6 | 7 | import "testing" 8 | 9 | func TestCore208(t *testing.T) { 10 | in := [64]byte{ 11 | 0x7e, 0x87, 0x9a, 0x21, 0x4f, 0x3e, 0xc9, 0x86, 12 | 0x7c, 0xa9, 0x40, 0xe6, 0x41, 0x71, 0x8f, 0x26, 13 | 0xba, 0xee, 0x55, 0x5b, 0x8c, 0x61, 0xc1, 0xb5, 14 | 0x0d, 0xf8, 0x46, 0x11, 0x6d, 0xcd, 0x3b, 0x1d, 15 | 0xee, 0x24, 0xf3, 0x19, 0xdf, 0x9b, 0x3d, 0x85, 16 | 0x14, 0x12, 0x1e, 0x4b, 0x5a, 0xc5, 0xaa, 0x32, 17 | 0x76, 0x02, 0x1d, 0x29, 0x09, 0xc7, 0x48, 0x29, 18 | 0xed, 0xeb, 0xc6, 0x8d, 0xb8, 0xb8, 0xc2, 0x5e} 19 | 20 | out := [64]byte{ 21 | 0xa4, 0x1f, 0x85, 0x9c, 0x66, 0x08, 0xcc, 0x99, 22 | 0x3b, 0x81, 0xca, 0xcb, 0x02, 0x0c, 0xef, 0x05, 23 | 0x04, 0x4b, 0x21, 0x81, 0xa2, 0xfd, 0x33, 0x7d, 24 | 0xfd, 0x7b, 0x1c, 0x63, 0x96, 0x68, 0x2f, 0x29, 25 | 0xb4, 0x39, 0x31, 0x68, 0xe3, 0xc9, 0xe6, 0xbc, 26 | 0xfe, 0x6b, 0xc5, 0xb7, 0xa0, 0x6d, 0x96, 0xba, 27 | 0xe4, 0x24, 0xcc, 0x10, 0x2c, 0x91, 0x74, 0x5c, 28 | 0x24, 0xad, 0x67, 0x3d, 0xc7, 0x61, 0x8f, 0x81, 29 | } 30 | 31 | Core208(&in, &in) 32 | if in != out { 33 | t.Errorf("expected %x, got %x", out, in) 34 | } 35 | } 36 | 37 | func TestOutOfBoundsWrite(t *testing.T) { 38 | // encrypted "0123456789" 39 | cipherText := []byte{170, 166, 196, 104, 175, 121, 68, 44, 174, 51} 40 | var counter [16]byte 41 | var key [32]byte 42 | want := "abcdefghij" 43 | plainText := []byte(want) 44 | defer func() { 45 | err := recover() 46 | if err == nil { 47 | t.Error("XORKeyStream expected to panic on len(dst) < len(src), but didn't") 48 | } 49 | if plainText[3] == '3' { 50 | t.Errorf("XORKeyStream did out of bounds write, want %v, got %v", want, string(plainText)) 51 | } 52 | }() 53 | XORKeyStream(plainText[:3], cipherText, &counter, &key) 54 | } 55 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/salsa20/salsa20.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package salsa20 implements the Salsa20 stream cipher as specified in https://cr.yp.to/snuffle/spec.pdf. 7 | 8 | Salsa20 differs from many other stream ciphers in that it is message orientated 9 | rather than byte orientated. Keystream blocks are not preserved between calls, 10 | therefore each side must encrypt/decrypt data with the same segmentation. 11 | 12 | Another aspect of this difference is that part of the counter is exposed as 13 | a nonce in each call. Encrypting two different messages with the same (key, 14 | nonce) pair leads to trivial plaintext recovery. This is analogous to 15 | encrypting two different messages with the same key with a traditional stream 16 | cipher. 17 | 18 | This package also implements XSalsa20: a version of Salsa20 with a 24-byte 19 | nonce as specified in https://cr.yp.to/snuffle/xsalsa-20081128.pdf. Simply 20 | passing a 24-byte slice as the nonce triggers XSalsa20. 21 | */ 22 | package salsa20 // import "golang.org/x/crypto/salsa20" 23 | 24 | // TODO(agl): implement XORKeyStream12 and XORKeyStream8 - the reduced round variants of Salsa20. 25 | 26 | import ( 27 | "golang.org/x/crypto/salsa20/salsa" 28 | ) 29 | 30 | // XORKeyStream crypts bytes from in to out using the given key and nonce. 31 | // In and out must overlap entirely or not at all. Nonce must 32 | // be either 8 or 24 bytes long. 33 | func XORKeyStream(out, in []byte, nonce []byte, key *[32]byte) { 34 | if len(out) < len(in) { 35 | in = in[:len(out)] 36 | } 37 | 38 | var subNonce [16]byte 39 | 40 | if len(nonce) == 24 { 41 | var subKey [32]byte 42 | var hNonce [16]byte 43 | copy(hNonce[:], nonce[:16]) 44 | salsa.HSalsa20(&subKey, &hNonce, key, &salsa.Sigma) 45 | copy(subNonce[:], nonce[16:]) 46 | key = &subKey 47 | } else if len(nonce) == 8 { 48 | copy(subNonce[:], nonce[:]) 49 | } else { 50 | panic("salsa20: nonce must be 8 or 24 bytes") 51 | } 52 | 53 | salsa.XORKeyStream(out, in, &subNonce, key) 54 | } 55 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/scrypt/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package scrypt_test 6 | 7 | import ( 8 | "encoding/base64" 9 | "fmt" 10 | "log" 11 | 12 | "golang.org/x/crypto/scrypt" 13 | ) 14 | 15 | func Example() { 16 | // DO NOT use this salt value; generate your own random salt. 8 bytes is 17 | // a good length. 18 | salt := []byte{0xc8, 0x28, 0xf2, 0x58, 0xa7, 0x6a, 0xad, 0x7b} 19 | 20 | dk, err := scrypt.Key([]byte("some password"), salt, 1<<15, 8, 1, 32) 21 | if err != nil { 22 | log.Fatal(err) 23 | } 24 | fmt.Println(base64.StdEncoding.EncodeToString(dk)) 25 | // Output: lGnMz8io0AUkfzn6Pls1qX20Vs7PGN6sbYQ2TQgY12M= 26 | } 27 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/sha3/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package sha3 implements the SHA-3 fixed-output-length hash functions and 6 | // the SHAKE variable-output-length hash functions defined by FIPS-202. 7 | // 8 | // Both types of hash function use the "sponge" construction and the Keccak 9 | // permutation. For a detailed specification see http://keccak.noekeon.org/ 10 | // 11 | // 12 | // Guidance 13 | // 14 | // If you aren't sure what function you need, use SHAKE256 with at least 64 15 | // bytes of output. The SHAKE instances are faster than the SHA3 instances; 16 | // the latter have to allocate memory to conform to the hash.Hash interface. 17 | // 18 | // If you need a secret-key MAC (message authentication code), prepend the 19 | // secret key to the input, hash with SHAKE256 and read at least 32 bytes of 20 | // output. 21 | // 22 | // 23 | // Security strengths 24 | // 25 | // The SHA3-x (x equals 224, 256, 384, or 512) functions have a security 26 | // strength against preimage attacks of x bits. Since they only produce "x" 27 | // bits of output, their collision-resistance is only "x/2" bits. 28 | // 29 | // The SHAKE-256 and -128 functions have a generic security strength of 256 and 30 | // 128 bits against all attacks, provided that at least 2x bits of their output 31 | // is used. Requesting more than 64 or 32 bytes of output, respectively, does 32 | // not increase the collision-resistance of the SHAKE functions. 33 | // 34 | // 35 | // The sponge construction 36 | // 37 | // A sponge builds a pseudo-random function from a public pseudo-random 38 | // permutation, by applying the permutation to a state of "rate + capacity" 39 | // bytes, but hiding "capacity" of the bytes. 40 | // 41 | // A sponge starts out with a zero state. To hash an input using a sponge, up 42 | // to "rate" bytes of the input are XORed into the sponge's state. The sponge 43 | // is then "full" and the permutation is applied to "empty" it. This process is 44 | // repeated until all the input has been "absorbed". The input is then padded. 45 | // The digest is "squeezed" from the sponge in the same way, except that output 46 | // output is copied out instead of input being XORed in. 47 | // 48 | // A sponge is parameterized by its generic security strength, which is equal 49 | // to half its capacity; capacity + rate is equal to the permutation's width. 50 | // Since the KeccakF-1600 permutation is 1600 bits (200 bytes) wide, this means 51 | // that the security strength of a sponge instance is equal to (1600 - bitrate) / 2. 52 | // 53 | // 54 | // Recommendations 55 | // 56 | // The SHAKE functions are recommended for most new uses. They can produce 57 | // output of arbitrary length. SHAKE256, with an output length of at least 58 | // 64 bytes, provides 256-bit security against all attacks. The Keccak team 59 | // recommends it for most applications upgrading from SHA2-512. (NIST chose a 60 | // much stronger, but much slower, sponge instance for SHA3-512.) 61 | // 62 | // The SHA-3 functions are "drop-in" replacements for the SHA-2 functions. 63 | // They produce output of the same length, with the same security strengths 64 | // against all attacks. This means, in particular, that SHA3-256 only has 65 | // 128-bit collision resistance, because its output length is 32 bytes. 66 | package sha3 // import "golang.org/x/crypto/sha3" 67 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/sha3/hashes.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package sha3 6 | 7 | // This file provides functions for creating instances of the SHA-3 8 | // and SHAKE hash functions, as well as utility functions for hashing 9 | // bytes. 10 | 11 | import ( 12 | "hash" 13 | ) 14 | 15 | // New224 creates a new SHA3-224 hash. 16 | // Its generic security strength is 224 bits against preimage attacks, 17 | // and 112 bits against collision attacks. 18 | func New224() hash.Hash { return &state{rate: 144, outputLen: 28, dsbyte: 0x06} } 19 | 20 | // New256 creates a new SHA3-256 hash. 21 | // Its generic security strength is 256 bits against preimage attacks, 22 | // and 128 bits against collision attacks. 23 | func New256() hash.Hash { return &state{rate: 136, outputLen: 32, dsbyte: 0x06} } 24 | 25 | // New384 creates a new SHA3-384 hash. 26 | // Its generic security strength is 384 bits against preimage attacks, 27 | // and 192 bits against collision attacks. 28 | func New384() hash.Hash { return &state{rate: 104, outputLen: 48, dsbyte: 0x06} } 29 | 30 | // New512 creates a new SHA3-512 hash. 31 | // Its generic security strength is 512 bits against preimage attacks, 32 | // and 256 bits against collision attacks. 33 | func New512() hash.Hash { return &state{rate: 72, outputLen: 64, dsbyte: 0x06} } 34 | 35 | // Sum224 returns the SHA3-224 digest of the data. 36 | func Sum224(data []byte) (digest [28]byte) { 37 | h := New224() 38 | h.Write(data) 39 | h.Sum(digest[:0]) 40 | return 41 | } 42 | 43 | // Sum256 returns the SHA3-256 digest of the data. 44 | func Sum256(data []byte) (digest [32]byte) { 45 | h := New256() 46 | h.Write(data) 47 | h.Sum(digest[:0]) 48 | return 49 | } 50 | 51 | // Sum384 returns the SHA3-384 digest of the data. 52 | func Sum384(data []byte) (digest [48]byte) { 53 | h := New384() 54 | h.Write(data) 55 | h.Sum(digest[:0]) 56 | return 57 | } 58 | 59 | // Sum512 returns the SHA3-512 digest of the data. 60 | func Sum512(data []byte) (digest [64]byte) { 61 | h := New512() 62 | h.Write(data) 63 | h.Sum(digest[:0]) 64 | return 65 | } 66 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/sha3/keccakf_amd64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build amd64,!appengine,!gccgo 6 | 7 | package sha3 8 | 9 | // This function is implemented in keccakf_amd64.s. 10 | 11 | //go:noescape 12 | 13 | func keccakF1600(a *[25]uint64) 14 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/sha3/register.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.4 6 | 7 | package sha3 8 | 9 | import ( 10 | "crypto" 11 | ) 12 | 13 | func init() { 14 | crypto.RegisterHash(crypto.SHA3_224, New224) 15 | crypto.RegisterHash(crypto.SHA3_256, New256) 16 | crypto.RegisterHash(crypto.SHA3_384, New384) 17 | crypto.RegisterHash(crypto.SHA3_512, New512) 18 | } 19 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/sha3/shake.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package sha3 6 | 7 | // This file defines the ShakeHash interface, and provides 8 | // functions for creating SHAKE instances, as well as utility 9 | // functions for hashing bytes to arbitrary-length output. 10 | 11 | import ( 12 | "io" 13 | ) 14 | 15 | // ShakeHash defines the interface to hash functions that 16 | // support arbitrary-length output. 17 | type ShakeHash interface { 18 | // Write absorbs more data into the hash's state. It panics if input is 19 | // written to it after output has been read from it. 20 | io.Writer 21 | 22 | // Read reads more output from the hash; reading affects the hash's 23 | // state. (ShakeHash.Read is thus very different from Hash.Sum) 24 | // It never returns an error. 25 | io.Reader 26 | 27 | // Clone returns a copy of the ShakeHash in its current state. 28 | Clone() ShakeHash 29 | 30 | // Reset resets the ShakeHash to its initial state. 31 | Reset() 32 | } 33 | 34 | func (d *state) Clone() ShakeHash { 35 | return d.clone() 36 | } 37 | 38 | // NewShake128 creates a new SHAKE128 variable-output-length ShakeHash. 39 | // Its generic security strength is 128 bits against all attacks if at 40 | // least 32 bytes of its output are used. 41 | func NewShake128() ShakeHash { return &state{rate: 168, dsbyte: 0x1f} } 42 | 43 | // NewShake256 creates a new SHAKE128 variable-output-length ShakeHash. 44 | // Its generic security strength is 256 bits against all attacks if 45 | // at least 64 bytes of its output are used. 46 | func NewShake256() ShakeHash { return &state{rate: 136, dsbyte: 0x1f} } 47 | 48 | // ShakeSum128 writes an arbitrary-length digest of data into hash. 49 | func ShakeSum128(hash, data []byte) { 50 | h := NewShake128() 51 | h.Write(data) 52 | h.Read(hash) 53 | } 54 | 55 | // ShakeSum256 writes an arbitrary-length digest of data into hash. 56 | func ShakeSum256(hash, data []byte) { 57 | h := NewShake256() 58 | h.Write(data) 59 | h.Read(hash) 60 | } 61 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/sha3/testdata/keccakKats.json.deflate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qq906907952/go_proxy/d750932506068316b6031e68699c160e87361b59/src/golang.org/x/crypto/sha3/testdata/keccakKats.json.deflate -------------------------------------------------------------------------------- /src/golang.org/x/crypto/sha3/xor.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !amd64,!386,!ppc64le appengine 6 | 7 | package sha3 8 | 9 | var ( 10 | xorIn = xorInGeneric 11 | copyOut = copyOutGeneric 12 | xorInUnaligned = xorInGeneric 13 | copyOutUnaligned = copyOutGeneric 14 | ) 15 | 16 | const xorImplementationUnaligned = "generic" 17 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/sha3/xor_generic.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package sha3 6 | 7 | import "encoding/binary" 8 | 9 | // xorInGeneric xors the bytes in buf into the state; it 10 | // makes no non-portable assumptions about memory layout 11 | // or alignment. 12 | func xorInGeneric(d *state, buf []byte) { 13 | n := len(buf) / 8 14 | 15 | for i := 0; i < n; i++ { 16 | a := binary.LittleEndian.Uint64(buf) 17 | d.a[i] ^= a 18 | buf = buf[8:] 19 | } 20 | } 21 | 22 | // copyOutGeneric copies ulint64s to a byte buffer. 23 | func copyOutGeneric(d *state, b []byte) { 24 | for i := 0; len(b) >= 8; i++ { 25 | binary.LittleEndian.PutUint64(b, d.a[i]) 26 | b = b[8:] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/sha3/xor_unaligned.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build amd64 386 ppc64le 6 | // +build !appengine 7 | 8 | package sha3 9 | 10 | import "unsafe" 11 | 12 | func xorInUnaligned(d *state, buf []byte) { 13 | bw := (*[maxRate / 8]uint64)(unsafe.Pointer(&buf[0])) 14 | n := len(buf) 15 | if n >= 72 { 16 | d.a[0] ^= bw[0] 17 | d.a[1] ^= bw[1] 18 | d.a[2] ^= bw[2] 19 | d.a[3] ^= bw[3] 20 | d.a[4] ^= bw[4] 21 | d.a[5] ^= bw[5] 22 | d.a[6] ^= bw[6] 23 | d.a[7] ^= bw[7] 24 | d.a[8] ^= bw[8] 25 | } 26 | if n >= 104 { 27 | d.a[9] ^= bw[9] 28 | d.a[10] ^= bw[10] 29 | d.a[11] ^= bw[11] 30 | d.a[12] ^= bw[12] 31 | } 32 | if n >= 136 { 33 | d.a[13] ^= bw[13] 34 | d.a[14] ^= bw[14] 35 | d.a[15] ^= bw[15] 36 | d.a[16] ^= bw[16] 37 | } 38 | if n >= 144 { 39 | d.a[17] ^= bw[17] 40 | } 41 | if n >= 168 { 42 | d.a[18] ^= bw[18] 43 | d.a[19] ^= bw[19] 44 | d.a[20] ^= bw[20] 45 | } 46 | } 47 | 48 | func copyOutUnaligned(d *state, buf []byte) { 49 | ab := (*[maxRate]uint8)(unsafe.Pointer(&d.a[0])) 50 | copy(buf, ab[:]) 51 | } 52 | 53 | var ( 54 | xorIn = xorInUnaligned 55 | copyOut = copyOutUnaligned 56 | ) 57 | 58 | const xorImplementationUnaligned = "unaligned" 59 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/agent/example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package agent_test 6 | 7 | import ( 8 | "log" 9 | "net" 10 | "os" 11 | 12 | "golang.org/x/crypto/ssh" 13 | "golang.org/x/crypto/ssh/agent" 14 | ) 15 | 16 | func ExampleClientAgent() { 17 | // ssh-agent has a UNIX socket under $SSH_AUTH_SOCK 18 | socket := os.Getenv("SSH_AUTH_SOCK") 19 | conn, err := net.Dial("unix", socket) 20 | if err != nil { 21 | log.Fatalf("net.Dial: %v", err) 22 | } 23 | agentClient := agent.NewClient(conn) 24 | config := &ssh.ClientConfig{ 25 | User: "username", 26 | Auth: []ssh.AuthMethod{ 27 | // Use a callback rather than PublicKeys 28 | // so we only consult the agent once the remote server 29 | // wants it. 30 | ssh.PublicKeysCallback(agentClient.Signers), 31 | }, 32 | HostKeyCallback: ssh.InsecureIgnoreHostKey(), 33 | } 34 | 35 | sshc, err := ssh.Dial("tcp", "localhost:22", config) 36 | if err != nil { 37 | log.Fatalf("Dial: %v", err) 38 | } 39 | // .. use sshc 40 | sshc.Close() 41 | } 42 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/agent/forward.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package agent 6 | 7 | import ( 8 | "errors" 9 | "io" 10 | "net" 11 | "sync" 12 | 13 | "golang.org/x/crypto/ssh" 14 | ) 15 | 16 | // RequestAgentForwarding sets up agent forwarding for the session. 17 | // ForwardToAgent or ForwardToRemote should be called to route 18 | // the authentication requests. 19 | func RequestAgentForwarding(session *ssh.Session) error { 20 | ok, err := session.SendRequest("auth-agent-req@openssh.com", true, nil) 21 | if err != nil { 22 | return err 23 | } 24 | if !ok { 25 | return errors.New("forwarding request denied") 26 | } 27 | return nil 28 | } 29 | 30 | // ForwardToAgent routes authentication requests to the given keyring. 31 | func ForwardToAgent(client *ssh.Client, keyring Agent) error { 32 | channels := client.HandleChannelOpen(channelType) 33 | if channels == nil { 34 | return errors.New("agent: already have handler for " + channelType) 35 | } 36 | 37 | go func() { 38 | for ch := range channels { 39 | channel, reqs, err := ch.Accept() 40 | if err != nil { 41 | continue 42 | } 43 | go ssh.DiscardRequests(reqs) 44 | go func() { 45 | ServeAgent(keyring, channel) 46 | channel.Close() 47 | }() 48 | } 49 | }() 50 | return nil 51 | } 52 | 53 | const channelType = "auth-agent@openssh.com" 54 | 55 | // ForwardToRemote routes authentication requests to the ssh-agent 56 | // process serving on the given unix socket. 57 | func ForwardToRemote(client *ssh.Client, addr string) error { 58 | channels := client.HandleChannelOpen(channelType) 59 | if channels == nil { 60 | return errors.New("agent: already have handler for " + channelType) 61 | } 62 | conn, err := net.Dial("unix", addr) 63 | if err != nil { 64 | return err 65 | } 66 | conn.Close() 67 | 68 | go func() { 69 | for ch := range channels { 70 | channel, reqs, err := ch.Accept() 71 | if err != nil { 72 | continue 73 | } 74 | go ssh.DiscardRequests(reqs) 75 | go forwardUnixSocket(channel, addr) 76 | } 77 | }() 78 | return nil 79 | } 80 | 81 | func forwardUnixSocket(channel ssh.Channel, addr string) { 82 | conn, err := net.Dial("unix", addr) 83 | if err != nil { 84 | return 85 | } 86 | 87 | var wg sync.WaitGroup 88 | wg.Add(2) 89 | go func() { 90 | io.Copy(conn, channel) 91 | conn.(*net.UnixConn).CloseWrite() 92 | wg.Done() 93 | }() 94 | go func() { 95 | io.Copy(channel, conn) 96 | channel.CloseWrite() 97 | wg.Done() 98 | }() 99 | 100 | wg.Wait() 101 | conn.Close() 102 | channel.Close() 103 | } 104 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/agent/keyring_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package agent 6 | 7 | import "testing" 8 | 9 | func addTestKey(t *testing.T, a Agent, keyName string) { 10 | err := a.Add(AddedKey{ 11 | PrivateKey: testPrivateKeys[keyName], 12 | Comment: keyName, 13 | }) 14 | if err != nil { 15 | t.Fatalf("failed to add key %q: %v", keyName, err) 16 | } 17 | } 18 | 19 | func removeTestKey(t *testing.T, a Agent, keyName string) { 20 | err := a.Remove(testPublicKeys[keyName]) 21 | if err != nil { 22 | t.Fatalf("failed to remove key %q: %v", keyName, err) 23 | } 24 | } 25 | 26 | func validateListedKeys(t *testing.T, a Agent, expectedKeys []string) { 27 | listedKeys, err := a.List() 28 | if err != nil { 29 | t.Fatalf("failed to list keys: %v", err) 30 | return 31 | } 32 | actualKeys := make(map[string]bool) 33 | for _, key := range listedKeys { 34 | actualKeys[key.Comment] = true 35 | } 36 | 37 | matchedKeys := make(map[string]bool) 38 | for _, expectedKey := range expectedKeys { 39 | if !actualKeys[expectedKey] { 40 | t.Fatalf("expected key %q, but was not found", expectedKey) 41 | } else { 42 | matchedKeys[expectedKey] = true 43 | } 44 | } 45 | 46 | for actualKey := range actualKeys { 47 | if !matchedKeys[actualKey] { 48 | t.Fatalf("key %q was found, but was not expected", actualKey) 49 | } 50 | } 51 | } 52 | 53 | func TestKeyringAddingAndRemoving(t *testing.T) { 54 | keyNames := []string{"dsa", "ecdsa", "rsa", "user"} 55 | 56 | // add all test private keys 57 | k := NewKeyring() 58 | for _, keyName := range keyNames { 59 | addTestKey(t, k, keyName) 60 | } 61 | validateListedKeys(t, k, keyNames) 62 | 63 | // remove a key in the middle 64 | keyToRemove := keyNames[1] 65 | keyNames = append(keyNames[:1], keyNames[2:]...) 66 | 67 | removeTestKey(t, k, keyToRemove) 68 | validateListedKeys(t, k, keyNames) 69 | 70 | // remove all keys 71 | err := k.RemoveAll() 72 | if err != nil { 73 | t.Fatalf("failed to remove all keys: %v", err) 74 | } 75 | validateListedKeys(t, k, []string{}) 76 | } 77 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/agent/testdata_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // IMPLEMENTATION NOTE: To avoid a package loop, this file is in three places: 6 | // ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three 7 | // instances. 8 | 9 | package agent 10 | 11 | import ( 12 | "crypto/rand" 13 | "fmt" 14 | 15 | "golang.org/x/crypto/ssh" 16 | "golang.org/x/crypto/ssh/testdata" 17 | ) 18 | 19 | var ( 20 | testPrivateKeys map[string]interface{} 21 | testSigners map[string]ssh.Signer 22 | testPublicKeys map[string]ssh.PublicKey 23 | ) 24 | 25 | func init() { 26 | var err error 27 | 28 | n := len(testdata.PEMBytes) 29 | testPrivateKeys = make(map[string]interface{}, n) 30 | testSigners = make(map[string]ssh.Signer, n) 31 | testPublicKeys = make(map[string]ssh.PublicKey, n) 32 | for t, k := range testdata.PEMBytes { 33 | testPrivateKeys[t], err = ssh.ParseRawPrivateKey(k) 34 | if err != nil { 35 | panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) 36 | } 37 | testSigners[t], err = ssh.NewSignerFromKey(testPrivateKeys[t]) 38 | if err != nil { 39 | panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) 40 | } 41 | testPublicKeys[t] = testSigners[t].PublicKey() 42 | } 43 | 44 | // Create a cert and sign it for use in tests. 45 | testCert := &ssh.Certificate{ 46 | Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil 47 | ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage 48 | ValidAfter: 0, // unix epoch 49 | ValidBefore: ssh.CertTimeInfinity, // The end of currently representable time. 50 | Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil 51 | Key: testPublicKeys["ecdsa"], 52 | SignatureKey: testPublicKeys["rsa"], 53 | Permissions: ssh.Permissions{ 54 | CriticalOptions: map[string]string{}, 55 | Extensions: map[string]string{}, 56 | }, 57 | } 58 | testCert.SignCert(rand.Reader, testSigners["rsa"]) 59 | testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] 60 | testSigners["cert"], err = ssh.NewCertSigner(testCert, testSigners["ecdsa"]) 61 | if err != nil { 62 | panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/benchmark_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package ssh 6 | 7 | import ( 8 | "errors" 9 | "io" 10 | "net" 11 | "testing" 12 | ) 13 | 14 | type server struct { 15 | *ServerConn 16 | chans <-chan NewChannel 17 | } 18 | 19 | func newServer(c net.Conn, conf *ServerConfig) (*server, error) { 20 | sconn, chans, reqs, err := NewServerConn(c, conf) 21 | if err != nil { 22 | return nil, err 23 | } 24 | go DiscardRequests(reqs) 25 | return &server{sconn, chans}, nil 26 | } 27 | 28 | func (s *server) Accept() (NewChannel, error) { 29 | n, ok := <-s.chans 30 | if !ok { 31 | return nil, io.EOF 32 | } 33 | return n, nil 34 | } 35 | 36 | func sshPipe() (Conn, *server, error) { 37 | c1, c2, err := netPipe() 38 | if err != nil { 39 | return nil, nil, err 40 | } 41 | 42 | clientConf := ClientConfig{ 43 | User: "user", 44 | } 45 | serverConf := ServerConfig{ 46 | NoClientAuth: true, 47 | } 48 | serverConf.AddHostKey(testSigners["ecdsa"]) 49 | done := make(chan *server, 1) 50 | go func() { 51 | server, err := newServer(c2, &serverConf) 52 | if err != nil { 53 | done <- nil 54 | } 55 | done <- server 56 | }() 57 | 58 | client, _, reqs, err := NewClientConn(c1, "", &clientConf) 59 | if err != nil { 60 | return nil, nil, err 61 | } 62 | 63 | server := <-done 64 | if server == nil { 65 | return nil, nil, errors.New("server handshake failed.") 66 | } 67 | go DiscardRequests(reqs) 68 | 69 | return client, server, nil 70 | } 71 | 72 | func BenchmarkEndToEnd(b *testing.B) { 73 | b.StopTimer() 74 | 75 | client, server, err := sshPipe() 76 | if err != nil { 77 | b.Fatalf("sshPipe: %v", err) 78 | } 79 | 80 | defer client.Close() 81 | defer server.Close() 82 | 83 | size := (1 << 20) 84 | input := make([]byte, size) 85 | output := make([]byte, size) 86 | b.SetBytes(int64(size)) 87 | done := make(chan int, 1) 88 | 89 | go func() { 90 | newCh, err := server.Accept() 91 | if err != nil { 92 | b.Fatalf("Client: %v", err) 93 | } 94 | ch, incoming, err := newCh.Accept() 95 | go DiscardRequests(incoming) 96 | for i := 0; i < b.N; i++ { 97 | if _, err := io.ReadFull(ch, output); err != nil { 98 | b.Fatalf("ReadFull: %v", err) 99 | } 100 | } 101 | ch.Close() 102 | done <- 1 103 | }() 104 | 105 | ch, in, err := client.OpenChannel("speed", nil) 106 | if err != nil { 107 | b.Fatalf("OpenChannel: %v", err) 108 | } 109 | go DiscardRequests(in) 110 | 111 | b.ResetTimer() 112 | b.StartTimer() 113 | for i := 0; i < b.N; i++ { 114 | if _, err := ch.Write(input); err != nil { 115 | b.Fatalf("WriteFull: %v", err) 116 | } 117 | } 118 | ch.Close() 119 | b.StopTimer() 120 | 121 | <-done 122 | } 123 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/buffer.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package ssh 6 | 7 | import ( 8 | "io" 9 | "sync" 10 | ) 11 | 12 | // buffer provides a linked list buffer for data exchange 13 | // between producer and consumer. Theoretically the buffer is 14 | // of unlimited capacity as it does no allocation of its own. 15 | type buffer struct { 16 | // protects concurrent access to head, tail and closed 17 | *sync.Cond 18 | 19 | head *element // the buffer that will be read first 20 | tail *element // the buffer that will be read last 21 | 22 | closed bool 23 | } 24 | 25 | // An element represents a single link in a linked list. 26 | type element struct { 27 | buf []byte 28 | next *element 29 | } 30 | 31 | // newBuffer returns an empty buffer that is not closed. 32 | func newBuffer() *buffer { 33 | e := new(element) 34 | b := &buffer{ 35 | Cond: newCond(), 36 | head: e, 37 | tail: e, 38 | } 39 | return b 40 | } 41 | 42 | // write makes buf available for Read to receive. 43 | // buf must not be modified after the call to write. 44 | func (b *buffer) write(buf []byte) { 45 | b.Cond.L.Lock() 46 | e := &element{buf: buf} 47 | b.tail.next = e 48 | b.tail = e 49 | b.Cond.Signal() 50 | b.Cond.L.Unlock() 51 | } 52 | 53 | // eof closes the buffer. Reads from the buffer once all 54 | // the data has been consumed will receive io.EOF. 55 | func (b *buffer) eof() { 56 | b.Cond.L.Lock() 57 | b.closed = true 58 | b.Cond.Signal() 59 | b.Cond.L.Unlock() 60 | } 61 | 62 | // Read reads data from the internal buffer in buf. Reads will block 63 | // if no data is available, or until the buffer is closed. 64 | func (b *buffer) Read(buf []byte) (n int, err error) { 65 | b.Cond.L.Lock() 66 | defer b.Cond.L.Unlock() 67 | 68 | for len(buf) > 0 { 69 | // if there is data in b.head, copy it 70 | if len(b.head.buf) > 0 { 71 | r := copy(buf, b.head.buf) 72 | buf, b.head.buf = buf[r:], b.head.buf[r:] 73 | n += r 74 | continue 75 | } 76 | // if there is a next buffer, make it the head 77 | if len(b.head.buf) == 0 && b.head != b.tail { 78 | b.head = b.head.next 79 | continue 80 | } 81 | 82 | // if at least one byte has been copied, return 83 | if n > 0 { 84 | break 85 | } 86 | 87 | // if nothing was read, and there is nothing outstanding 88 | // check to see if the buffer is closed. 89 | if b.closed { 90 | err = io.EOF 91 | break 92 | } 93 | // out of buffers, wait for producer 94 | b.Cond.Wait() 95 | } 96 | return 97 | } 98 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/buffer_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package ssh 6 | 7 | import ( 8 | "io" 9 | "testing" 10 | ) 11 | 12 | var alphabet = []byte("abcdefghijklmnopqrstuvwxyz") 13 | 14 | func TestBufferReadwrite(t *testing.T) { 15 | b := newBuffer() 16 | b.write(alphabet[:10]) 17 | r, _ := b.Read(make([]byte, 10)) 18 | if r != 10 { 19 | t.Fatalf("Expected written == read == 10, written: 10, read %d", r) 20 | } 21 | 22 | b = newBuffer() 23 | b.write(alphabet[:5]) 24 | r, _ = b.Read(make([]byte, 10)) 25 | if r != 5 { 26 | t.Fatalf("Expected written == read == 5, written: 5, read %d", r) 27 | } 28 | 29 | b = newBuffer() 30 | b.write(alphabet[:10]) 31 | r, _ = b.Read(make([]byte, 5)) 32 | if r != 5 { 33 | t.Fatalf("Expected written == 10, read == 5, written: 10, read %d", r) 34 | } 35 | 36 | b = newBuffer() 37 | b.write(alphabet[:5]) 38 | b.write(alphabet[5:15]) 39 | r, _ = b.Read(make([]byte, 10)) 40 | r2, _ := b.Read(make([]byte, 10)) 41 | if r != 10 || r2 != 5 || 15 != r+r2 { 42 | t.Fatal("Expected written == read == 15") 43 | } 44 | } 45 | 46 | func TestBufferClose(t *testing.T) { 47 | b := newBuffer() 48 | b.write(alphabet[:10]) 49 | b.eof() 50 | _, err := b.Read(make([]byte, 5)) 51 | if err != nil { 52 | t.Fatal("expected read of 5 to not return EOF") 53 | } 54 | b = newBuffer() 55 | b.write(alphabet[:10]) 56 | b.eof() 57 | r, err := b.Read(make([]byte, 5)) 58 | r2, err2 := b.Read(make([]byte, 10)) 59 | if r != 5 || r2 != 5 || err != nil || err2 != nil { 60 | t.Fatal("expected reads of 5 and 5") 61 | } 62 | 63 | b = newBuffer() 64 | b.write(alphabet[:10]) 65 | b.eof() 66 | r, err = b.Read(make([]byte, 5)) 67 | r2, err2 = b.Read(make([]byte, 10)) 68 | r3, err3 := b.Read(make([]byte, 10)) 69 | if r != 5 || r2 != 5 || r3 != 0 || err != nil || err2 != nil || err3 != io.EOF { 70 | t.Fatal("expected reads of 5 and 5 and 0, with EOF") 71 | } 72 | 73 | b = newBuffer() 74 | b.write(make([]byte, 5)) 75 | b.write(make([]byte, 10)) 76 | b.eof() 77 | r, err = b.Read(make([]byte, 9)) 78 | r2, err2 = b.Read(make([]byte, 3)) 79 | r3, err3 = b.Read(make([]byte, 3)) 80 | r4, err4 := b.Read(make([]byte, 10)) 81 | if err != nil || err2 != nil || err3 != nil || err4 != io.EOF { 82 | t.Fatalf("Expected EOF on forth read only, err=%v, err2=%v, err3=%v, err4=%v", err, err2, err3, err4) 83 | } 84 | if r != 9 || r2 != 3 || r3 != 3 || r4 != 0 { 85 | t.Fatal("Expected written == read == 15", r, r2, r3, r4) 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/client_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package ssh 6 | 7 | import ( 8 | "net" 9 | "strings" 10 | "testing" 11 | ) 12 | 13 | func testClientVersion(t *testing.T, config *ClientConfig, expected string) { 14 | clientConn, serverConn := net.Pipe() 15 | defer clientConn.Close() 16 | receivedVersion := make(chan string, 1) 17 | config.HostKeyCallback = InsecureIgnoreHostKey() 18 | go func() { 19 | version, err := readVersion(serverConn) 20 | if err != nil { 21 | receivedVersion <- "" 22 | } else { 23 | receivedVersion <- string(version) 24 | } 25 | serverConn.Close() 26 | }() 27 | NewClientConn(clientConn, "", config) 28 | actual := <-receivedVersion 29 | if actual != expected { 30 | t.Fatalf("got %s; want %s", actual, expected) 31 | } 32 | } 33 | 34 | func TestCustomClientVersion(t *testing.T) { 35 | version := "Test-Client-Version-0.0" 36 | testClientVersion(t, &ClientConfig{ClientVersion: version}, version) 37 | } 38 | 39 | func TestDefaultClientVersion(t *testing.T) { 40 | testClientVersion(t, &ClientConfig{}, packageVersion) 41 | } 42 | 43 | func TestHostKeyCheck(t *testing.T) { 44 | for _, tt := range []struct { 45 | name string 46 | wantError string 47 | key PublicKey 48 | }{ 49 | {"no callback", "must specify HostKeyCallback", nil}, 50 | {"correct key", "", testSigners["rsa"].PublicKey()}, 51 | {"mismatch", "mismatch", testSigners["ecdsa"].PublicKey()}, 52 | } { 53 | c1, c2, err := netPipe() 54 | if err != nil { 55 | t.Fatalf("netPipe: %v", err) 56 | } 57 | defer c1.Close() 58 | defer c2.Close() 59 | serverConf := &ServerConfig{ 60 | NoClientAuth: true, 61 | } 62 | serverConf.AddHostKey(testSigners["rsa"]) 63 | 64 | go NewServerConn(c1, serverConf) 65 | clientConf := ClientConfig{ 66 | User: "user", 67 | } 68 | if tt.key != nil { 69 | clientConf.HostKeyCallback = FixedHostKey(tt.key) 70 | } 71 | 72 | _, _, _, err = NewClientConn(c2, "", &clientConf) 73 | if err != nil { 74 | if tt.wantError == "" || !strings.Contains(err.Error(), tt.wantError) { 75 | t.Errorf("%s: got error %q, missing %q", tt.name, err.Error(), tt.wantError) 76 | } 77 | } else if tt.wantError != "" { 78 | t.Errorf("%s: succeeded, but want error string %q", tt.name, tt.wantError) 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package ssh implements an SSH client and server. 7 | 8 | SSH is a transport security protocol, an authentication protocol and a 9 | family of application protocols. The most typical application level 10 | protocol is a remote shell and this is specifically implemented. However, 11 | the multiplexed nature of SSH is exposed to users that wish to support 12 | others. 13 | 14 | References: 15 | [PROTOCOL.certkeys]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys?rev=HEAD 16 | [SSH-PARAMETERS]: http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1 17 | 18 | This package does not fall under the stability promise of the Go language itself, 19 | so its API may be changed when pressing needs arise. 20 | */ 21 | package ssh // import "golang.org/x/crypto/ssh" 22 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/kex_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package ssh 6 | 7 | // Key exchange tests. 8 | 9 | import ( 10 | "crypto/rand" 11 | "reflect" 12 | "testing" 13 | ) 14 | 15 | func TestKexes(t *testing.T) { 16 | type kexResultErr struct { 17 | result *kexResult 18 | err error 19 | } 20 | 21 | for name, kex := range kexAlgoMap { 22 | a, b := memPipe() 23 | 24 | s := make(chan kexResultErr, 1) 25 | c := make(chan kexResultErr, 1) 26 | var magics handshakeMagics 27 | go func() { 28 | r, e := kex.Client(a, rand.Reader, &magics) 29 | a.Close() 30 | c <- kexResultErr{r, e} 31 | }() 32 | go func() { 33 | r, e := kex.Server(b, rand.Reader, &magics, testSigners["ecdsa"]) 34 | b.Close() 35 | s <- kexResultErr{r, e} 36 | }() 37 | 38 | clientRes := <-c 39 | serverRes := <-s 40 | if clientRes.err != nil { 41 | t.Errorf("client: %v", clientRes.err) 42 | } 43 | if serverRes.err != nil { 44 | t.Errorf("server: %v", serverRes.err) 45 | } 46 | if !reflect.DeepEqual(clientRes.result, serverRes.result) { 47 | t.Errorf("kex %q: mismatch %#v, %#v", name, clientRes.result, serverRes.result) 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/mac.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package ssh 6 | 7 | // Message authentication support 8 | 9 | import ( 10 | "crypto/hmac" 11 | "crypto/sha1" 12 | "crypto/sha256" 13 | "hash" 14 | ) 15 | 16 | type macMode struct { 17 | keySize int 18 | etm bool 19 | new func(key []byte) hash.Hash 20 | } 21 | 22 | // truncatingMAC wraps around a hash.Hash and truncates the output digest to 23 | // a given size. 24 | type truncatingMAC struct { 25 | length int 26 | hmac hash.Hash 27 | } 28 | 29 | func (t truncatingMAC) Write(data []byte) (int, error) { 30 | return t.hmac.Write(data) 31 | } 32 | 33 | func (t truncatingMAC) Sum(in []byte) []byte { 34 | out := t.hmac.Sum(in) 35 | return out[:len(in)+t.length] 36 | } 37 | 38 | func (t truncatingMAC) Reset() { 39 | t.hmac.Reset() 40 | } 41 | 42 | func (t truncatingMAC) Size() int { 43 | return t.length 44 | } 45 | 46 | func (t truncatingMAC) BlockSize() int { return t.hmac.BlockSize() } 47 | 48 | var macModes = map[string]*macMode{ 49 | "hmac-sha2-256-etm@openssh.com": {32, true, func(key []byte) hash.Hash { 50 | return hmac.New(sha256.New, key) 51 | }}, 52 | "hmac-sha2-256": {32, false, func(key []byte) hash.Hash { 53 | return hmac.New(sha256.New, key) 54 | }}, 55 | "hmac-sha1": {20, false, func(key []byte) hash.Hash { 56 | return hmac.New(sha1.New, key) 57 | }}, 58 | "hmac-sha1-96": {20, false, func(key []byte) hash.Hash { 59 | return truncatingMAC{12, hmac.New(sha1.New, key)} 60 | }}, 61 | } 62 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/mempipe_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package ssh 6 | 7 | import ( 8 | "io" 9 | "sync" 10 | "testing" 11 | ) 12 | 13 | // An in-memory packetConn. It is safe to call Close and writePacket 14 | // from different goroutines. 15 | type memTransport struct { 16 | eof bool 17 | pending [][]byte 18 | write *memTransport 19 | sync.Mutex 20 | *sync.Cond 21 | } 22 | 23 | func (t *memTransport) readPacket() ([]byte, error) { 24 | t.Lock() 25 | defer t.Unlock() 26 | for { 27 | if len(t.pending) > 0 { 28 | r := t.pending[0] 29 | t.pending = t.pending[1:] 30 | return r, nil 31 | } 32 | if t.eof { 33 | return nil, io.EOF 34 | } 35 | t.Cond.Wait() 36 | } 37 | } 38 | 39 | func (t *memTransport) closeSelf() error { 40 | t.Lock() 41 | defer t.Unlock() 42 | if t.eof { 43 | return io.EOF 44 | } 45 | t.eof = true 46 | t.Cond.Broadcast() 47 | return nil 48 | } 49 | 50 | func (t *memTransport) Close() error { 51 | err := t.write.closeSelf() 52 | t.closeSelf() 53 | return err 54 | } 55 | 56 | func (t *memTransport) writePacket(p []byte) error { 57 | t.write.Lock() 58 | defer t.write.Unlock() 59 | if t.write.eof { 60 | return io.EOF 61 | } 62 | c := make([]byte, len(p)) 63 | copy(c, p) 64 | t.write.pending = append(t.write.pending, c) 65 | t.write.Cond.Signal() 66 | return nil 67 | } 68 | 69 | func memPipe() (a, b packetConn) { 70 | t1 := memTransport{} 71 | t2 := memTransport{} 72 | t1.write = &t2 73 | t2.write = &t1 74 | t1.Cond = sync.NewCond(&t1.Mutex) 75 | t2.Cond = sync.NewCond(&t2.Mutex) 76 | return &t1, &t2 77 | } 78 | 79 | func TestMemPipe(t *testing.T) { 80 | a, b := memPipe() 81 | if err := a.writePacket([]byte{42}); err != nil { 82 | t.Fatalf("writePacket: %v", err) 83 | } 84 | if err := a.Close(); err != nil { 85 | t.Fatal("Close: ", err) 86 | } 87 | p, err := b.readPacket() 88 | if err != nil { 89 | t.Fatal("readPacket: ", err) 90 | } 91 | if len(p) != 1 || p[0] != 42 { 92 | t.Fatalf("got %v, want {42}", p) 93 | } 94 | p, err = b.readPacket() 95 | if err != io.EOF { 96 | t.Fatalf("got %v, %v, want EOF", p, err) 97 | } 98 | } 99 | 100 | func TestDoubleClose(t *testing.T) { 101 | a, _ := memPipe() 102 | err := a.Close() 103 | if err != nil { 104 | t.Errorf("Close: %v", err) 105 | } 106 | err = a.Close() 107 | if err != io.EOF { 108 | t.Errorf("expect EOF on double close.") 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/streamlocal.go: -------------------------------------------------------------------------------- 1 | package ssh 2 | 3 | import ( 4 | "errors" 5 | "io" 6 | "net" 7 | ) 8 | 9 | // streamLocalChannelOpenDirectMsg is a struct used for SSH_MSG_CHANNEL_OPEN message 10 | // with "direct-streamlocal@openssh.com" string. 11 | // 12 | // See openssh-portable/PROTOCOL, section 2.4. connection: Unix domain socket forwarding 13 | // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL#L235 14 | type streamLocalChannelOpenDirectMsg struct { 15 | socketPath string 16 | reserved0 string 17 | reserved1 uint32 18 | } 19 | 20 | // forwardedStreamLocalPayload is a struct used for SSH_MSG_CHANNEL_OPEN message 21 | // with "forwarded-streamlocal@openssh.com" string. 22 | type forwardedStreamLocalPayload struct { 23 | SocketPath string 24 | Reserved0 string 25 | } 26 | 27 | // streamLocalChannelForwardMsg is a struct used for SSH2_MSG_GLOBAL_REQUEST message 28 | // with "streamlocal-forward@openssh.com"/"cancel-streamlocal-forward@openssh.com" string. 29 | type streamLocalChannelForwardMsg struct { 30 | socketPath string 31 | } 32 | 33 | // ListenUnix is similar to ListenTCP but uses a Unix domain socket. 34 | func (c *Client) ListenUnix(socketPath string) (net.Listener, error) { 35 | m := streamLocalChannelForwardMsg{ 36 | socketPath, 37 | } 38 | // send message 39 | ok, _, err := c.SendRequest("streamlocal-forward@openssh.com", true, Marshal(&m)) 40 | if err != nil { 41 | return nil, err 42 | } 43 | if !ok { 44 | return nil, errors.New("ssh: streamlocal-forward@openssh.com request denied by peer") 45 | } 46 | ch := c.forwards.add(&net.UnixAddr{Name: socketPath, Net: "unix"}) 47 | 48 | return &unixListener{socketPath, c, ch}, nil 49 | } 50 | 51 | func (c *Client) dialStreamLocal(socketPath string) (Channel, error) { 52 | msg := streamLocalChannelOpenDirectMsg{ 53 | socketPath: socketPath, 54 | } 55 | ch, in, err := c.OpenChannel("direct-streamlocal@openssh.com", Marshal(&msg)) 56 | if err != nil { 57 | return nil, err 58 | } 59 | go DiscardRequests(in) 60 | return ch, err 61 | } 62 | 63 | type unixListener struct { 64 | socketPath string 65 | 66 | conn *Client 67 | in <-chan forward 68 | } 69 | 70 | // Accept waits for and returns the next connection to the listener. 71 | func (l *unixListener) Accept() (net.Conn, error) { 72 | s, ok := <-l.in 73 | if !ok { 74 | return nil, io.EOF 75 | } 76 | ch, incoming, err := s.newCh.Accept() 77 | if err != nil { 78 | return nil, err 79 | } 80 | go DiscardRequests(incoming) 81 | 82 | return &chanConn{ 83 | Channel: ch, 84 | laddr: &net.UnixAddr{ 85 | Name: l.socketPath, 86 | Net: "unix", 87 | }, 88 | raddr: &net.UnixAddr{ 89 | Name: "@", 90 | Net: "unix", 91 | }, 92 | }, nil 93 | } 94 | 95 | // Close closes the listener. 96 | func (l *unixListener) Close() error { 97 | // this also closes the listener. 98 | l.conn.forwards.remove(&net.UnixAddr{Name: l.socketPath, Net: "unix"}) 99 | m := streamLocalChannelForwardMsg{ 100 | l.socketPath, 101 | } 102 | ok, _, err := l.conn.SendRequest("cancel-streamlocal-forward@openssh.com", true, Marshal(&m)) 103 | if err == nil && !ok { 104 | err = errors.New("ssh: cancel-streamlocal-forward@openssh.com failed") 105 | } 106 | return err 107 | } 108 | 109 | // Addr returns the listener's network address. 110 | func (l *unixListener) Addr() net.Addr { 111 | return &net.UnixAddr{ 112 | Name: l.socketPath, 113 | Net: "unix", 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/tcpip_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package ssh 6 | 7 | import ( 8 | "testing" 9 | ) 10 | 11 | func TestAutoPortListenBroken(t *testing.T) { 12 | broken := "SSH-2.0-OpenSSH_5.9hh11" 13 | works := "SSH-2.0-OpenSSH_6.1" 14 | if !isBrokenOpenSSHVersion(broken) { 15 | t.Errorf("version %q not marked as broken", broken) 16 | } 17 | if isBrokenOpenSSHVersion(works) { 18 | t.Errorf("version %q marked as broken", works) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/terminal/util_bsd.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build darwin dragonfly freebsd netbsd openbsd 6 | 7 | package terminal 8 | 9 | import "golang.org/x/sys/unix" 10 | 11 | const ioctlReadTermios = unix.TIOCGETA 12 | const ioctlWriteTermios = unix.TIOCSETA 13 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/terminal/util_linux.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package terminal 6 | 7 | import "golang.org/x/sys/unix" 8 | 9 | const ioctlReadTermios = unix.TCGETS 10 | const ioctlWriteTermios = unix.TCSETS 11 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/terminal/util_plan9.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package terminal provides support functions for dealing with terminals, as 6 | // commonly found on UNIX systems. 7 | // 8 | // Putting a terminal into raw mode is the most common requirement: 9 | // 10 | // oldState, err := terminal.MakeRaw(0) 11 | // if err != nil { 12 | // panic(err) 13 | // } 14 | // defer terminal.Restore(0, oldState) 15 | package terminal 16 | 17 | import ( 18 | "fmt" 19 | "runtime" 20 | ) 21 | 22 | type State struct{} 23 | 24 | // IsTerminal returns true if the given file descriptor is a terminal. 25 | func IsTerminal(fd int) bool { 26 | return false 27 | } 28 | 29 | // MakeRaw put the terminal connected to the given file descriptor into raw 30 | // mode and returns the previous state of the terminal so that it can be 31 | // restored. 32 | func MakeRaw(fd int) (*State, error) { 33 | return nil, fmt.Errorf("terminal: MakeRaw not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) 34 | } 35 | 36 | // GetState returns the current state of a terminal which may be useful to 37 | // restore the terminal after a signal. 38 | func GetState(fd int) (*State, error) { 39 | return nil, fmt.Errorf("terminal: GetState not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) 40 | } 41 | 42 | // Restore restores the terminal connected to the given file descriptor to a 43 | // previous state. 44 | func Restore(fd int, state *State) error { 45 | return fmt.Errorf("terminal: Restore not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) 46 | } 47 | 48 | // GetSize returns the dimensions of the given terminal. 49 | func GetSize(fd int) (width, height int, err error) { 50 | return 0, 0, fmt.Errorf("terminal: GetSize not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) 51 | } 52 | 53 | // ReadPassword reads a line of input from a terminal without local echo. This 54 | // is commonly used for inputting passwords and other sensitive data. The slice 55 | // returned does not include the \n. 56 | func ReadPassword(fd int) ([]byte, error) { 57 | return nil, fmt.Errorf("terminal: ReadPassword not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) 58 | } 59 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/terminal/util_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build windows 6 | 7 | // Package terminal provides support functions for dealing with terminals, as 8 | // commonly found on UNIX systems. 9 | // 10 | // Putting a terminal into raw mode is the most common requirement: 11 | // 12 | // oldState, err := terminal.MakeRaw(0) 13 | // if err != nil { 14 | // panic(err) 15 | // } 16 | // defer terminal.Restore(0, oldState) 17 | package terminal 18 | 19 | import ( 20 | "golang.org/x/sys/windows" 21 | ) 22 | 23 | type State struct { 24 | mode uint32 25 | } 26 | 27 | // IsTerminal returns true if the given file descriptor is a terminal. 28 | func IsTerminal(fd int) bool { 29 | var st uint32 30 | err := windows.GetConsoleMode(windows.Handle(fd), &st) 31 | return err == nil 32 | } 33 | 34 | // MakeRaw put the terminal connected to the given file descriptor into raw 35 | // mode and returns the previous state of the terminal so that it can be 36 | // restored. 37 | func MakeRaw(fd int) (*State, error) { 38 | var st uint32 39 | if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil { 40 | return nil, err 41 | } 42 | raw := st &^ (windows.ENABLE_ECHO_INPUT | windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT) 43 | if err := windows.SetConsoleMode(windows.Handle(fd), raw); err != nil { 44 | return nil, err 45 | } 46 | return &State{st}, nil 47 | } 48 | 49 | // GetState returns the current state of a terminal which may be useful to 50 | // restore the terminal after a signal. 51 | func GetState(fd int) (*State, error) { 52 | var st uint32 53 | if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil { 54 | return nil, err 55 | } 56 | return &State{st}, nil 57 | } 58 | 59 | // Restore restores the terminal connected to the given file descriptor to a 60 | // previous state. 61 | func Restore(fd int, state *State) error { 62 | return windows.SetConsoleMode(windows.Handle(fd), state.mode) 63 | } 64 | 65 | // GetSize returns the dimensions of the given terminal. 66 | func GetSize(fd int) (width, height int, err error) { 67 | var info windows.ConsoleScreenBufferInfo 68 | if err := windows.GetConsoleScreenBufferInfo(windows.Handle(fd), &info); err != nil { 69 | return 0, 0, err 70 | } 71 | return int(info.Size.X), int(info.Size.Y), nil 72 | } 73 | 74 | // passwordReader is an io.Reader that reads from a specific Windows HANDLE. 75 | type passwordReader int 76 | 77 | func (r passwordReader) Read(buf []byte) (int, error) { 78 | return windows.Read(windows.Handle(r), buf) 79 | } 80 | 81 | // ReadPassword reads a line of input from a terminal without local echo. This 82 | // is commonly used for inputting passwords and other sensitive data. The slice 83 | // returned does not include the \n. 84 | func ReadPassword(fd int) ([]byte, error) { 85 | var st uint32 86 | if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil { 87 | return nil, err 88 | } 89 | old := st 90 | 91 | st &^= (windows.ENABLE_ECHO_INPUT) 92 | st |= (windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT) 93 | if err := windows.SetConsoleMode(windows.Handle(fd), st); err != nil { 94 | return nil, err 95 | } 96 | 97 | defer func() { 98 | windows.SetConsoleMode(windows.Handle(fd), old) 99 | }() 100 | 101 | return readPasswordLine(passwordReader(fd)) 102 | } 103 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/test/agent_unix_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build darwin dragonfly freebsd linux netbsd openbsd 6 | 7 | package test 8 | 9 | import ( 10 | "bytes" 11 | "testing" 12 | 13 | "golang.org/x/crypto/ssh" 14 | "golang.org/x/crypto/ssh/agent" 15 | ) 16 | 17 | func TestAgentForward(t *testing.T) { 18 | server := newServer(t) 19 | defer server.Shutdown() 20 | conn := server.Dial(clientConfig()) 21 | defer conn.Close() 22 | 23 | keyring := agent.NewKeyring() 24 | if err := keyring.Add(agent.AddedKey{PrivateKey: testPrivateKeys["dsa"]}); err != nil { 25 | t.Fatalf("Error adding key: %s", err) 26 | } 27 | if err := keyring.Add(agent.AddedKey{ 28 | PrivateKey: testPrivateKeys["dsa"], 29 | ConfirmBeforeUse: true, 30 | LifetimeSecs: 3600, 31 | }); err != nil { 32 | t.Fatalf("Error adding key with constraints: %s", err) 33 | } 34 | pub := testPublicKeys["dsa"] 35 | 36 | sess, err := conn.NewSession() 37 | if err != nil { 38 | t.Fatalf("NewSession: %v", err) 39 | } 40 | if err := agent.RequestAgentForwarding(sess); err != nil { 41 | t.Fatalf("RequestAgentForwarding: %v", err) 42 | } 43 | 44 | if err := agent.ForwardToAgent(conn, keyring); err != nil { 45 | t.Fatalf("SetupForwardKeyring: %v", err) 46 | } 47 | out, err := sess.CombinedOutput("ssh-add -L") 48 | if err != nil { 49 | t.Fatalf("running ssh-add: %v, out %s", err, out) 50 | } 51 | key, _, _, _, err := ssh.ParseAuthorizedKey(out) 52 | if err != nil { 53 | t.Fatalf("ParseAuthorizedKey(%q): %v", out, err) 54 | } 55 | 56 | if !bytes.Equal(key.Marshal(), pub.Marshal()) { 57 | t.Fatalf("got key %s, want %s", ssh.MarshalAuthorizedKey(key), ssh.MarshalAuthorizedKey(pub)) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/test/cert_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build darwin dragonfly freebsd linux netbsd openbsd 6 | 7 | package test 8 | 9 | import ( 10 | "bytes" 11 | "crypto/rand" 12 | "testing" 13 | 14 | "golang.org/x/crypto/ssh" 15 | ) 16 | 17 | // Test both logging in with a cert, and also that the certificate presented by an OpenSSH host can be validated correctly 18 | func TestCertLogin(t *testing.T) { 19 | s := newServer(t) 20 | defer s.Shutdown() 21 | 22 | // Use a key different from the default. 23 | clientKey := testSigners["dsa"] 24 | caAuthKey := testSigners["ecdsa"] 25 | cert := &ssh.Certificate{ 26 | Key: clientKey.PublicKey(), 27 | ValidPrincipals: []string{username()}, 28 | CertType: ssh.UserCert, 29 | ValidBefore: ssh.CertTimeInfinity, 30 | } 31 | if err := cert.SignCert(rand.Reader, caAuthKey); err != nil { 32 | t.Fatalf("SetSignature: %v", err) 33 | } 34 | 35 | certSigner, err := ssh.NewCertSigner(cert, clientKey) 36 | if err != nil { 37 | t.Fatalf("NewCertSigner: %v", err) 38 | } 39 | 40 | conf := &ssh.ClientConfig{ 41 | User: username(), 42 | HostKeyCallback: (&ssh.CertChecker{ 43 | IsHostAuthority: func(pk ssh.PublicKey, addr string) bool { 44 | return bytes.Equal(pk.Marshal(), testPublicKeys["ca"].Marshal()) 45 | }, 46 | }).CheckHostKey, 47 | } 48 | conf.Auth = append(conf.Auth, ssh.PublicKeys(certSigner)) 49 | 50 | for _, test := range []struct { 51 | addr string 52 | succeed bool 53 | }{ 54 | {addr: "host.example.com:22", succeed: true}, 55 | {addr: "host.example.com:10000", succeed: true}, // non-standard port must be OK 56 | {addr: "host.example.com", succeed: false}, // port must be specified 57 | {addr: "host.ex4mple.com:22", succeed: false}, // wrong host 58 | } { 59 | client, err := s.TryDialWithAddr(conf, test.addr) 60 | 61 | // Always close client if opened successfully 62 | if err == nil { 63 | client.Close() 64 | } 65 | 66 | // Now evaluate whether the test failed or passed 67 | if test.succeed { 68 | if err != nil { 69 | t.Fatalf("TryDialWithAddr: %v", err) 70 | } 71 | } else { 72 | if err == nil { 73 | t.Fatalf("TryDialWithAddr, unexpected success") 74 | } 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/test/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // This package contains integration tests for the 6 | // golang.org/x/crypto/ssh package. 7 | package test // import "golang.org/x/crypto/ssh/test" 8 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/test/testdata_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // IMPLEMENTATION NOTE: To avoid a package loop, this file is in three places: 6 | // ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three 7 | // instances. 8 | 9 | package test 10 | 11 | import ( 12 | "crypto/rand" 13 | "fmt" 14 | 15 | "golang.org/x/crypto/ssh" 16 | "golang.org/x/crypto/ssh/testdata" 17 | ) 18 | 19 | var ( 20 | testPrivateKeys map[string]interface{} 21 | testSigners map[string]ssh.Signer 22 | testPublicKeys map[string]ssh.PublicKey 23 | ) 24 | 25 | func init() { 26 | var err error 27 | 28 | n := len(testdata.PEMBytes) 29 | testPrivateKeys = make(map[string]interface{}, n) 30 | testSigners = make(map[string]ssh.Signer, n) 31 | testPublicKeys = make(map[string]ssh.PublicKey, n) 32 | for t, k := range testdata.PEMBytes { 33 | testPrivateKeys[t], err = ssh.ParseRawPrivateKey(k) 34 | if err != nil { 35 | panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) 36 | } 37 | testSigners[t], err = ssh.NewSignerFromKey(testPrivateKeys[t]) 38 | if err != nil { 39 | panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) 40 | } 41 | testPublicKeys[t] = testSigners[t].PublicKey() 42 | } 43 | 44 | // Create a cert and sign it for use in tests. 45 | testCert := &ssh.Certificate{ 46 | Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil 47 | ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage 48 | ValidAfter: 0, // unix epoch 49 | ValidBefore: ssh.CertTimeInfinity, // The end of currently representable time. 50 | Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil 51 | Key: testPublicKeys["ecdsa"], 52 | SignatureKey: testPublicKeys["rsa"], 53 | Permissions: ssh.Permissions{ 54 | CriticalOptions: map[string]string{}, 55 | Extensions: map[string]string{}, 56 | }, 57 | } 58 | testCert.SignCert(rand.Reader, testSigners["rsa"]) 59 | testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] 60 | testSigners["cert"], err = ssh.NewCertSigner(testCert, testSigners["ecdsa"]) 61 | if err != nil { 62 | panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/testdata/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // This package contains test data shared between the various subpackages of 6 | // the golang.org/x/crypto/ssh package. Under no circumstance should 7 | // this data be used for production code. 8 | package testdata // import "golang.org/x/crypto/ssh/testdata" 9 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/testdata_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // IMPLEMENTATION NOTE: To avoid a package loop, this file is in three places: 6 | // ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three 7 | // instances. 8 | 9 | package ssh 10 | 11 | import ( 12 | "crypto/rand" 13 | "fmt" 14 | 15 | "golang.org/x/crypto/ssh/testdata" 16 | ) 17 | 18 | var ( 19 | testPrivateKeys map[string]interface{} 20 | testSigners map[string]Signer 21 | testPublicKeys map[string]PublicKey 22 | ) 23 | 24 | func init() { 25 | var err error 26 | 27 | n := len(testdata.PEMBytes) 28 | testPrivateKeys = make(map[string]interface{}, n) 29 | testSigners = make(map[string]Signer, n) 30 | testPublicKeys = make(map[string]PublicKey, n) 31 | for t, k := range testdata.PEMBytes { 32 | testPrivateKeys[t], err = ParseRawPrivateKey(k) 33 | if err != nil { 34 | panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) 35 | } 36 | testSigners[t], err = NewSignerFromKey(testPrivateKeys[t]) 37 | if err != nil { 38 | panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) 39 | } 40 | testPublicKeys[t] = testSigners[t].PublicKey() 41 | } 42 | 43 | // Create a cert and sign it for use in tests. 44 | testCert := &Certificate{ 45 | Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil 46 | ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage 47 | ValidAfter: 0, // unix epoch 48 | ValidBefore: CertTimeInfinity, // The end of currently representable time. 49 | Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil 50 | Key: testPublicKeys["ecdsa"], 51 | SignatureKey: testPublicKeys["rsa"], 52 | Permissions: Permissions{ 53 | CriticalOptions: map[string]string{}, 54 | Extensions: map[string]string{}, 55 | }, 56 | } 57 | testCert.SignCert(rand.Reader, testSigners["rsa"]) 58 | testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] 59 | testSigners["cert"], err = NewCertSigner(testCert, testSigners["ecdsa"]) 60 | if err != nil { 61 | panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/ssh/transport_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package ssh 6 | 7 | import ( 8 | "bytes" 9 | "crypto/rand" 10 | "encoding/binary" 11 | "strings" 12 | "testing" 13 | ) 14 | 15 | func TestReadVersion(t *testing.T) { 16 | longversion := strings.Repeat("SSH-2.0-bla", 50)[:253] 17 | cases := map[string]string{ 18 | "SSH-2.0-bla\r\n": "SSH-2.0-bla", 19 | "SSH-2.0-bla\n": "SSH-2.0-bla", 20 | longversion + "\r\n": longversion, 21 | } 22 | 23 | for in, want := range cases { 24 | result, err := readVersion(bytes.NewBufferString(in)) 25 | if err != nil { 26 | t.Errorf("readVersion(%q): %s", in, err) 27 | } 28 | got := string(result) 29 | if got != want { 30 | t.Errorf("got %q, want %q", got, want) 31 | } 32 | } 33 | } 34 | 35 | func TestReadVersionError(t *testing.T) { 36 | longversion := strings.Repeat("SSH-2.0-bla", 50)[:253] 37 | cases := []string{ 38 | longversion + "too-long\r\n", 39 | } 40 | for _, in := range cases { 41 | if _, err := readVersion(bytes.NewBufferString(in)); err == nil { 42 | t.Errorf("readVersion(%q) should have failed", in) 43 | } 44 | } 45 | } 46 | 47 | func TestExchangeVersionsBasic(t *testing.T) { 48 | v := "SSH-2.0-bla" 49 | buf := bytes.NewBufferString(v + "\r\n") 50 | them, err := exchangeVersions(buf, []byte("xyz")) 51 | if err != nil { 52 | t.Errorf("exchangeVersions: %v", err) 53 | } 54 | 55 | if want := "SSH-2.0-bla"; string(them) != want { 56 | t.Errorf("got %q want %q for our version", them, want) 57 | } 58 | } 59 | 60 | func TestExchangeVersions(t *testing.T) { 61 | cases := []string{ 62 | "not\x000allowed", 63 | "not allowed\n", 64 | } 65 | for _, c := range cases { 66 | buf := bytes.NewBufferString("SSH-2.0-bla\r\n") 67 | if _, err := exchangeVersions(buf, []byte(c)); err == nil { 68 | t.Errorf("exchangeVersions(%q): should have failed", c) 69 | } 70 | } 71 | } 72 | 73 | type closerBuffer struct { 74 | bytes.Buffer 75 | } 76 | 77 | func (b *closerBuffer) Close() error { 78 | return nil 79 | } 80 | 81 | func TestTransportMaxPacketWrite(t *testing.T) { 82 | buf := &closerBuffer{} 83 | tr := newTransport(buf, rand.Reader, true) 84 | huge := make([]byte, maxPacket+1) 85 | err := tr.writePacket(huge) 86 | if err == nil { 87 | t.Errorf("transport accepted write for a huge packet.") 88 | } 89 | } 90 | 91 | func TestTransportMaxPacketReader(t *testing.T) { 92 | var header [5]byte 93 | huge := make([]byte, maxPacket+128) 94 | binary.BigEndian.PutUint32(header[0:], uint32(len(huge))) 95 | // padding. 96 | header[4] = 0 97 | 98 | buf := &closerBuffer{} 99 | buf.Write(header[:]) 100 | buf.Write(huge) 101 | 102 | tr := newTransport(buf, rand.Reader, true) 103 | _, err := tr.readPacket() 104 | if err == nil { 105 | t.Errorf("transport succeeded reading huge packet.") 106 | } else if !strings.Contains(err.Error(), "large") { 107 | t.Errorf("got %q, should mention %q", err.Error(), "large") 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/tea/tea_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package tea 6 | 7 | import ( 8 | "bytes" 9 | "testing" 10 | ) 11 | 12 | // A sample test key for when we just want to initialize a cipher 13 | var testKey = []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF} 14 | 15 | // Test that the block size for tea is correct 16 | func TestBlocksize(t *testing.T) { 17 | c, err := NewCipher(testKey) 18 | if err != nil { 19 | t.Fatalf("NewCipher returned error: %s", err) 20 | } 21 | 22 | if result := c.BlockSize(); result != BlockSize { 23 | t.Errorf("cipher.BlockSize returned %d, but expected %d", result, BlockSize) 24 | } 25 | } 26 | 27 | // Test that invalid key sizes return an error 28 | func TestInvalidKeySize(t *testing.T) { 29 | var key [KeySize + 1]byte 30 | 31 | if _, err := NewCipher(key[:]); err == nil { 32 | t.Errorf("invalid key size %d didn't result in an error.", len(key)) 33 | } 34 | 35 | if _, err := NewCipher(key[:KeySize-1]); err == nil { 36 | t.Errorf("invalid key size %d didn't result in an error.", KeySize-1) 37 | } 38 | } 39 | 40 | // Test Vectors 41 | type teaTest struct { 42 | rounds int 43 | key []byte 44 | plaintext []byte 45 | ciphertext []byte 46 | } 47 | 48 | var teaTests = []teaTest{ 49 | // These were sourced from https://github.com/froydnj/ironclad/blob/master/testing/test-vectors/tea.testvec 50 | { 51 | numRounds, 52 | []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 53 | []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 54 | []byte{0x41, 0xea, 0x3a, 0x0a, 0x94, 0xba, 0xa9, 0x40}, 55 | }, 56 | { 57 | numRounds, 58 | []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, 59 | []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, 60 | []byte{0x31, 0x9b, 0xbe, 0xfb, 0x01, 0x6a, 0xbd, 0xb2}, 61 | }, 62 | { 63 | 16, 64 | []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 65 | []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 66 | []byte{0xed, 0x28, 0x5d, 0xa1, 0x45, 0x5b, 0x33, 0xc1}, 67 | }, 68 | } 69 | 70 | // Test encryption 71 | func TestCipherEncrypt(t *testing.T) { 72 | // Test encryption with standard 64 rounds 73 | for i, test := range teaTests { 74 | c, err := NewCipherWithRounds(test.key, test.rounds) 75 | if err != nil { 76 | t.Fatalf("#%d: NewCipher returned error: %s", i, err) 77 | } 78 | 79 | var ciphertext [BlockSize]byte 80 | c.Encrypt(ciphertext[:], test.plaintext) 81 | 82 | if !bytes.Equal(ciphertext[:], test.ciphertext) { 83 | t.Errorf("#%d: incorrect ciphertext. Got %x, wanted %x", i, ciphertext, test.ciphertext) 84 | } 85 | 86 | var plaintext2 [BlockSize]byte 87 | c.Decrypt(plaintext2[:], ciphertext[:]) 88 | 89 | if !bytes.Equal(plaintext2[:], test.plaintext) { 90 | t.Errorf("#%d: incorrect plaintext. Got %x, wanted %x", i, plaintext2, test.plaintext) 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/xtea/block.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Implementation adapted from Needham and Wheeler's paper: 7 | http://www.cix.co.uk/~klockstone/xtea.pdf 8 | 9 | A precalculated look up table is used during encryption/decryption for values that are based purely on the key. 10 | */ 11 | 12 | package xtea 13 | 14 | // XTEA is based on 64 rounds. 15 | const numRounds = 64 16 | 17 | // blockToUint32 reads an 8 byte slice into two uint32s. 18 | // The block is treated as big endian. 19 | func blockToUint32(src []byte) (uint32, uint32) { 20 | r0 := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) 21 | r1 := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) 22 | return r0, r1 23 | } 24 | 25 | // uint32ToBlock writes two uint32s into an 8 byte data block. 26 | // Values are written as big endian. 27 | func uint32ToBlock(v0, v1 uint32, dst []byte) { 28 | dst[0] = byte(v0 >> 24) 29 | dst[1] = byte(v0 >> 16) 30 | dst[2] = byte(v0 >> 8) 31 | dst[3] = byte(v0) 32 | dst[4] = byte(v1 >> 24) 33 | dst[5] = byte(v1 >> 16) 34 | dst[6] = byte(v1 >> 8) 35 | dst[7] = byte(v1 >> 0) 36 | } 37 | 38 | // encryptBlock encrypts a single 8 byte block using XTEA. 39 | func encryptBlock(c *Cipher, dst, src []byte) { 40 | v0, v1 := blockToUint32(src) 41 | 42 | // Two rounds of XTEA applied per loop 43 | for i := 0; i < numRounds; { 44 | v0 += ((v1<<4 ^ v1>>5) + v1) ^ c.table[i] 45 | i++ 46 | v1 += ((v0<<4 ^ v0>>5) + v0) ^ c.table[i] 47 | i++ 48 | } 49 | 50 | uint32ToBlock(v0, v1, dst) 51 | } 52 | 53 | // decryptBlock decrypt a single 8 byte block using XTEA. 54 | func decryptBlock(c *Cipher, dst, src []byte) { 55 | v0, v1 := blockToUint32(src) 56 | 57 | // Two rounds of XTEA applied per loop 58 | for i := numRounds; i > 0; { 59 | i-- 60 | v1 -= ((v0<<4 ^ v0>>5) + v0) ^ c.table[i] 61 | i-- 62 | v0 -= ((v1<<4 ^ v1>>5) + v1) ^ c.table[i] 63 | } 64 | 65 | uint32ToBlock(v0, v1, dst) 66 | } 67 | -------------------------------------------------------------------------------- /src/golang.org/x/crypto/xtea/cipher.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package xtea implements XTEA encryption, as defined in Needham and Wheeler's 6 | // 1997 technical report, "Tea extensions." 7 | package xtea // import "golang.org/x/crypto/xtea" 8 | 9 | // For details, see http://www.cix.co.uk/~klockstone/xtea.pdf 10 | 11 | import "strconv" 12 | 13 | // The XTEA block size in bytes. 14 | const BlockSize = 8 15 | 16 | // A Cipher is an instance of an XTEA cipher using a particular key. 17 | // table contains a series of precalculated values that are used each round. 18 | type Cipher struct { 19 | table [64]uint32 20 | } 21 | 22 | type KeySizeError int 23 | 24 | func (k KeySizeError) Error() string { 25 | return "crypto/xtea: invalid key size " + strconv.Itoa(int(k)) 26 | } 27 | 28 | // NewCipher creates and returns a new Cipher. 29 | // The key argument should be the XTEA key. 30 | // XTEA only supports 128 bit (16 byte) keys. 31 | func NewCipher(key []byte) (*Cipher, error) { 32 | k := len(key) 33 | switch k { 34 | default: 35 | return nil, KeySizeError(k) 36 | case 16: 37 | break 38 | } 39 | 40 | c := new(Cipher) 41 | initCipher(c, key) 42 | 43 | return c, nil 44 | } 45 | 46 | // BlockSize returns the XTEA block size, 8 bytes. 47 | // It is necessary to satisfy the Block interface in the 48 | // package "crypto/cipher". 49 | func (c *Cipher) BlockSize() int { return BlockSize } 50 | 51 | // Encrypt encrypts the 8 byte buffer src using the key and stores the result in dst. 52 | // Note that for amounts of data larger than a block, 53 | // it is not safe to just call Encrypt on successive blocks; 54 | // instead, use an encryption mode like CBC (see crypto/cipher/cbc.go). 55 | func (c *Cipher) Encrypt(dst, src []byte) { encryptBlock(c, dst, src) } 56 | 57 | // Decrypt decrypts the 8 byte buffer src using the key k and stores the result in dst. 58 | func (c *Cipher) Decrypt(dst, src []byte) { decryptBlock(c, dst, src) } 59 | 60 | // initCipher initializes the cipher context by creating a look up table 61 | // of precalculated values that are based on the key. 62 | func initCipher(c *Cipher, key []byte) { 63 | // Load the key into four uint32s 64 | var k [4]uint32 65 | for i := 0; i < len(k); i++ { 66 | j := i << 2 // Multiply by 4 67 | k[i] = uint32(key[j+0])<<24 | uint32(key[j+1])<<16 | uint32(key[j+2])<<8 | uint32(key[j+3]) 68 | } 69 | 70 | // Precalculate the table 71 | const delta = 0x9E3779B9 72 | var sum uint32 = 0 73 | 74 | // Two rounds of XTEA applied per loop 75 | for i := 0; i < numRounds; { 76 | c.table[i] = sum + k[sum&3] 77 | i++ 78 | sum += delta 79 | c.table[i] = sum + k[(sum>>11)&3] 80 | i++ 81 | } 82 | } 83 | --------------------------------------------------------------------------------