github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/encrypt/license.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package encrypt
     7  
     8  import (
     9  	"encoding/base64"
    10  	"math/rand"
    11  	"time"
    12  )
    13  
    14  func EncryptLicense(plainText, sourceKey []byte, shiftKey byte, shiftArray []int64) (string, error) {
    15  	source := transferBytes(sourceKey, shiftArray)
    16  	key := transformBytes(source, shiftKey)
    17  	cipherText, err := AesGcmEncrypt(key, plainText)
    18  	if err != nil {
    19  		return "", err
    20  	}
    21  	return base64.StdEncoding.EncodeToString(cipherText), nil
    22  }
    23  
    24  func DecryptLicense(cipherString string, sourceKey []byte, shiftKey byte, shiftArray []int64) ([]byte, error) {
    25  	cipherText, err := base64.StdEncoding.DecodeString(cipherString)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  	source := transferBytes(sourceKey, shiftArray)
    30  	key := transformBytes(source, shiftKey)
    31  	return AesGcmDecrypt(key, cipherText)
    32  }
    33  
    34  func transformBytes(source []byte, shift byte) []byte {
    35  	result := make([]byte, len(source))
    36  
    37  	for i, r := range source {
    38  		ascii := (r + shift) % 128
    39  		result[i] = ascii + 128
    40  	}
    41  
    42  	return result
    43  }
    44  
    45  func transferBytes(source []byte, indexArray []int64) []byte {
    46  	result := make([]byte, len(indexArray))
    47  	sourceLen := len(source)
    48  
    49  	for i, index := range indexArray {
    50  		result[i] = source[int(index)%sourceLen]
    51  	}
    52  
    53  	return result
    54  }
    55  
    56  func generateRandomArray(length int) []int {
    57  	rand.Seed(time.Now().UnixNano())
    58  	randomArray := make([]int, length)
    59  
    60  	for i := 0; i < length; i++ {
    61  		randomArray[i] = rand.Int()
    62  	}
    63  
    64  	return randomArray
    65  }