在安全軟體設計中,避免以明文形式儲存密碼。相反,應採用哈希和加密技術來保護敏感資訊。
將憑證從字串移轉到字元陣列。字串是不可變的,使得資料在清理之前容易暴露。另一方面,字元數組可以立即清理。
加密憑證,同時保留原始雜湊以確保安全。僅在身份驗證過程中解密憑證。建議避免對憑證進行硬編碼,而是安全地儲存它們,例如儲存在加密的設定檔中。
實作 TLS 或 SSL 來加密資料客戶端和伺服器之間的傳輸。這可以保護憑證免於竊聽。
應用混淆技術以防止惡意方存取安全措施,即使在反編譯的情況下也是如此。混淆使攻擊者更難發現漏洞。
以下程式碼片段說明了加密和解密憑證:
import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; public class SecureCredentials { private static final char[] PASSWORD = "YourEncryptionKey".toCharArray(); private static final byte[] SALT = { (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12 }; public static void encrypt(char[] property) throws Exception { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20)); // Encrypt and save to temporary storage String encrypted = Base64.encodeBytes(pbeCipher.doFinal(property)); // Cleanup data sources for (int i = 0; i < property.length; i++) { property[i] = 0; } property = null; System.gc(); // Return encryption result return encrypted; } public static String decrypt(String property) throws Exception { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20)); return new String(pbeCipher.doFinal(Base64.decode(property))); } // Usage example public static void main(String[] args) { try { char[] password = "MySecurePassword".toCharArray(); String encryptedPassword = encrypt(password); String decryptedPassword = decrypt(encryptedPassword); System.out.println("Original Password: " + String.valueOf(password)); System.out.println("Encrypted Password: " + encryptedPassword); System.out.println("Decrypted Password: " + decryptedPassword); } catch (Exception e) { e.printStackTrace(); } } }
以上是如何在軟體中安全儲存使用者憑證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!