我用Kotlin编写了一个小测试,使用密码实例加密一些文本"Hello“,其算法为”AES/CFB8 8/NoPadding“。(我的经验之谈)
我现在正试图在Go中做同样的事情,但是我无法产生同样的结果。我尝试过的所有不同的方法总是产生不同的东西。
为了达到这个目的,下面是我已经看过的线程/示例。
Kotlin代码:
enum class Mode(val mode: Int)
{
ENCRYPT(Cipher.ENCRYPT_MODE),
DECRYPT(Cipher.DECRYPT_MODE),
}
fun createSecret(data: String): SecretKey
{
return SecretKeySpec(data.toByteArray(), "AES")
}
fun newCipher(mode: Mode): Cipher
{
val secret = createSecret("qwdhyte62kjneThg")
val cipher = Cipher.getInstance("AES/CFB8/NoPadding")
cipher.init(mode.mode, secret, IvParameterSpec(secret.encoded))
return cipher
}
fun runCipher(data: ByteArray, cipher: Cipher): ByteArray
{
val output = ByteArray(data.size)
cipher.update(data, 0, data.size, output)
return output
}
fun main()
{
val encrypter = newCipher(Mode.ENCRYPT)
val decrypter = newCipher(Mode.DECRYPT)
val iText = "Hello"
val eText = runCipher(iText.toByteArray(), encrypter)
val dText = runCipher(eText, decrypter)
val oText = String(dText)
println(iText)
println(Arrays.toString(eText))
println(Arrays.toString(dText))
println(oText)
}Go代码:
func TestCipher(t *testing.T) {
secret := newSecret("qwdhyte62kjneThg")
encrypter := newCipher(secret, ENCRYPT)
decrypter := newCipher(secret, DECRYPT)
iText := "Hello"
eText := encrypter.run([]byte(iText))
dText := decrypter.run(eText)
oText := string(dText)
fmt.Printf("%s\n%v\n%v\n%s\n", iText, eText, dText, oText)
}
type Mode int
const (
ENCRYPT Mode = iota
DECRYPT
)
type secret struct {
Data []byte
}
type cipherInst struct {
Data cipher2.Block
Make cipher2.Stream
}
func newSecret(text string) *secret {
return &secret{Data: []byte(text)}
}
func newCipher(data *secret, mode Mode) *cipherInst {
cip, err := aes.NewCipher(data.Data)
if err != nil {
panic(err)
}
var stream cipher2.Stream
if mode == ENCRYPT {
stream = cipher2.NewCFBEncrypter(cip, data.Data)
} else {
stream = cipher2.NewCFBDecrypter(cip, data.Data)
}
return &cipherInst{Data: cip, Make: stream}
}
func (cipher *cipherInst) run(dataI []byte) []byte {
out := make([]byte, len(dataI))
cipher.Make.XORKeyStream(out, dataI)
return out
}Kotlin代码生成输出:
Hello
[68, -97, 26, -50, 126]
[72, 101, 108, 108, 111]
Hello但是,Go代码生成输出:
Hello
[68 97 242 158 187]
[72 101 108 108 111]
Hello在这一点上,这个问题已经在很大程度上停止了我正在研究的项目的进展。任何关于我错过了什么或者做错了什么的信息都会有帮助。
发布于 2019-09-15 01:31:06
解决方案是手动实现CFB8,因为内置实现默认为CFB128。
由克斯特亚创建并由Ilmari (here)修复的实现。
https://stackoverflow.com/questions/57540370
复制相似问题