Пример #1
0
func createBaseDirForPackages(
	rootDir string,
	packages []string,
	storageEngine storage,
) (exists bool, dirName string, err error) {
	imageName := fmt.Sprintf(
		"%x",
		sha256.Sum224([]byte(strings.Join(packages, ","))),
	)

	imageDir := getImageDir(rootDir, imageName)
	if isExists(imageDir) && !isExists(imageDir, ".hastur") {
		err = storageEngine.DeInitImage(imageName)
		if err != nil {
			return false, "", ser.Errorf(
				err, "can't deinitialize image %s", imageName,
			)
		}
	}

	if !isExists(imageDir) {
		err = storageEngine.InitImage(imageName)
		if err != nil {
			return false, "", ser.Errorf(
				err, "can't initialize image %s", imageName,
			)
		}

		return false, imageName, nil
	} else {
		return true, imageName, nil
	}
}
Пример #2
0
func (sysRand *SysRandom) CreateCid(size int, prefix string) string {
	buf := make([]byte, size)
	for i := 0; i < size; i++ {
		buf[i] = acceptCahrs[sysRand.Intn(len(acceptCahrs))]
	}
	return fmt.Sprintf("%s-%x", prefix, sha256.Sum224(buf))
}
Пример #3
0
func _passpharseHash(passpharse []byte, encodingWay []string) (encodedpasspharse []byte) {
	encodepasspharse := passpharse
	for _, hashalgor := range encodingWay {
		switch hashalgor {
		case "md5":
			sum := md5.Sum(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha1":
			sum := sha1.Sum(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha224":
			sum := sha256.Sum224(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha256":
			sum := sha256.Sum256(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha384":
			sum := sha512.Sum384(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha512":
			sum := sha512.Sum512(encodepasspharse)
			encodepasspharse = sum[:]
		}
	}
	//issue if return with not args,the return value will be null
	return encodepasspharse
}
Пример #4
0
func readerID(index []byte, numWorkers int) int {
	q := make([]byte, len(index)+4)
	copy(q, index)
	copy(q[len(index):], secret)
	s := sha256.Sum224(q)
	s1 := binary.BigEndian.Uint64(s[0:8])
	return int(s1 % uint64(numWorkers))
}
Пример #5
0
// Create a new Deterministic Byte Machine.
func NewDbm(data string) *Dbm {
	dbm := &Dbm{i: 0}
	dbm.data = make([]byte, sha1.Size+sha256.Size+sha256.Size224)

	// initialize random data from input data
	bsha1 := sha1.Sum([]byte(data))
	bsha256 := sha256.Sum256([]byte(data))
	bsha224 := sha256.Sum224([]byte(data))
	copy(dbm.data, bsha1[:])
	copy(dbm.data[sha1.Size:], bsha256[:])
	copy(dbm.data[sha1.Size+sha256.Size:], bsha224[:])
	return dbm
}
Пример #6
0
func TestGolden(t *testing.T) {
	for i := 0; i < len(golden); i++ {
		g := golden[i]
		s := fmt.Sprintf("%x", sha256.Sum256([]byte(g.in)))
		if s != g.out {
			t.Fatalf("Sum256 function: sha256(%s) = %s want %s", g.in, s, g.out)
		}
		c := sha256.New()
		for j := 0; j < 3; j++ {
			if j < 2 {
				io.WriteString(c, g.in)
			} else {
				io.WriteString(c, g.in[0:len(g.in)/2])
				c.Sum(nil)
				io.WriteString(c, g.in[len(g.in)/2:])
			}
			s := fmt.Sprintf("%x", c.Sum(nil))
			if s != g.out {
				t.Fatalf("sha256[%d](%s) = %s want %s", j, g.in, s, g.out)
			}
			c.Reset()
		}
	}
	for i := 0; i < len(golden224); i++ {
		g := golden224[i]
		s := fmt.Sprintf("%x", sha256.Sum224([]byte(g.in)))
		if s != g.out {
			t.Fatalf("Sum224 function: sha224(%s) = %s want %s", g.in, s, g.out)
		}
		c := sha256.New224()
		for j := 0; j < 3; j++ {
			if j < 2 {
				io.WriteString(c, g.in)
			} else {
				io.WriteString(c, g.in[0:len(g.in)/2])
				c.Sum(nil)
				io.WriteString(c, g.in[len(g.in)/2:])
			}
			s := fmt.Sprintf("%x", c.Sum(nil))
			if s != g.out {
				t.Fatalf("sha224[%d](%s) = %s want %s", j, g.in, s, g.out)
			}
			c.Reset()
		}
	}
}
Пример #7
0
// This method is used to decrypt messages where symmetrci encryption is used
func (engine *CryptoEngine) DecryptWithPublicKey(encryptedBytes []byte, verificationEngine VerificationEngine) (*message, error) {

	var err error

	// get the peer public key
	peerPublicKey := verificationEngine.PublicKey()

	// convert the bytes to an encrypted message
	encryptedMessage, err := encryptedMessageFromBytes(encryptedBytes)
	if err != nil {
		return nil, err
	}

	// Make sure the key has a valid size
	if len(peerPublicKey) < keySize {
		return nil, KeyNotValidError
	}

	// calculate the hash of the peer public key
	sha224String := fmt.Sprintf("%x", sha256.Sum224(peerPublicKey[:]))

	// lock the mutex
	engine.mutex.Lock()

	// check if the pre sgared key is already present in the map
	if preSharedKey, ok := engine.preSharedKeysMap[sha224String]; ok { // means the key is there
		// unlock the mutex
		engine.mutex.Unlock()

		messageBytes, err := decryptWithPreShared(preSharedKey, encryptedMessage)
		if err != nil {
			return nil, err
		}
		return messageFromBytes(messageBytes)

	} else {
		// otherwise decrypt with the standard box open function
		messageBytes, valid := box.Open(nil, encryptedMessage.data, &encryptedMessage.nonce, &peerPublicKey, &engine.privateKey)
		if !valid {
			return nil, MessageDecryptionError
		}
		return messageFromBytes(messageBytes)
	}

}
Пример #8
0
// Cheat function to handle the hash type switch.
func hashMessage(m []byte, h crypto.Hash) []byte {
	switch h {
	case crypto.SHA1:
		sum := sha1.Sum(m)
		return sum[:]
	case crypto.SHA224:
		sum := sha256.Sum224(m)
		return sum[:]
	case crypto.SHA256:
		sum := sha256.Sum256(m)
		return sum[:]
	case crypto.SHA384:
		sum := sha512.Sum384(m)
		return sum[:]
	case crypto.SHA512:
		sum := sha512.Sum512(m)
		return sum[:]
	default:
		return nil
	}
}
Пример #9
0
func (pf *ProxyFile) Qid() (protocol.Qid, error) {
	if err := pf.updateInfo(); err != nil {
		return protocol.Qid{}, err
	}

	var tp protocol.QidType
	if pf.info.IsDir() {
		tp |= protocol.QTDIR
	}

	// This is not entirely correct as a path, as removing and recreating the
	// file should give a new path, but... What the hell.
	chk := sha256.Sum224([]byte(filepath.Join(pf.root, pf.path)))
	path := binary.LittleEndian.Uint64(chk[:8])

	return protocol.Qid{
		Path:    path,
		Version: uint32(pf.info.ModTime().UnixNano() / 1000000),
		Type:    tp,
	}, nil
}
Пример #10
0
func main() {
	s := "Hello world!"
	b := []byte(s)

	md5Sum := md5.Sum(b)
	fmt.Println("MD5   :", myHex(md5Sum[:]))
	fmt.Println("      :", myBase64(md5Sum[:]))

	sha1Sum := sha1.Sum(b)
	fmt.Println("SHA1  :", myHex(sha1Sum[:]))
	fmt.Println("      :", myBase64(sha1Sum[:]))

	sha224Sum := sha256.Sum224(b)
	fmt.Println("SHA224:", myHex(sha224Sum[:]))
	fmt.Println("      :", myBase64(sha224Sum[:]))

	sha256Sum := sha256.Sum256(b)
	fmt.Println("SHA256:", myHex(sha256Sum[:]))
	fmt.Println("      :", myBase64(sha256Sum[:]))

}
Пример #11
0
func GetFingerPrint(key OpenSSHPublicKey, algo string) (fp string, err error) {
	pubkey, err := ssh.ParsePublicKey(key.key)
	if err != nil {
		return "", errors.New("Cannot Get Fingerprint: Cannot Parse")
	}

	var cs []byte
	switch algo {
	case "md5":
		tmp := md5.Sum(pubkey.Marshal())
		cs = tmp[:]
	case "sha224":
		tmp := sha256.Sum224(pubkey.Marshal())
		cs = tmp[:]
	case "sha256":
		tmp := sha256.Sum256(pubkey.Marshal())
		cs = tmp[:]
	case "sha384":
		tmp := sha512.Sum384(pubkey.Marshal())
		cs = tmp[:]
	case "sha512":
		tmp := sha512.Sum512(pubkey.Marshal())
		cs = tmp[:]
	default:
		tmp := sha256.Sum256(pubkey.Marshal())
		cs = tmp[:]
	}
	switch algo {
	case "md5":
		for i := 0; i < len(cs); i++ {
			fp = fmt.Sprintf("%s%0.2x", fp, cs[i])
			if i != len(cs)-1 {
				fp = fp + ":"
			}
		}
	default:
		fp = base64.StdEncoding.EncodeToString(cs)
	}
	return
}
Пример #12
0
func shasum(data *[]byte, algorithm string) (interface{}, error) {
	var sum interface{}
	switch strings.ToLower(algorithm) {
	case "md5":
		sum = md5.Sum(*data)
	case "1":
		sum = sha1.Sum(*data)
	case "224":
		sum = sha256.Sum224(*data)
	case "256":
		sum = sha256.Sum256(*data)
	case "384":
		sum = sha512.Sum384(*data)
	case "512":
		sum = sha512.Sum512(*data)
	case "512224":
		sum = sha512.Sum512_224(*data)
	case "512256":
		sum = sha512.Sum512_256(*data)
	default:
		return nil, errors.New("unsupported algorithm")
	}
	return sum, nil
}
Пример #13
0
func createBaseDirForPackages(
	root string, packages []string,
) (exists bool, dirName string, err error) {
	baseDir := fmt.Sprintf(
		"%s.#%x",
		filepath.Join(root, "base"),
		sha256.Sum224([]byte(strings.Join(packages, ","))),
	)

	if _, err := os.Stat(baseDir); os.IsNotExist(err) {
		err := os.Mkdir(baseDir, 0755)
		if err != nil {
			return false, "", fmt.Errorf(
				"can't create base dir '%s': %s",
				baseDir,
				err,
			)
		}

		return false, baseDir, nil
	} else {
		return true, baseDir, nil
	}
}
Пример #14
0
func main() {
	help := flag.Bool("help", false, help_text)
	version := flag.Bool("version", false, version_text)
	check := flag.Bool("check", false, "check sha224 sums against given list")
	check1 := flag.Bool("c", false, "check sha224 sums against given list")
	flag.Parse()

	if *help {
		fmt.Println(help_text)
		os.Exit(0)
	}

	if *version {
		fmt.Println(version_text)
		os.Exit(0)
	}

	// If you are NOT checking...
	if !*check && !*check1 {
		if flag.NArg() > 0 {
			for _, file := range flag.Args() {
				buff, err := ioutil.ReadFile(file)
				if err != nil {
					fmt.Printf("sha224sum: cannot read '%s': %s\n", file, err)
				}
				fmt.Printf("%x %s\n", sha256.Sum224(buff), file)
			}
		} else {
			buff, err := ioutil.ReadAll(os.Stdin)
			if err != nil {
				fmt.Printf("sha224sum: cannot read 'STDIN': %s\n", err)
			}
			fmt.Printf("%x -\n", sha256.Sum224(buff))
		}

		// Check the files...
	} else {
		if flag.NArg() > 0 {
			NUMFAILED := 0
			for _, file := range flag.Args() {
				fp, err := os.Open(file)
				if err != nil {
					fmt.Printf("sha224sum: cannot read '%s': %s\n", file, err)
				}
				// Set up new reader
				bf := bufio.NewReader(fp)

				// loop through lines
				for {
					// get info
					line, isPrefix, err := bf.ReadLine()

					// is if EOF?
					if err == io.EOF {
						break
					}
					// another ERR?
					if err != nil {
						fmt.Printf("sha224sum: cannot read '%s': %s\n", file, err)
					}
					// is the line WAY too long?
					if isPrefix {
						fmt.Printf("sha224sum: unexpected long line: %s\n", file)
					}

					// success. check the hash
					hashfile := strings.Split(string(line), " ")
					HASH := string(hashfile[0])
					HFIL := string(hashfile[1])
					buff, err := ioutil.ReadFile(HFIL)
					if err != nil {
						fmt.Printf("sha224sum: cannot read '%s': %s\n", HFIL, err)
					}
					if HASH == fmt.Sprintf("%x", sha256.Sum224(buff)) {
						fmt.Printf("%s: OK\n", HFIL)
					} else {
						fmt.Printf("%s: FAILED\n", HFIL)
						NUMFAILED += 1
					}
				}
			}
			// Print how many TOTAL failed...
			if NUMFAILED > 0 {
				fmt.Printf("sha224sum: WARNING: %d computed checksum did NOT match\n", NUMFAILED)
			}

		} /* TODO: Implement this section...
		 else {
			buff, err := ioutil.ReadAll(os.Stdin)
			if err != nil {
				fmt.Printf("sha224sum: cannot read 'STDIN': %s", err)
			}
			fmt.Printf("%x -\n", sha224.Sum(buff))
		} */
	}
}
Пример #15
0
// SHA224Bytes calculates SHA-224 sum of the input array, returning result as a byte array
func SHA224Bytes(buf []byte) []byte {
	s := sha256.Sum224(buf)
	return s[:]
}
Пример #16
0
func (sysRand *SysRandom) CreateTaskId() string {
	src := fmt.Sprintf("%s-%d", sysRand.GetShotPrefix(), time.Now().UTC().UnixNano())
	return fmt.Sprintf("%x", sha256.Sum224([]byte(src)))
}
Пример #17
0
// This method accepts the message as byte slice and the public key of the receiver of the messae,
// then encrypts it using the asymmetric key public key.
// If the public key is not privisioned and does not have the required length of 32 bytes it raises an exception.
func (engine *CryptoEngine) NewEncryptedMessageWithPubKey(msg message, verificationEngine VerificationEngine) (EncryptedMessage, error) {

	encryptedMessage := EncryptedMessage{}

	// get the peer public key
	peerPublicKey := verificationEngine.PublicKey()

	// check the size of the peerPublicKey
	if len(peerPublicKey) != keySize {
		return encryptedMessage, KeyNotValidError
	}

	// check the peerPublicKey is not empty (all zeros)
	if bytes.Compare(peerPublicKey[:], emptyKey) == 0 {
		return encryptedMessage, KeyNotValidError
	}

	// derive nonce
	nonce, err := deriveNonce(engine.nonceKey, engine.salt, engine.context, engine.fetchAndIncrement())
	if err != nil {
		return encryptedMessage, err
	}

	// set the nonce to the encrypted message
	encryptedMessage.nonce = nonce

	// calculate the hash of the peer public key
	sha224String := fmt.Sprintf("%x", sha256.Sum224(peerPublicKey[:]))

	// lock the mutex
	engine.mutex.Lock()

	// check if the pre sgared key is already present in the map
	if preSharedKey, ok := engine.preSharedKeysMap[sha224String]; ok { // means the key is there
		// unlock the mutex
		engine.mutex.Unlock()

		// encrypt with the pre-computed key
		encryptedData := box.SealAfterPrecomputation(nil, msg.toBytes(), &nonce, &preSharedKey)

		// assign the encrypted data to the message
		encryptedMessage.data = encryptedData

	} else { // means the key is not there

		// generate the key
		// init the buffer
		preSharedKey = [keySize]byte{}

		// precompute the share key
		box.Precompute(&preSharedKey, &peerPublicKey, &engine.privateKey)

		// assign it to the map
		engine.preSharedKeysMap[sha224String] = preSharedKey

		// unlock the mutex once the map has the sharedKey set
		engine.mutex.Unlock()

		// encrypt with the pre-computed key
		encryptedData := box.SealAfterPrecomputation(nil, msg.toBytes(), &nonce, &preSharedKey)

		// assign the encrypted data to the message
		encryptedMessage.data = encryptedData
	}

	// calculate the size of the message
	encryptedMessage.length = uint64(len(encryptedMessage.data) + len(encryptedMessage.nonce) + 8)

	return encryptedMessage, nil

}