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通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式

《Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式》本文详细介绍如何使用Java通过JDBC连接MySQL数据库,包括下载驱动、配置Eclipse环境、检测数据库连接等关键步骤,... 目录一、下载驱动包二、放jar包三、检测数据库连接JavaJava 如何使用 JDBC 连接 mys

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

Ubuntu如何分配​​未使用的空间

《Ubuntu如何分配​​未使用的空间》Ubuntu磁盘空间不足,实际未分配空间8.2G因LVM卷组名称格式差异(双破折号误写)导致无法扩展,确认正确卷组名后,使用lvextend和resize2fs... 目录1:原因2:操作3:报错5:解决问题:确认卷组名称​6:再次操作7:验证扩展是否成功8:问题已解

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

一文详解SpringBoot中控制器的动态注册与卸载

《一文详解SpringBoot中控制器的动态注册与卸载》在项目开发中,通过动态注册和卸载控制器功能,可以根据业务场景和项目需要实现功能的动态增加、删除,提高系统的灵活性和可扩展性,下面我们就来看看Sp... 目录项目结构1. 创建 Spring Boot 启动类2. 创建一个测试控制器3. 创建动态控制器注

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Java操作Word文档的全面指南

《Java操作Word文档的全面指南》在Java开发中,操作Word文档是常见的业务需求,广泛应用于合同生成、报表输出、通知发布、法律文书生成、病历模板填写等场景,本文将全面介绍Java操作Word文... 目录简介段落页头与页脚页码表格图片批注文本框目录图表简介Word编程最重要的类是org.apach

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核