aes使用java加密,go解密

版权声明:学习中。。。 https://blog.csdn.net/fangdengfu123/article/details/82997494

java 加密

AESUtil.encrypt(s, pwd)

go 解密

content, err := hex.DecodeString(message.Data)
if err != nil {
	return nil, nil, err
}
tb, err := AesDecrypt(content, secret)
if err != nil {
	return nil, nil, err
}

// aes 解密
func AesDecrypt(crypted, key []byte) ([]byte, error) {
	key = addSuffix(key)
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	blockMode := cipher.NewCBCDecrypter(block, iv)
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	return origData, nil
}


// aes规定秘钥必须是8的倍数,8还不行,所以在这里固定成16
func addSuffix(secret []byte) []byte {
	s := string(secret)
	len := len(s)
	for i:=0; i<16-len; i++ {
		s += "="
	}
	return []byte(s)
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

// aes 加密
func AesEncrypt(origData, key []byte) ([]byte, error) {
	key = addSuffix(key)
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()
	origData = PKCS5Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, iv)
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

// 这个没用
// 使用现有的数据做计算,如果计算结果匹配,说明秘钥正确,如果不匹配,说明秘钥错误
func verifySecret(data *Data, secret []byte) error {
	log.Info("开始验证秘钥")
	ab, err := json.Marshal(data.Account)
	if err != nil {
		return err
	}
	hashes := Hash(ab)
	res, err := AesEncrypt(hashes, secret)
	//log.Infof("进行正向加密: %s", string(res))
	//log.Info(res)
	//log.Info(hex.EncodeToString(res))
	//log.Infof("状态数据的hash: %s", data.Hash)
	//log.Info([]byte(data.Hash))
	//log.Info(hex.EncodeToString([]byte(data.Hash)))
	if err != nil {
		return err
	}
	// bytes.Compare([]byte(data.Hash), res) == 0   该方法比较失败
	// data.Hash == string(res) 					比较失败
	// bytes.Equal([]byte(data.Hash), res)			失败
	// strings.Compare(data.Hash, string(res)) == 0	失败

	if strings.EqualFold(data.Hash, string(res)) {		// 成功
		log.Info("秘钥验证通过")
		return nil
	} else {
		log.Info("秘钥验证失败")
		return verifyKeyErr
	}
}

public class AESUtil {

    //初始化向量,aes 16位
    private static final String IV = "abcdefghijk1mnop";

    //二进制转变为16进制
    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    //将16进制转变为二进制
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    //加密
    public static String encrypt(String content, String keyWord) throws Exception {
        keyWord = addSuffix(keyWord);
        try {
            SecretKeySpec key = new SecretKeySpec(keyWord.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes()));
            byte[] encryptedData = cipher.doFinal(content.getBytes("UTF-8"));
            return parseByte2HexStr(encryptedData);
        } catch (Exception e) {
            throw new Exception("加密失败");
        }
    }

    //解密
    public static String decrypt(String content, String keyWord) throws Exception {
        keyWord = addSuffix(keyWord);
        byte[] contentBytes = parseHexStr2Byte(content);
        try {
            SecretKeySpec key = new SecretKeySpec(keyWord.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes()));
            byte[] result = cipher.doFinal(contentBytes);
            return new String(result, "UTF-8");
        } catch (Exception e) {
            throw new Exception("解密失败");
        }
    }

    public static String addSuffix(String key) {
        int len = key.length();
        if (len >= 16) {
            return key;
        }
        for (int i=0; i<16-len; i++) {
            key += "=";
        }
        return key;
    }

    public static void main(String[] args) throws Exception {

        String content = "梅须逊雪三分白,雪却输梅一段香。";
        //此处使用AES-128-CBC加密模式,key需要为16位
        String password = "********";

        System.out.println("加密前:" + content);
        String encryptResult = AESUtil.encrypt(content, password);
        System.out.println("加密后:" + encryptResult);
        String decryptResult = AESUtil.decrypt(encryptResult,password);
        System.out.println("解密后:" + decryptResult);
    }


}

猜你喜欢

转载自blog.csdn.net/fangdengfu123/article/details/82997494