ch4/ch4-01 #188
Replies: 11 comments 1 reply
-
练习4.2: import ( func main() { |
Beta Was this translation helpful? Give feedback.
-
练习4.1: func PopCount(x, y string) (num int) { |
Beta Was this translation helpful? Give feedback.
-
4.1
|
Beta Was this translation helpful? Give feedback.
-
4.2
|
Beta Was this translation helpful? Give feedback.
-
4-2: go run main.go --method=1
Enter a string: abcd
88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589
package main
import (
"crypto/sha256"
"crypto/sha512"
"flag"
"fmt"
"log"
)
func main() {
var method string
flag.StringVar(&method, "method", "1", "编码方式(1 - SHA256, 2 - SHA384,3 - SHA512)")
flag.Parse()
ValidateMethod(method)
fmt.Print("Enter a string: ")
var input string
fmt.Scanln(&input)
var inputBytes = []byte(input)
if method == "1" {
fmt.Printf("%x\n", sha256.Sum256(inputBytes))
} else if method == "2" {
fmt.Printf("%x\n", sha512.Sum384(inputBytes))
} else {
fmt.Printf("%x\n", sha512.Sum512(inputBytes))
}
}
func ValidateMethod(m string) {
if m != "1" && m != "2" && m != "3" {
log.Fatalf("method %s is not supported.", m)
}
} |
Beta Was this translation helpful? Give feedback.
-
练习4.1 package main
import (
"crypto/sha256"
"fmt"
)
// 每个8位有几个位为1的对照表
var pc [256]byte
// 初始化pc byte数组
func init() {
for i := range pc {
pc[i] = pc[i/2] + byte(i&1)
}
}
func main() {
c1 := sha256.Sum256([]byte("X"))
c2 := sha256.Sum256([]byte("X"))
fmt.Printf("%d",compareSha256(c1, c2))
}
// 返回有几个1位
func Popcount(x byte) int {
return int(pc[x])
}
func compareSha256(x, y [32]byte) int{
count := 0
for i := 0; i < 8; i++ { // 每8位对比一次
count += Popcount((x[i]^y[i]))
}
return count
} |
Beta Was this translation helpful? Give feedback.
-
练习 4.1 package main
import (
"crypto/sha256"
"fmt"
)
func popCount(num uint8) int {
result := 0
for num > 0 {
num &= (num - 1)
result++
}
return result
}
func countDiff(a, b [32]uint8) int {
result := 0
for i, aValue := range a {
bValue := b[i]
diffValue := aValue ^ bValue
result += popCount(diffValue)
}
return result
}
func main() {
c1 := sha256.Sum256([]byte("x"))
c2 := sha256.Sum256([]byte("X"))
diff := countDiff(c1, c2)
fmt.Println(diff)
} 4.2 没看懂题目,额,,, |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
4.1 import ( func sha256Hash(data string) string { func hexToBinary(hexString string) string { func countDifferentBits(hash1, hash2 string) int {
} func main() {
} |
Beta Was this translation helpful? Give feedback.
-
package main import ( func main() {
} func countDiffBits(c1, c2 [32]byte) int { |
Beta Was this translation helpful? Give feedback.
-
package main import ( func main() { |
Beta Was this translation helpful? Give feedback.
-
ch4/ch4-01
中文版
https://gopl-zh.github.io/ch4/ch4-01.html
Beta Was this translation helpful? Give feedback.
All reactions