Java對字元串加密並返回星號※

来源:https://www.cnblogs.com/taojietaoge/archive/2019/04/26/10773455.html
-Advertisement-
Play Games

If you don't look back, you'll never know I waiting for you behind you. Java對字元串加密並返回星號※ PasswordUtils這個加密工具類是在Ranger項目的源碼中發現的,它是一個安全管理框架,普通的加密需求應該用它的 ...


 If you don't look back, you'll never know I waiting for you behind you.

 

Java對字元串加密並返回星號※

PasswordUtils這個加密工具類是在Ranger項目的源碼中發現的,它是一個安全管理框架,普通的加密需求應該用它的加密工具類就OK了;

首先,用戶輸入密碼,前端先用type為password把密碼顯示為※,但是這時通過F12查看,瀏覽器仍然可以看到密碼信息,但是這是用戶自己輸入的,第一把看見也ok;一旦請求提交立刻返回經加密後的密碼,此處並非返回加密後的密碼,而是直接返回一個※密碼如“******”,並把轉換加密後的密碼存入資料庫,之後每次請求也都返回“******”;然後在後臺需要用到密碼的地方就自己解密咯。

加密工具類PasswordUtils:

  1 package org.apache.ranger.plugin.util;
  2 
  3 import java.io.IOException;
  4 import java.util.Map;
  5 
  6 import javax.crypto.Cipher;
  7 import javax.crypto.SecretKey;
  8 import javax.crypto.SecretKeyFactory;
  9 import javax.crypto.spec.PBEKeySpec;
 10 import javax.crypto.spec.PBEParameterSpec;
 11 
 12 import org.apache.commons.lang.StringUtils;
 13 import org.slf4j.Logger;
 14 import org.slf4j.LoggerFactory;
 15 
 16 import com.sun.jersey.core.util.Base64;
 17 public class PasswordUtils {
 18 
 19     private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
 20 
 21     private final String CRYPT_ALGO;
 22     private String password;
 23     private final char[] ENCRYPT_KEY;
 24     private final byte[] SALT;
 25     private final int ITERATION_COUNT;
 26     private final char[] encryptKey;
 27     private final byte[] salt;
 28     private static final String LEN_SEPARATOR_STR = ":";
 29 
 30     public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
 31     public static final String DEFAULT_ENCRYPT_KEY = "tzL1AKl5uc4NKYaoQ4P3WLGIBFPXWPWdu1fRm9004jtQiV";
 32     public static final String DEFAULT_SALT = "f77aLYLo";
 33     public static final int DEFAULT_ITERATION_COUNT = 17;
 34 
 35     public static String encryptPassword(String aPassword) throws IOException {
 36         return new PasswordUtils(aPassword).encrypt();
 37     }
 38 
 39     private String encrypt() throws IOException {
 40         String ret = null;
 41         String strToEncrypt = null;        
 42         if (password == null) {
 43             strToEncrypt = "";
 44         } else {
 45             strToEncrypt = password.length() + LEN_SEPARATOR_STR + password;
 46         }
 47         try {
 48             Cipher engine = Cipher.getInstance(CRYPT_ALGO);
 49             PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
 50             SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
 51             SecretKey key = skf.generateSecret(keySpec);
 52             engine.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
 53             byte[] encryptedStr = engine.doFinal(strToEncrypt.getBytes());
 54             ret = new String(Base64.encode(encryptedStr));
 55         }
 56         catch(Throwable t) {
 57             LOG.error("Unable to encrypt password due to error", t);
 58             throw new IOException("Unable to encrypt password due to error", t);
 59         }
 60         return ret;
 61     }
 62 
 63         PasswordUtils(String aPassword) {
 64             String[] crypt_algo_array = null;
 65             int count = 0;
 66             if (aPassword != null && aPassword.contains(",")) {
 67                 count = StringUtils.countMatches(aPassword, ",");
 68                 crypt_algo_array = aPassword.split(",");
 69             }
 70             if (crypt_algo_array != null && crypt_algo_array.length > 4) {
 71                 CRYPT_ALGO = crypt_algo_array[0];
 72                 ENCRYPT_KEY = crypt_algo_array[1].toCharArray();
 73                 SALT = crypt_algo_array[2].getBytes();
 74                 ITERATION_COUNT = Integer.parseInt(crypt_algo_array[3]);
 75                 password = crypt_algo_array[4];
 76                 if (count > 4) {
 77                     for (int i = 5 ; i<=count ; i++){
 78                         password = password + "," + crypt_algo_array[i];
 79                     }
 80                 }
 81             } else {
 82                     CRYPT_ALGO = DEFAULT_CRYPT_ALGO;
 83                     ENCRYPT_KEY = DEFAULT_ENCRYPT_KEY.toCharArray();
 84                     SALT = DEFAULT_SALT.getBytes();
 85                     ITERATION_COUNT = DEFAULT_ITERATION_COUNT;
 86                     password = aPassword;
 87             }
 88             Map<String, String> env = System.getenv();
 89             String encryptKeyStr = env.get("ENCRYPT_KEY");
 90             if (encryptKeyStr == null) {
 91                 encryptKey=ENCRYPT_KEY;
 92             }else{
 93                 encryptKey=encryptKeyStr.toCharArray();
 94             }
 95             String saltStr = env.get("ENCRYPT_SALT");
 96             if (saltStr == null) {
 97                 salt = SALT;
 98             }else{
 99                 salt=saltStr.getBytes();
100             }
101         }
102 
103     public static String decryptPassword(String aPassword) throws IOException {
104         return new PasswordUtils(aPassword).decrypt();
105     }
106 
107     private String decrypt() throws IOException {
108         String ret = null;
109         try {
110             byte[] decodedPassword = Base64.decode(password);
111             Cipher engine = Cipher.getInstance(CRYPT_ALGO);
112             PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
113             SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
114             SecretKey key = skf.generateSecret(keySpec);
115             engine.init(Cipher.DECRYPT_MODE, key,new PBEParameterSpec(salt, ITERATION_COUNT));
116             String decrypted = new String(engine.doFinal(decodedPassword));
117             int foundAt = decrypted.indexOf(LEN_SEPARATOR_STR);
118             if (foundAt > -1) {
119                 if (decrypted.length() > foundAt) {
120                     ret = decrypted.substring(foundAt+1);
121                 }
122                 else {
123                     ret = "";
124                 }
125             }
126             else {
127                 ret = null;
128             }
129         }
130         catch(Throwable t) {
131             LOG.error("Unable to decrypt password due to error", t);
132             throw new IOException("Unable to decrypt password due to error", t);
133         }
134         return ret;
135     }
136 
137     public static String getDecryptPassword(String password) {
138         String decryptedPwd = null;
139         try {
140             decryptedPwd = decryptPassword(password);
141         } catch (Exception ex) {
142             LOG.warn("Password decryption failed, trying original password string.");
143             decryptedPwd = null;
144         } finally {
145             if (decryptedPwd == null) {
146                 decryptedPwd = password;
147             }
148         }
149         return decryptedPwd;
150     }
151 }

測試加密/解密執行結果:

 1 package com.xinyan.springcloud.tjt;
 2 
 3 public class TestDecryptEncrypt {
 4     
 5     public static void main(String[] args) throws Exception {
 6         String password = "taojietaoge";
 7         //加密:
 8         String encryptPassword = PasswordUtils.encryptPassword(password);
 9         System.out.println("加密後:"+ encryptPassword);
10         //解密:
11         String decryptPassword = PasswordUtils.decryptPassword(encryptPassword);
12         System.out.println("解密後:"+ decryptPassword);
13     }
14 
15 }

執行結果如下:

 

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 定義: 定義: 提供一個創建一系列相關或相互依賴對象的介面,而無需指定他們具體的類。 結構:(書中圖,侵刪) 這個圖相對來說有一點點複雜,其實就是在工廠方法模式的基礎上做了一些擴展,工廠方法模式只用於生成一種產品(把上圖ProductB相關的都去掉就是了),而抽象工廠模式可用於生產多種產品。 加上例 ...
  • 適配器模式簡述: 定義:將一個類的介面轉化成客戶希望的另一個介面,適配器模式讓那些介面不相容的類可以一起工作。別名(包裝器[Wrapper]模式) 它屬於創建型模式的成員,何為創建型模式:就是關註如何將現有類或對象組織在一起形成更大的結構。由於系統中存在類和對象,所以存在兩種結構型模式:類結構型模式 ...
  • 這個例子主要是將zuul和eureka結合起來使用,zuul作為反向代理,同時起到負載均衡的作用,同時網關後面的消費者也作為服務提供者,同時提供負載均衡。 ...
  • [TOC] 文章代碼及地址: "https://github.com/codeEngraver/java technology stack/tree/master/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B" 如果覺得不錯的可以給個star,整理不易。謝謝謝,持續更新技 ...
  • 先看一段推理<*一切都是在8個比特位的前提下,討論二進位的符號位,溢出等等,才有意義*> +124:0111 1100 -124:1000 0100 +125:0111 1101 -125:1000 0011 +126:0111 1110 -126:1000 0010 +127:0111 1111 ...
  • 一、HTML傳值/PHP接收方法 1、GET(地址欄+問號+數據信息) (1)方式一:表單Form: method = 'get' GET接收數據方式: $_GET[‘表單元素name對應的值] (2)方式二:鏈接方式 註意每個數據用 “&” 分開,地址欄中 “=” 不能左右不能有空格 2、POST ...
  • 定義 自己總結:就相當於現實中各種用途的工具,有著對數據進行各種處理的功能(實質就是比較複雜的變數?!) 分類 自定義函數和Python語言已經定義過的常用的內置函數 自定義函數的組成部分 自己理解: ①def:是內置函數名(保留標識符),用於自定義一個自定義函數,實現需要內置函數沒有的功能 ②函數 ...
  • 1. WebSocket 是什麼? WebSocket允許伺服器「主動」給瀏覽器發消息。 2. 為什麼要用 WebSocket 實時獲取服務端數據這種需求,在使用 WebSocket 之前也是可以做到的,主要方式就是輪詢。比如 javascript上一個定時器,每隔幾秒鐘向服務端發送消息詢問最新價格 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...