zoukankan      html  css  js  c++  java
  • Java JS SHA256

    本来想用MD5做散列来做密码传输的,无奈现在字典满天飞,而且已经被碰撞破解了。后打算用SHA1,但是到MD5.JS 上一看,人家作者推荐用SHA256或者更强的。好吧,那就改用SHA256好了。

    服务器端

    JAVA的MessageDigest类直接可以做SHA散列,不过散列完以后是Byte[]类型数据,所以还要再处理一下,使用apache的commons-codec库来做,就不自己写了。

    commons-codec库的下载地址

    http://commons.apache.org/proper/commons-codec/download_codec.cgi

    代码是:(标红的是关键语句)

    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    
    import org.apache.commons.codec.binary.Hex;
    
    
    public class TestSHA {
        public static void main(String args[]){
            String text = "123456123456";
            MessageDigest digest;
            try {
                digest = MessageDigest.getInstance("SHA-256");
                byte[] hash = digest.digest(text.getBytes("UTF-8"));
                String output = Hex.encodeHexString(hash);
                System.out.println(output);
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }

    试了几个字符串:

    123456123456

    SHA-256: 958d51602bbfbd18b2a084ba848a827c29952bfef170c936419b0922994c0589

    hello world

    SHA-256: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

    客户端

    客户端用现成的sha256.js做。

    下载地址:http://www.bichlmeier.info/sha256.html

    测试页面HTML代码:

    <html>
    <head></head>
    <body>
    <script type="text/javascript" src="sha256_2.js">
    </script>
    <script type="text/javascript">
    
      document.write(sha256_digest("hello world"));
    
    </script> 
    </body>
    </html>

    页面输出:

    b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

    可以看到跟上面的是匹配的。

    小结

    散列算法本身只能防止由截获的信息逆推回密码明文,但是无法保证密码传输时候的安全性。所以,在使用时,最好还是使用加盐的方式并且加上从服务器端传来的随机数作为验证码,防止黑客使用被截获的用户ID+密码来通过验证。加入随机验证码后,散列后产生的字串就变成了一次性的校验密码,例如:

    SHA256(SHA256(userID+password) + 验证码)

    验证码通过session传输,难逃session劫持的危险。所以,如果要保证完全的传输安全性,还要做防session劫持的处理,比如将cookieID绑定为MAC地址等。

    但是以上的所有做法都无法避免键盘记录器的盗窃方式。所以不适合用在跟钱打交道的场合。只能防止普通应用网站客户密码信息的暴露。

  • 相关阅读:
    warning: already initialized constant FileUtils::VERSION
    manjaro开启sdd trim
    manjaro i3 sound soft
    archlinux or manjaro install pg gem
    rails 5.2 启动警告 warning: previous definition of VERSION was here和bootsnap
    react config test env with jest and create-react-app 1
    Python pyQt4/PyQt5 学习笔记4(事件和信号)
    MacOS 安装PyQt5
    笔者使用macOS的一些经验点滴记录1
    win7 64位系统下读写access数据库以及安装了office32位软件再安装64位odbc的方法
  • 原文地址:https://www.cnblogs.com/elaron/p/3010375.html
Copyright © 2011-2022 走看看