2 回答

TA貢獻1801條經驗 獲得超16個贊
所以重點:
為了應用鹽并派生正確的密鑰,
pbkdf2.Key()
必須使用如下所示Spring Security 中的
nonce
(或Initialization Vector
)大小是 16 個字節,而不是 12 個字節go
下面的摘錄省略了錯誤處理,只是為了強調解決方案的本質:
const nonceSize = 16
func decryptWithAes256GcmPbkdf2(cipherBytes []byte, password string, salt string) (string) {
key := pbkdf2.Key([]byte(password), []byte(salt), 1024, 32, sha1.New)
c, _ := aes.NewCipher(key)
gcm, _ := cipher.NewGCMWithNonceSize(c, nonceSize)
plaintextBytes, _ := gcm.Open(nil, cipherBytes[:nonceSize], cipherBytes[nonceSize:], nil)
return string(plaintextBytes)
}

TA貢獻1993條經驗 獲得超6個贊
盡管問題與“更強”的解密有關。
請參閱:https ://docs.spring.io/spring-security/site/docs/4.2.20.RELEASE/apidocs/org/springframework/security/crypto/encrypt/Encryptors.html
我想舉一個“標準”解密的完整例子來擴展前面的答案。
就我而言,任務是在 Go 中實現以下 Java 代碼:
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
...
private static final String SALT = "123456789abcdef0"; // hex
public static String decrypt(final String encryptedText, final String password) {
TextEncryptor encryptor = Encryptors.text(password, SALT);
return encryptor.decrypt(encryptedText);
}
翻譯成 Go 的代碼:
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha1"
"encoding/hex"
"fmt"
"strings"
"golang.org/x/crypto/pbkdf2"
)
func decryptWithAes256CbcPbkdf2(cipherBytes []byte, passwordBytes []byte, saltBytes []byte) string {
key := pbkdf2.Key(passwordBytes, saltBytes, 1024, 32, sha1.New)
if len(key) != 32 {
panic(fmt.Sprintf("Unexpected key length (!= 32) '%s' %d", key, len(key)))
}
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
if len(cipherBytes) < aes.BlockSize {
panic("ciphertext too short")
}
iv := cipherBytes[:aes.BlockSize]
cipherBytes = cipherBytes[aes.BlockSize:]
if len(cipherBytes)%aes.BlockSize != 0 {
panic("ciphertext is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(cipherBytes, cipherBytes)
return strings.Trim(string(cipherBytes), "\b")
}
func main() {
cipherText := "05589d13fe6eedceae78fe099eed2f6b238ac7d4dbb62c281ccdc9401b24bb0c"
cipherBytes, _ := hex.DecodeString(cipherText)
passwordText := "12345"
passwordBytes := []byte(passwordText)
saltText := "123456789abcdef0"
saltBytes, _ := hex.DecodeString(saltText)
plainText := decryptWithAes256CbcPbkdf2(cipherBytes, passwordBytes, saltBytes)
fmt.Println(plainText)
}
- 2 回答
- 0 關注
- 533 瀏覽
添加回答
舉報