河豚GoLang加密和Java解密

时间:2018-07-16 07:19:44

标签: java go encryption cryptography blowfish

无法解密Java中的密文,该密文是使用Blowfish在GoLang中加密的。

加密

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\n", 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=

解密

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³

根据输出,GoLang中的加密和Java中的解密不会产生相同的纯文本。最初,认为问题可能与base64编码和解码中涉及的golang字节(0到255)和Java字节(-128到127)有关。但是戳入Java的解密代码,可以使用value & 255正确地处理它。

在golang中解密相同的密文非常有效。 Java中的加密和解密也可以完美地工作。但是其中一个不是加密,而另一个是解密。

我认为加密和解密逻辑是正确的。只猜测可能存在一些特定于语言的语言?密文移植到其他语言进行解密时丢失。

1 个答案:

答案 0 :(得分:2)

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

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

相关问题