Created
          August 19, 2019 03:48 
        
      - 
      
- 
        Save asahasrabuddhe/71284f7e85412da664963ecb79ce8aed to your computer and use it in GitHub Desktop. 
    encrypt decrypt
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package main | |
| import ( | |
| "crypto/aes" | |
| "crypto/cipher" | |
| "crypto/sha256" | |
| "encoding/base64" | |
| "encoding/hex" | |
| "fmt" | |
| ) | |
| var ( | |
| KEY = []byte("rappier_simple_secret_key") | |
| IV = []byte("rappier_simple_secret_iv") | |
| ) | |
| func main() { | |
| h := sha256.New() | |
| h.Write(KEY) | |
| KEY = h.Sum(nil) | |
| h.Reset() | |
| h.Write(IV) | |
| IV = h.Sum(nil)[:16] | |
| fmt.Println("Key", hex.EncodeToString(KEY)) | |
| fmt.Println("IV", hex.EncodeToString(IV)) | |
| // This ciphertext was generated by the PHP module | |
| de := "rDAnykzTorR5/SgpdD7slA==" | |
| q, err := decrypt(KEY, IV, de) | |
| fmt.Println(string(q), err) | |
| } | |
| // Returns slice of the original data without padding. | |
| func pkcs7Unpad(data []byte, blocklen int) ([]byte, error) { | |
| if blocklen <= 0 { | |
| return nil, fmt.Errorf("invalid blocklen %d", blocklen) | |
| } | |
| if len(data)%blocklen != 0 || len(data) == 0 { | |
| return nil, fmt.Errorf("invalid data len %d", len(data)) | |
| } | |
| padlen := int(data[len(data)-1]) | |
| if padlen > blocklen || padlen == 0 { | |
| return nil, fmt.Errorf("invalid padding") | |
| } | |
| // check padding | |
| pad := data[len(data)-padlen:] | |
| for i := 0; i < padlen; i++ { | |
| if pad[i] != byte(padlen) { | |
| return nil, fmt.Errorf("invalid padding") | |
| } | |
| } | |
| return data[:len(data)-padlen], nil | |
| } | |
| func decrypt(key []byte, iv []byte, encrypted string) ([]byte, error) { | |
| data, err := base64.StdEncoding.DecodeString(encrypted) | |
| if err != nil { | |
| return nil, err | |
| } | |
| if len(data) == 0 || len(data)%aes.BlockSize != 0 { | |
| return nil, fmt.Errorf("bad blocksize(%v), aes.BlockSize = %v\n", len(data), aes.BlockSize) | |
| } | |
| c, err := aes.NewCipher(key) | |
| if err != nil { | |
| return nil, err | |
| } | |
| cbc := cipher.NewCBCDecrypter(c, iv) | |
| cbc.CryptBlocks(data, data) | |
| out, err := pkcs7Unpad(data, aes.BlockSize) | |
| if err != nil { | |
| return out, err | |
| } | |
| return out, nil | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment