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

Lý do tại sao bạn nên sử dụng proxy khi truy cập web đen

Khi bạn cần sử dụng proxy để truy cập vào các trang web bị chặn hoặc giới hạn về địa chỉ...
27/02/2023

Install Numix Theme on Ubuntu

Of course, the interface is the classic one that signifies Ubuntu. However, for us, it’s bound to become a boring thing....
29/12/2020

Linux Mint 19 Release date

Even though Linux Mint 18.3, codenamed Sylvia, was released only recently to a huge applause of Linux fans around the world,...
28/12/2020
Bài Viết

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

Dịch Vụ Xây Dựng Hệ Thống Peering Với Internet Exchange (IXP)
04/04/2025

Dịch Vụ Triển Khai VPN Site-to-Site & Remote Access
04/04/2025

Dịch Vụ Thiết Lập Hệ Thống Tường Lửa (Firewall)
04/04/2025

Dịch Vụ Triển Khai Hệ Thống Ảo Hóa & Cloud
04/04/2025

Dịch Vụ Triển Khai Hệ Thống Ceph
04/04/2025