5 frammenti di codice Golang per la sicurezza informatica

Apr 22 2023
Golang è uno dei linguaggi più popolari per la sicurezza informatica, grazie alla sua potente libreria standard e al supporto simultaneo; in questo post, spiegherò 10 frammenti di codice che potrebbero aiutarti nel tuo progetto. Funzione di hashing (SHA-256) Con questa funzione, puoi calcolare SHA-256, che può essere utile per archiviare le password nel DB, convalidare l'integrità dei file, ecc.
Generato utilizzando Lexica

Golang è uno dei linguaggi più popolari per la sicurezza informatica, grazie alla sua potente libreria standard e al supporto simultaneo; in questo post, spiegherò 10 frammenti di codice che potrebbero aiutarti nel tuo progetto.

Funzione di hashing (SHA-256)

Con questa funzione, puoi calcolare SHA-256, che può essere utile per archiviare le password nel DB, convalidare l'integrità dei file, ecc.

// This is a simple Go program that demonstrates the usage of SHA-256 hashing.
package main

import (
 "crypto/sha256" // Import the crypto/sha256 package for hashing.
 "encoding/hex"   // Import the encoding/hex package for hexadecimal encoding.
 "fmt"            // Import the fmt package for formatted I/O.
)

// hashSHA256 takes a string as input and returns its SHA-256 hash in hexadecimal format.
func hashSHA256(data string) string {
 hasher := sha256.New()           // Create a new SHA-256 hasher.
 hasher.Write([]byte(data))        // Write the input data as bytes to the hasher.
 return hex.EncodeToString(hasher.Sum(nil)) // Compute the hash, encode it as a hexadecimal string, and return it.
}

func main() {
 data := "This is a sample data to hash." // Define the data to be hashed.
 hash := hashSHA256(data)                // Call the hashSHA256 function to compute the hash.
 fmt.Println("SHA-256 Hash:", hash)      // Print the computed hash.
}

Base64 è un metodo di codifica comune per la trasmissione di dati binari come testo e la funzione seguente può codificare o decodificare i dati in Base64.

// This is a simple Go program that demonstrates the usage of Base64 encoding and decoding.
package main

import (
 "encoding/base64" // Import the encoding/base64 package for Base64 encoding and decoding.
 "fmt"             // Import the fmt package for formatted I/O.
)

// base64Encode takes a byte slice as input and returns its Base64 encoded string.
func base64Encode(data []byte) string {
 return base64.StdEncoding.EncodeToString(data)
}

// base64Decode takes a Base64 encoded string as input and returns the decoded byte slice and an error if any.
func base64Decode(data string) ([]byte, error) {
 return base64.StdEncoding.DecodeString(data)
}

func main() {
 data := "Sample data for Base64 encoding." // Define the data to be encoded.
 encoded := base64Encode([]byte(data))      // Call the base64Encode function to encode the data.
 fmt.Println("Encoded data:", encoded)      // Print the encoded data.

 // Call the base64Decode function to decode the encoded data, and handle any errors that may occur.
 decoded, err := base64Decode(encoded)
 if err != nil {
  fmt.Println("Error decoding data:", err)
  return
 }
 fmt.Println("Decoded data:", string(decoded)) // Print the decoded data.
}

Puoi utilizzare questa funzione se hai bisogno di numeri sicuri e crittograficamente casuali per generare chiavi e sali di crittografia.

// This is a simple Go program that demonstrates the generation of cryptographically secure random numbers.
package main

import (
 "crypto/rand"     // Import the crypto/rand package for generating cryptographically secure random numbers.
 "encoding/binary" // Import the encoding/binary package for converting byte slices to integer values.
 "fmt"             // Import the fmt package for formatted I/O.
)

// generateSecureRandomNumber generates a cryptographically secure random uint64 number and returns it along with an error if any.
func generateSecureRandomNumber() (uint64, error) {
 buf := make([]byte, 8)       // Create a byte slice of size 8.
 _, err := rand.Read(buf)     // Fill the byte slice with random data from the crypto/rand package.
 if err != nil {
  return 0, err          // If an error occurs, return the error.
 }
 return binary.BigEndian.Uint64(buf), nil // Convert the byte slice to a uint64 value and return it.
}

func main() {
 // Call the generateSecureRandomNumber function to generate a secure random number and handle any errors that may occur.
 randomNumber, err := generateSecureRandomNumber()
 if err != nil {
  fmt.Println("Error generating secure random number:", err)
  return
 }
 fmt.Println("Secure random number:", randomNumber) // Print the generated secure random number.
}

Utilizzando le funzioni seguenti, puoi sfruttare le funzionalità di concorrenza di Golang per decifrare le password con il metodo Brute Force.

package main

import (
 "fmt"
 "strings"
 "sync"
)

// The character set used to generate all possible password combinations
const charset = "abcdefghijklmnopqrstuvwxyz"

// The brute force password cracker function. Generates all possible
// combinations of characters from the character set up to a maximum length
// and checks if they match the given password. Uses concurrency to generate
// combinations of different lengths simultaneously.
func bruteForce(password string, maxLength int) string {
 var wg sync.WaitGroup
 // Channel to send matching password guesses
 found := make(chan string)

 // Create goroutines to generate password combinations of different lengths
 for length := 1; length <= maxLength; length++ {
  wg.Add(1)
  go func(length int) {
   defer wg.Done()
   // Generate combinations of the given length and send to the channel
   generateCombinations(charset, length, "", found)
  }(length)
 }

 // Read from the channel until a matching password guess is found
 for passwordGuess := range found {
  if strings.Compare(password, passwordGuess) == 0 {
   close(found)
   return passwordGuess
  }
 }

 return ""
}

// Recursive function to generate all combinations of characters of a given length
func generateCombinations(charset string, length int, prefix string, found chan<- string) {
 // If the desired length is 0, send the generated combination to the channel
 if length == 0 {
  found <- prefix
  return
 }
 // Recursively generate combinations by appending each character from the character set
 for _, c := range charset {
  generateCombinations(charset, length-1, prefix+string(c), found)
 }
}

func main() {
 password := "secret"
 maxLength := 6
 found := bruteForce(password, maxLength)
 if found == "" {
  fmt.Println("Password not found!")
 } else {
  fmt.Println("Password found:", found)
 }
}

Il codice seguente risolve il DNS per un determinato dominio e restituisce tutti gli indirizzi IP.

package main

import (
 "fmt"
 "net"
)

func main() {
 // Domain to resolve
 domain := "example.com"
 // Use the net package to look up the IP address associated with the domain
 ips, err := net.LookupIP(domain)
 if err != nil {
  fmt.Println("Error resolving domain:", err)
  return
 }
 // Print each IP address associated with the domain
 for _, ip := range ips {
  fmt.Println(ip)
 }
}

Elimina i pod Kubernetes con Golang e un pizzico di divertimento! grpc modo semplice!