Golang Crypto Package

28/12/2020
Chưa phân loại
In this lesson on Crypto package in Golang, we will study various examples on managing and creating Ciphers in Go and see how Crypto package helps us in regards to Cipher Handling in Go programming language. We will get started now.

Starting with Go

Just to make sure we are on the same page, here is the directory structure which I made for my Hello World program:

Here is the program we created:

package main

import "fmt"

func main() {
    fmt.Printf("Hello, world.n")
}

We can run the above program with following command:

go run hello.go

Once we run this command, here is the output you will see:

Now that looks good. Let’s move to our main agenda.

Crypto Package in Golang

Using Crypto in Golang isn’t very easy to understand. This is because of the constructs it provides and the algorithm it follows to achieve encryption and decryption.

In this lesson, we will study these points:

  • SHA256 encryption
  • How to use bcrypt to encrypt Strings like passwords in your web applications
  • Using AES encryption and decryption

Let’s start by Hashing and comparing passwords.

SHA256 Encryption

We will start with somewhat simple. We will try a very simple example on how to perform an SHA256 encryption using Golang. Let’s look at the example:

package main

import (
  "fmt"
  "errors"
  "crypto/sha256"
  "encoding/base64"
)

func main() {
    someText := "shubham"
    hash, err := hashTextTo32Bytes(someText)
    fmt.Printf("%sn %s", hash, err)
}

func hashTextTo32Bytes(hashThis string) (hashed string, err error) {

    if len(hashThis) == 0 {
        return "", errors.New("No input supplied")
    }

    hasher := sha256.New()
    hasher.Write([]byte(hashThis))

    stringToSHA256 := base64.URLEncoding.EncodeToString(hasher.Sum(nil))

    // Cut the length down to 32 bytes and return.
    return stringToSHA256[:32], nil
}

We started by creating a hasher initially. Following this, we used it to write the hash in a byte array. Finally, we encode the String and return the 32 bits of hash.

When we run this example, we will get the following output:

Hashing and Matching Password

Now, we will finally use bcrypt to produce Hashed passwords. We will keep the functions direct and simple.

We will also include a function which matches the hashed password to a given String. This way, we can also confirm if the password provided by the user is correct one.  Before running this code will need to install the golang package for bcrypt with the following command:

# go get "golang.org/x/crypto/bcrypt"

Then you can execute this code:

package main

import "fmt"
import "golang.org/x/crypto/bcrypt"

func HashPassword(password string) (string, error) {
    bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
    return string(bytes), err
}

func CheckPasswordHash(password, hash string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
    return err == nil
}

func main() {
    myPwd := "shubham"
    providedHash, _ := HashPassword(myPwd)
    fmt.Println("Password :", myPwd)
    fmt.Println("Hash :", providedHash)

    isMatch := CheckPasswordHash(myPwd, providedHash)
    fmt.Println("Matched ?:", isMatch)
}

When we run this example, we will get the following output:

Conclusion

In this post, we studied simple but useful examples on how we can use crypto package to do actions very important and useful in our applications.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

How to Install CentOS 7 on a Virtualbox using Pre-installed Image

As part of my upcoming HowTo tutorials on my blog, I will need to install CentOS 7 on a virtualbox to accomplish this tasks....
28/12/2020

How to Mine Cryptocurrency with GPU Mining Rigs

As you may already know, it’s no longer possible to mine Bitcoin and many other cryptocurrencies using a CPU (Central...
28/12/2020

Setup Passwordless Login to Servers via SSH

As a Linux system administrator, you will be configuring and tweaking a lot of Linux servers frequently. So, you have to...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Check proxy trên trang nào chuẩn nhất❓
01/11/2023

Thuê Proxy chạy Google Ads / Cần chú ý gì khi chọn proxy và email chạy G.G ads?
12/10/2023

Thuê proxy 4G ở đâu uy tín, giá rẻ, chất lượng?
05/10/2023

Vì sao cần thuê proxy xoay? Địa chỉ cung cấp proxy xoay uy tín
05/10/2023

Thuê proxy v6 kéo view Youtube ở đâu uy tín, chất lượng?
05/10/2023