Java 代碼安全(一)      —— 避免用String儲存敏感性資料,javastring

來源:互聯網
上載者:User

Java 代碼安全(一)      —— 避免用String儲存敏感性資料,javastring

Java 代碼安全(一)
     —— 避免用String儲存敏感性資料

    如果重要的資料(儲存在記憶體中)在使用後沒有及時清理,有可能會導致資訊洩漏。開發人員通常都回用String 儲存敏感性資料(密碼,卡號等)。因為String 對象是不可變的,只有 JVM 的記憶體回收行程才能從記憶體中清除String的值。而只有記憶體不足的時候虛擬機器才會執行記憶體回收,所以我們不能保證記憶體回收什麼時候進行。當系統崩潰後,memory dump 可能會泄漏敏感性資料。

這裡解析一下String 對象不可變是什麼意思
比如 String  s1 = “abc”;  s1 = “def”;
這裡引用 s1 只是重新指向另外一個對象。對象”abc”並沒有被修改。
    

例子一:
   Final char[] password = getPassword();
   String  passwordAsString = new String(password)

這裡passwordAsString 不確定什麼時候被清理掉,容易被泄露。

解決方案:
   當重要資料不需要再使用的時候,保證把它清除掉。用byte 數組 或 character 數組來代替一些不可變的對象,比如String。應為byte 和 character 數組能用程式清理掉。
如:

Final char[] password = getPassword();
//use the password

//clear when finished
Arrays.fill(password,’’);


Memory dump : 記憶體轉存  
用途:存一個當時記憶體的副本,可以用工具開啟複原當時的情況。因為東西都在記憶體裡。

附:java中String類的記憶體配置  http://jingyan.baidu.com/article/8275fc869a070346a03cf6f4.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.