辉尝爪哇 2019-04-23 10:50 采纳率: 100%
浏览 885

AES加密后,登录提示密码长度错误,请大神帮帮忙,谢谢!

1.先用md5加密:

 public static String getMd5(String s) {
        char hexChar[] = {'0', '1', '2', '3', '4', '5', '6',
                '7', '8' , '9', 'a', 'b', 'c', 'd', 'e', 'f','A', 'B', 'C', 'D', 'E', 'F'};
        //md5加密算法的加密对象为字符数组,这里是为了得到加密的对象
        byte[] b = s.getBytes();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(b);
            byte[] b2 = md.digest();// 进行加密并返回字符数组
            char str[] = new char[b2.length << 1];
            int len = 0;
            //将字符数组转换成十六进制串,形成最终的密文
            for (int i = 0; i < b2.length; i++) {
                byte val = b2[i];
                str[len++] = hexChar[(val >>> 4) & 0xf];
                str[len++] = hexChar[val & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

2.再用AES加密,

   /**
     * AES 加密
     * 密钥是apiSecret 的前16位
     * 向量是apiSecret 的后16位
     * @param password
     * @param apiSecret
     * @return
     * @throws Exception
     */
    public static String getAesEncrypt(String password,String apiSecret)throws Exception{
        String key = apiSecret.substring(0,16);
        String iv = apiSecret.substring(16);
        String md5Pass = getMd5(password);

        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("UTF-8"));

        //System.out.println("密码的长度为:"+keyspec.getEncoded().length);
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(md5Pass.getBytes("UTF-8"));
        return bytesToHexString(encrypted);
    }

    public static String bytesToHexString(byte[] bs) {
        StringBuffer sb = new StringBuffer();
        String hex = "";
        for (int i = 0; i < bs.length; i++) {
            hex = Integer.toHexString(bs[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex);
        }
        System.out.println("结果为:"+sb);
        return sb.toString();
    }

结果就提示:登录失败;加密后的密码长度错误

图片说明

  • 写回答

1条回答 默认 最新

  • 毕小宝 博客专家认证 2019-04-23 14:09
    关注

    具体的异常信息是什么?直接搜异常信息可能会找到解决办法的。
    java 的 jce 高版本需要配置 jce_policy-8 .

    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建