60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package services
|
|
|
|
import (
|
|
helper "api-service/internal/helpers/bpjs"
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
)
|
|
|
|
// ResponseVclaim decrypts the encrypted response from VClaim API
|
|
func ResponseVclaim(encrypted string, key string) (string, error) {
|
|
if encrypted == "" {
|
|
return "", errors.New("encrypted response is empty")
|
|
}
|
|
|
|
if key == "" {
|
|
return "", errors.New("decryption key is empty")
|
|
}
|
|
|
|
cipherText, err := base64.StdEncoding.DecodeString(encrypted)
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to decode base64: %w", err)
|
|
}
|
|
|
|
hash := sha256.Sum256([]byte(key))
|
|
block, err := aes.NewCipher(hash[:])
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to create cipher: %w", err)
|
|
}
|
|
|
|
if len(cipherText) < aes.BlockSize {
|
|
return "", errors.New("cipherText too short")
|
|
}
|
|
|
|
iv := hash[:aes.BlockSize]
|
|
if len(cipherText)%aes.BlockSize != 0 {
|
|
return "", errors.New("cipherText is not a multiple of the block size")
|
|
}
|
|
|
|
mode := cipher.NewCBCDecrypter(block, iv)
|
|
mode.CryptBlocks(cipherText, cipherText)
|
|
|
|
// Unpad the decrypted data
|
|
cipherText, err = helper.Unpad(cipherText, aes.BlockSize)
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to unpad: %w", err)
|
|
}
|
|
|
|
// Decompress the data
|
|
data, err := helper.DecompressFromEncodedUriComponent(string(cipherText))
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to decompress: %w", err)
|
|
}
|
|
|
|
return data, nil
|
|
}
|