河豚GoLang加密和Java解密

Unable to decrypt the cipher text in Java which is ecrypted in GoLang using Blowfish.

Encryption

import (
    "testing"
    "golang.org/x/crypto/blowfish"
    "github.com/andreburgaud/crypt2go/ecb"
    "github.com/andreburgaud/crypt2go/padding"
    "fmt"
    "encoding/base64"
)

func TestEncrypt(t *testing.T) {

    bytes := []byte("cap")
    key := []byte("1c157d26e2db9a96a556e7614e1fbe36")

    encByte := encrypt(bytes, key)
    enc := base64.StdEncoding.EncodeToString(encByte)
    fmt.Printf("ENC - %s
", enc)
}

func encrypt(pt, key []byte) []byte {
    block, err := blowfish.NewCipher(key)
    if err != nil {
        panic(err.Error())
    }
    mode := ecb.NewECBEncrypter(block)
    padder := padding.NewPkcs5Padding()
    pt, err = padder.Pad(pt) // padd last block of plaintext if block size less than block cipher size
    if err != nil {
        panic(err.Error())
    }
    ct := make([]byte, len(pt))
    mode.CryptBlocks(ct, pt)
    return ct
}

// Output
// ENC - AP9atM49v8o=

Decryption

import lombok.SneakyThrows;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import static java.util.Base64.getDecoder;
import static java.util.Base64.getEncoder;

public class UserAuthenticationFilter {

    public static void main(String[] args) throws Exception {
        String key = "1c157d26e2db9a96a556e7614e1fbe36";
        System.out.println(decrypt(getDecoder().decode("AP9atM49v8o="), key));

        // encryption and decryption verification
        // String plainText = "cap";
        // String cipher = encrypt(plainText, key);
        // String decrypted = decrypt(getDecoder().decode(enc), key);
        // assert decrypted.equals(plainText);
    }

    @SneakyThrows
    public static String encrypt(String plainText, String key) {
        byte[] myKeyByte = hexToBytes(key);
        SecretKeySpec skeySpec = new SecretKeySpec(myKeyByte, "Blowfish");
        Cipher ecipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
        ecipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        byte[] src = ecipher.doFinal(plainText.getBytes("ISO-8859-1"));
        return getEncoder().encodeToString(src);
    }

    @SneakyThrows
    public static String decrypt(byte[] cipherContent, String key) {
        byte[] myKeyByte = hexToBytes(key);
        SecretKeySpec skeySpec = new SecretKeySpec(myKeyByte, "Blowfish");
        Cipher dcipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
        dcipher.init(2, skeySpec);
        byte[] dcontent = dcipher.doFinal(cipherContent);
        return (new String(dcontent, "ISO-8859-1")).trim();
    }

    private static byte[] hexToBytes(String str) {
        if (str == null) {
            return null;
        } else if (str.length() < 2) {
            return null;
        } else {
            int len = str.length() / 2;
            byte[] buffer = new byte[len];

            for(int i = 0; i < len; ++i) {
                buffer[i] = (byte)Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
            }

            return buffer;
        }
    }

}

// Output
// BY x³

As per the outputs, encryption in GoLang and decryption in Java doesn't produce the same plain text. Initially, thought the problem might be related to golang's byte (0 to 255) and java's byte (-128 to 127) involved in base64 encoding and decoding. But poking in Java's decryption code, it's handled correctly with value & 255.

Decryption of the same cipher text in golang works perfectly. Also encryption and decryption in Java works perfectly. But not the encryption in one and decryption in other.

I think the encryption and decryption logic were correct. Only guess might be there's some language specific ??? is missing when the cipher text is ported to other language for decryption.

douliang2935
douliang2935 疑难杂症..!问题在于将密钥转换为byte[],而不是解码十六进制,只是将其转换为字节。您可以将其发布为答案。
大约 2 年之前 回复
dongtang1966
dongtang1966 我相信您的问题出在thrgolang示例的字节中。我不是golang的专家,但我假设您是根据字符串字符创建一个字节数组,而不是对十六进制值进行解码
大约 2 年之前 回复
dsmgcse8876
dsmgcse8876 将信息编辑到问题中
大约 2 年之前 回复
doulin3510
doulin3510 为了测试Java中的加密和解密,我使用Blowfish/ECB/PKCS5Padding进行加密,并使用Blowfish/ECB/NoPadding进行解密,这可以按预期工作。所以我认为,如果填充有问题,它会被BadPaddingException吐出
大约 2 年之前 回复
doupa2871
doupa2871 在解密中,不指定填充,而在加密中,则使用填充。
大约 2 年之前 回复

1个回答



  key:= [] byte(“ 1c157d26e2db9a96a556e7614e1fbe36”)
</ code> </ pre>

我相信这段代码返回字符串本身的字节数组,而不是十六进制的解码值。 要获得有效的密钥,您可以尝试使用十六进制解码 </ p>
< / DIV>

展开原文

原文

key := []byte("1c157d26e2db9a96a556e7614e1fbe36")

I believe this piece of code returns byte array of the string itself, not hex decoded value. To get a valid key you may try to use hex decoding

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐