Fortify代码扫描:Parivacy Violation:Heap Inspection漏洞解决方案

该漏洞引发情况:

将敏感数据存储在 String 对象中使系统无法从内存中可靠地清除数据。

如果在使用敏感数据(例如密码、社会保障号码、信用卡号等)后不清除内存,则存储在内存中的这些数据可能会泄漏。通常而言,String 是所用的存储敏感数据,然而,由于 String 对象不可改变,因此用户只能使用 JVM 垃圾收集器来从内存中清除 String 的值。除非 JVM 内存不足,否则系统不要求运行垃圾收集器,因此垃圾收集器何时运行并无保证。如果发生应用程序崩溃,则应用程序的内存转储操作可能会导致敏感数据泄漏。

所以一般使用char数组来代替String存储敏感数据。

而在存储该数据过程中,只要有String对象被使用(不论是用来存储,还是用来作为媒介转换),都可能出现该漏洞。

博主所遇情况为:

第一种(把一个char[]数组转为String中直接使用String方法或new String可能有漏洞):

char[] decryptChars = DecryptString(splits[1]);//splits是一个String[]
resultValue = String.valueOf(decryptChars);//该行引发漏洞,返回值resultValue是字符串
//resultValue = new String(decryptChars);//同上,该方法同样引发漏洞
Arrays.fill(decryptChars,' ');
if (resultValue == null) {
     throw new Exception("解密字符串失败!");
}
    

修改后:

char[] decryptChars = DecryptString(splits[1]);
StringBuffer sb = new StringBuffer();
for (int i = 0;i < decryptChars.length;i++){
    sb.append(decryptChars[i]);
}
Arrays.fill(decryptChars,' ');
if (sb.length()==0){
    throw new Exception("解密字符串失败!");
}

第二种(把一个byte[]转换为char[]):

byte[] bytes = HexToByte(sEncrypted);//sEncrypted是一个字符串
byte[] deBytes = DecryptStream(bytes);//加密
sDecryptChar = new String(deBytes,"ISO-8859-1");//引发漏洞,sDecryptChar是一个char[]

修改后:

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

byte[] bytes = HexToByte(sEncrypted);
byte[] deBytes = DecryptStream(bytes);
Charset cs = Charset.forName("ISO-8859-1");
ByteBuffer bb = ByteBuffer.allocate(deBytes.length);
bb.put(bytes).flip();
CharBuffer cb = cs.decode(bb);
sDecryptChar = cb.array();
发布了95 篇原创文章 · 获赞 43 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/lyxuefeng/article/details/103862926