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 Trim Strings in PHP

The function of trimming strings is to remove the unwanted characters from string data.  String data requires trimming...
28/12/2020

How to Install and Play War Thunder on Ubuntu

After spending years on Windows, adjusting to a different operating system can be quite hectic for some people. Those people...
29/12/2020

Bash for loop examples

Loops are a very essential part of any type of programming or scripting languages. Like any other standard programming,...
29/12/2020
Bài Viết

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

Reliable IPv4 and IPv6 Subnet Rental Services: The Perfect Solution for Global Businesses
23/12/2024

Tìm Hiểu Về Thuê Proxy US – Lợi Ích và Cách Sử Dụng Hiệu Quả
11/12/2024

Mua Proxy V6 Nuôi Facebook Spam Hiệu Quả Tại Onetcomvn
03/06/2024

Hướng dẫn cách sử dụng ProxyDroid để duyệt web ẩn danh
03/06/2024

Mua proxy Onet uy tín tại Onet.com.vn
03/06/2024