zoukankan      html  css  js  c++  java
  • java aes encrypt

    本次使用aes 对称加密算法。

    选用aes的原因是,可以还原加密串。 程序如下:

        public static String encode(String content){
            KeyGenerator keyGen;
            try {
                keyGen = KeyGenerator.getInstance("AES");
                keyGen.init(128,new SecureRandom(SALT));
                
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    //坑在这里 Key key
    = new SecretKeySpec(keyGen.getKey().getEncoded(),"AES"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] bytes = cipher.doFinal(content.getBytes("utf-8")); StringBuilder sb = new StringBuilder(); for(int i=0;i<bytes.length;i++){ sb.append(bytes[i]+","); } sb.setLength(sb.length()-1); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }

    这样就可以实现加密了。

    问题在坑的这一行。

    是这样的, 一般来说,我们对 db connection的 用户名和密码进行加密计算,然后在其他机器上进行解密,然后进行连接。

    我本地使用该程序运算出的加密字符串在服务器上无法decode。

    经排查,问题出现在

    keyGen.getKey().getEncoded()  类型是 byte[]
    因为服务器和我本机的生成的表达式完全不同。导致服务器无法解密本地生成的字符串。
    这个就有点蛋疼了。 于是,切换成固定的byte[]
    服务器就可以解析本地生成的字符串了。
  • 相关阅读:
    【Codeforces 349B】Color the Fence
    【Codeforces 459D】Pashmak and Parmida's problem
    【Codeforces 467C】George and Job
    【Codeforces 161D】Distance in Tree
    【Codeforces 522A】Reposts
    【Codeforces 225C】Barcode
    【Codeforces 446A】DZY Loves Sequences
    【Codeforces 429B】Working out
    【Codeforces 478C】Table Decorations
    【Codeforces 478C】Table Decorations
  • 原文地址:https://www.cnblogs.com/lykm02/p/4970485.html
Copyright © 2011-2022 走看看