shiro-密码比较的设计 CredentialsMatcher -为什么Java中的密码优先使用 char[] 而不是String?

本文主要是介绍shiro-密码比较的设计 CredentialsMatcher -为什么Java中的密码优先使用 char[] 而不是String?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

密码比较
昨天的时候,笔者仔细的追踪了,整个获取信息的主要的设计,通过用户的唯一标识得到 AuthenticationInfo 然后和 AuthenticationToken (用户名 密码),进行比较! 有一个专门的设计类,用来处理密码匹配的比较的。而且很复杂~

AuthenticatingRealm中有一个成员变量
private CredentialsMatcher credentialsMatcher; 凭据的匹配,就是密码的比较辣。这个是一个接口!默认的实现为 SimpleCredentialsMatcher 这个类!都是面向接口编程的~

AuthenticatingRealm 类中的一个函数,通过匹配的实现,进行密码信息的比较工作。

 protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {CredentialsMatcher cm = getCredentialsMatcher();if (cm != null) {//if (!cm.doCredentialsMatch(token, info)) {//not successful - throw an exception to indicate this:String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";throw new IncorrectCredentialsException(msg);}} else {throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " +"credentials during authentication.  If you do not wish for credentials to be examined, you " +"can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");}}

看看比较类信息的继承图 可以看出来这里的SimpleCredentialsMatcher 只是简单的实现加密,下面的Hash的单向加密算法MD5,SHA子类的算法 http://www.cnblogs.com/crazylqy/p/4813483.html 对此不是非常的了解,一般的JDK都是要实现的。接下来就是看看这个密码匹配的整个炉子实现的解析!,你发现没有,无论是realm门面还是我们的密码匹配都是设计的扩展性十足的,这样的学习列子,学习看源码好处真的非常棒!
这里写图片描述

CredentialsMatcher 接口,这个接口呢,结合了昨天的,一个是我们登录的时候密码和用户名,AuthenticationToken的实现类 和 通过用户名获得的当前用户的所有的信息,昨天已经很详细的解析了,比如权限,角色信息等等。AuthenticationInfo的实现类 SimpleAuthenticationInfo 。这两个信息的凭证也是密码进行比较,就是实现的意义。

/*** Interface implemented by classes that can determine if an AuthenticationToken's provided* credentials matches a corresponding account's credentials stored in the system.** <p>Simple direct comparisons are handled well by the* {@link SimpleCredentialsMatcher SimpleCredentialsMatcher}.  If you* hash user's credentials before storing them in a realm (a common practice), look at the* {@link HashedCredentialsMatcher HashedCredentialsMatcher} implementations,* as they support this scenario.** @see SimpleCredentialsMatcher* @see AllowAllCredentialsMatcher* @see Md5CredentialsMatcher* @see Sha1CredentialsMatcher* @since 0.1*/
public interface CredentialsMatcher {/*** Returns {@code true} if the provided token credentials match the stored account credentials*/boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info);}

CodecSupport这个抽象类,是实现了一个Utis方法的类,充满了String,Char Byte之间的转换。


/*** Base abstract class that provides useful encoding and decoding operations, especially for character data.** @since 0.9*/
public abstract class CodecSupport {public static final String PREFERRED_ENCODING = "UTF-8";/*** @param chars the character array to be converted to a byte array.* @return the byte array of the UTF-8 encoded character array.*/public static byte[] toBytes(char[] chars) {return toBytes(new String(chars), PREFERRED_ENCODING);}public static byte[] toBytes(char[] chars, String encoding) throws CodecException {return toBytes(new String(chars), encoding);}public static byte[] toBytes(String source) {return toBytes(source, PREFERRED_ENCODING);}/*** Converts the specified source to a byte array via the specified encoding, throwing a* {@link CodecException CodecException} if the encoding fails.*/public static byte[] toBytes(String source, String encoding) throws CodecException {try {return source.getBytes(encoding);} catch (UnsupportedEncodingException e) {String msg = "Unable to convert source [" + source + "] to byte array using " +"encoding '" + encoding + "'";throw new CodecException(msg, e);}}/*** Converts the specified byte array to a String using * 将bytes转换为String */public static String toString(byte[] bytes) {return toString(bytes, PREFERRED_ENCODING);}/*** Converts the specified byte array to a String using the specified character encoding.  This implementation* does the same thing as <code>new {@link String#String(byte[], String) String(byte[], encoding)}</code>, but will* wrap any {@link UnsupportedEncodingException} with a nicer runtime {@link CodecException}, allowing you to* decide whether or not you want to catch the exception or let it propagate.*/public static String toString(byte[] bytes, String encoding) throws CodecException {try {return new String(bytes, encoding);} catch (UnsupportedEncodingException e) {String msg = "Unable to convert byte array to String with encoding '" + encoding + "'.";throw new CodecException(msg, e);}}/*** Returns the specified byte array as a character array using the* bytes ->String->Char* {@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING}.*/public static char[] toChars(byte[] bytes) {return toChars(bytes, PREFERRED_ENCODING);}public static char[] toChars(byte[] bytes, String encoding) throws CodecException {return toString(bytes, encoding).toCharArray();}protected boolean isByteSource(Object o) {return o instanceof byte[] || o instanceof char[] || o instanceof String ||o instanceof ByteSource || o instanceof File || o instanceof InputStream;}protected byte[] toBytes(Object o) {if (o == null) {String msg = "Argument for byte conversion cannot be null.";throw new IllegalArgumentException(msg);}if (o instanceof byte[]) {return (byte[]) o;} else if (o instanceof ByteSource) {return ((ByteSource) o).getBytes();} else if (o instanceof char[]) {return toBytes((char[]) o);} else if (o instanceof String) {return toBytes((String) o);} else if (o instanceof File) {return toBytes((File) o);} else if (o instanceof InputStream) {return toBytes((InputStream) o);} else {return objectToBytes(o);}}protected String toString(Object o) {if (o == null) {String msg = "Argument for String conversion cannot be null.";throw new IllegalArgumentException(msg);}if (o instanceof byte[]) {return toString((byte[]) o);} else if (o instanceof char[]) {return new String((char[]) o);} else if (o instanceof String) {return (String) o;} else {return objectToString(o);}}protected byte[] toBytes(File file) {if (file == null) {throw new IllegalArgumentException("File argument cannot be null.");}try {return toBytes(new FileInputStream(file));} catch (FileNotFoundException e) {String msg = "Unable to acquire InputStream for file [" + file + "]";throw new CodecException(msg, e);}}protected byte[] toBytes(InputStream in) {if (in == null) {throw new IllegalArgumentException("InputStream argument cannot be null.");}final int BUFFER_SIZE = 512;ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);byte[] buffer = new byte[BUFFER_SIZE];int bytesRead;try {while ((bytesRead = in.read(buffer)) != -1) {out.write(buffer, 0, bytesRead);}return out.toByteArray();} catch (IOException ioe) {throw new CodecException(ioe);} finally {try {in.close();} catch (IOException ignored) {}try {out.close();} catch (IOException ignored) {}}}protected byte[] objectToBytes(Object o) {String msg = "The " + getClass().getName();throw new CodecException(msg);}protected String objectToString(Object o) {return o.toString();}
}

SimpleCredentialsMatcher 只是简单的进行了扩展,没有使用到加密MD5子类的信息~


public class SimpleCredentialsMatcher extends CodecSupport implements CredentialsMatcher {protected Object getCredentials(AuthenticationToken token) {return token.getCredentials();}protected Object getCredentials(AuthenticationInfo info) {return info.getCredentials();}protected boolean equals(Object tokenCredentials, Object accountCredentials) {if (log.isDebugEnabled()) {log.debug("Performing credentials equality check for tokenCredentials of type [" +tokenCredentials.getClass().getName() + " and accountCredentials of type [" +accountCredentials.getClass().getName() + "]");}if (isByteSource(tokenCredentials) && isByteSource(accountCredentials)) {if (log.isDebugEnabled()) {log.debug("Both credentials arguments can be easily converted to byte arrays.  Performing " +"array equals comparison");}byte[] tokenBytes = toBytes(tokenCredentials);byte[] accountBytes = toBytes(accountCredentials);return Arrays.equals(tokenBytes, accountBytes);} else {return accountCredentials.equals(tokenCredentials);}}/*** 判断一下是否相等,得到凭证!这里使用Object的意思也是为了各种可能的扩展吧**/public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {Object tokenCredentials = getCredentials(token);Object accountCredentials = getCredentials(info);return equals(tokenCredentials, accountCredentials);}}

下面的Hash的处理,不太想去看了,各种版本,有很多废弃啦,写的很烦~~~,不过知道意思就好了。

为什么Java中的密码优先使用 char[] 而不是String?
https://www.zhihu.com/question/36734157 知乎答的说的不错!但是最好还是加密
String在Java中是不可变对象,如果作为普通文本存储密码,那么它会一直存在内存中直至被垃圾收集器回收。这就意味着一旦创建了一个字符串,如果另一个进程把尝试内存的数据导出(dump),在GC进行垃圾回收之前该字符串会一直保留在内存中,那么该进程就可以轻易的读取到该字符串。

而对于数组,可以在使用该数组之后显示地擦掉数组中的内容,你可以使用其他不相关的内容把数组内容覆盖掉,例如,在使用完密码后,我们将char[]的值均赋为0,如果有人能以某种方式看到内存映像,他只能看到一串0;而如果我们使用的是字符串,他们便能以纯文本方式看到密码。因此,使用char[]是相对安全的。

推荐使用char[],这是从安全角度来选择的。但是,我们应当注意到,即使是用char[]处理密码也只是降低被攻击的概率而已,还是会有其他方法攻破数组处理的密码。

另一方面,使用String的时候,你可能会不经意间将密码打印出来(如log文件),此时,使用char[]就显得更加的安全了,如:

public static void main(String[] args) {
Object pw = “Password”;
System.out.println(“String: ” + pw);

pw = "Password".toCharArray();
System.out.println("Array: " + pw);

}

此时的输出结果将会是

String: PasswordArray: [C@5829428e

实际上,即使使用了char[]保存密码也仍然不够安全,内存中还是可能会有这串数据的零碎副本,因此,建议使用加密的密码来代替普通的文本字符串密码,并且在使用完后记得立即清除。

这篇关于shiro-密码比较的设计 CredentialsMatcher -为什么Java中的密码优先使用 char[] 而不是String?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1091612

相关文章

Java方法重载与重写之同名方法的双面魔法(最新整理)

《Java方法重载与重写之同名方法的双面魔法(最新整理)》文章介绍了Java中的方法重载Overloading和方法重写Overriding的区别联系,方法重载是指在同一个类中,允许存在多个方法名相同... 目录Java方法重载与重写:同名方法的双面魔法方法重载(Overloading):同门师兄弟的不同绝

python中的flask_sqlalchemy的使用及示例详解

《python中的flask_sqlalchemy的使用及示例详解》文章主要介绍了在使用SQLAlchemy创建模型实例时,通过元类动态创建实例的方式,并说明了如何在实例化时执行__init__方法,... 目录@orm.reconstructorSQLAlchemy的回滚关联其他模型数据库基本操作将数据添

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav

Java数组动态扩容的实现示例

《Java数组动态扩容的实现示例》本文主要介绍了Java数组动态扩容的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1 问题2 方法3 结语1 问题实现动态的给数组添加元素效果,实现对数组扩容,原始数组使用静态分配

Java中ArrayList与顺序表示例详解

《Java中ArrayList与顺序表示例详解》顺序表是在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构,:本文主要介绍Java中ArrayList与... 目录前言一、Java集合框架核心接口与分类ArrayList二、顺序表数据结构中的顺序表三、常用代码手动

JAVA项目swing转javafx语法规则以及示例代码

《JAVA项目swing转javafx语法规则以及示例代码》:本文主要介绍JAVA项目swing转javafx语法规则以及示例代码的相关资料,文中详细讲解了主类继承、窗口创建、布局管理、控件替换、... 目录最常用的“一行换一行”速查表(直接全局替换)实际转换示例(JFramejs → JavaFX)迁移建

Spring Boot Interceptor的原理、配置、顺序控制及与Filter的关键区别对比分析

《SpringBootInterceptor的原理、配置、顺序控制及与Filter的关键区别对比分析》本文主要介绍了SpringBoot中的拦截器(Interceptor)及其与过滤器(Filt... 目录前言一、核心功能二、拦截器的实现2.1 定义自定义拦截器2.2 注册拦截器三、多拦截器的执行顺序四、过

JAVA线程的周期及调度机制详解

《JAVA线程的周期及调度机制详解》Java线程的生命周期包括NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING和TERMINATED,线程调度依赖操作系统,采用抢占... 目录Java线程的生命周期线程状态转换示例代码JAVA线程调度机制优先级设置示例注意事项JAVA线程

Python中4大日志记录库比较的终极PK

《Python中4大日志记录库比较的终极PK》日志记录框架是一种工具,可帮助您标准化应用程序中的日志记录过程,:本文主要介绍Python中4大日志记录库比较的相关资料,文中通过代码介绍的非常详细,... 目录一、logging库1、优点2、缺点二、LogAid库三、Loguru库四、Structlogphp

JavaWeb项目创建、部署、连接数据库保姆级教程(tomcat)

《JavaWeb项目创建、部署、连接数据库保姆级教程(tomcat)》:本文主要介绍如何在IntelliJIDEA2020.1中创建和部署一个JavaWeb项目,包括创建项目、配置Tomcat服务... 目录简介:一、创建项目二、tomcat部署1、将tomcat解压在一个自己找得到路径2、在idea中添加