如何使用Blowfish + Hex获得相同的长度编码

问题描述 投票:0回答:1

我们正在尝试使用Blowfish + Hex编码来对具有相同长度(32)的几个输入字符串进行编码。问题在于,最终编码的字符串并非总是具有与我们期望的长度相同的长度(32个长度的字符串)。在下面找到使用的代码。拜托,您能帮忙建议出什么问题吗?

public static String encrypt(String clear, String key)
{                          
    try
    {
        Security.setProperty("crypto.policy", "unlimited");
        byte [] keyBytes = key.getBytes("ASCII");//toByteArray(key);
        filelogger.info("Key coded in bytes "+keyBytes);
        SecretKeySpec skey = new SecretKeySpec(keyBytes, "Blowfish");
        byte [] clearBytes = clear.getBytes();//toByteArray(clear);
        filelogger.info("Input string coded in bytes "+clearBytes);
        Cipher ci = Cipher.getInstance("Blowfish");                            
        ci.init(Cipher.ENCRYPT_MODE, skey);

        // encrypt the clear bytes value
        byte[] encoded = ci.doFinal(clearBytes);
        filelogger.info("Blowfish output "+encoded);

        return Base64.getEncoder().encodeToString(encoded);
    }
    catch (Exception e)
    {
        filelogger.error("Error while encrypting: " + e.toString());
        logger.error("Error while encrypting: " + e.toString());

        return Base64.getEncoder().encodeToString(new byte[0]);
    }
}

最诚挚的问候

blowfish
1个回答
0
投票

我们已经使用以下解决方案解决了:

  1. 将选项“ Blowfish / ECB / NoPadding”传递给getInstance函数。

    public byte [] cryptoBlowfishECBNopadding(byte [] key,byte [] dati){byte []输出= null;尝试{SecretKeySpec KS =新的SecretKeySpec(key,“ Blowfish”);密码cipher = Cipher.getInstance(“ Blowfish / ECB / NoPadding”);cipher.init(Cipher.ENCRYPT_MODE,KS);输出= cipher.doFinal(dati);返回输出;} catch(Exception ee){logger.error(ee.getMessage());filelogger.error(ee.toString());返回新的字节[0];}}

  2. 对方法的结果进行如下编码:

    byte [] cryptoresult = encryptBlowfishECBNopadding(toByteArray(decriptedki),toByteArray(criptokeyhlr.getKeydata()));字符串stringencriptedki = Hex.encodeHexString(encryptresult).toUpperCase();

以这种方式,每个输出字符串具有相同的长度。

谢谢大家的支持!

© www.soinside.com 2019 - 2024. All rights reserved.