在對安全性要求比較高的報文做加密的時候,算法有很多種,我這里主要用到的就是AES加密算法。由于在國內(nèi)使用,所以不可避免的要對中文進行加密和解密,而在這個過程中,發(fā)現(xiàn),如果不做處理,很容易會出現(xiàn)中文亂碼。(推薦:java視頻教程)
下面是常見的情況:
一、中文亂碼
不對密碼進行編碼處理
byte[] decryptResult = decrypt(encryptResult, password); System.out.println("解密后:" + new String(decryptResult));
運行后
加密前:我是shoneworn 解密后:鎴戞槸shoneworn
二、對文字進行編碼處理,但是在傳輸過程中草率的將byte[]轉(zhuǎn)成String, String code = new String(bytes); 由于AES加密算法要求密文是16位的倍數(shù)。所以,這么處理,在解密的時候,就會報各種錯。比如下面的。
String code = new String(encryptResult); byte[] decryptResult = decrypt(code.getBytes(), password);
AES加密時會將被加密數(shù)據(jù)轉(zhuǎn)換成編碼格式的字節(jié)數(shù)組也就是String.getBytes()方法,當(dāng)getBytes方法不設(shè)置參數(shù)時,默認(rèn)使用本機默認(rèn)編碼格式,改成String.getBytes(“utf-8”)問題解決。
使用rsa加密解密示例:
package com.ailin.test;import java.io.UnsupportedEncodingException;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;public class AES { /** * 加密 * * @param content * 需要加密的內(nèi)容 * @param password * 加密密碼 * @return */ public static byte[] encrypt(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 創(chuàng)建密碼器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } /** * 解密 * * @param content * 待解密內(nèi)容 * @param password * 解密密鑰 * @return */ public static byte[] decrypt(byte[] content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 創(chuàng)建密碼器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(content); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } /** * 將二進制轉(zhuǎn)換成16進制 * * @param buf * @return */ public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** * 將16進制轉(zhuǎn)換為二進制 * * @param hexStr * @return */ public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } /** * 加密 * * @param content * 需要加密的內(nèi)容 * @param password * 加密密碼 * @return */ public static byte[] encrypt2(String content, String password) { try { SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } public static void main(String[] args) throws UnsupportedEncodingException { String content = "我是shoneworn"; String password = "12345678"; // 加密 System.out.println("加密前:" + content); byte[] encode = encrypt(content, password); //傳輸過程,不轉(zhuǎn)成16進制的字符串,就等著程序崩潰掉吧 String code = parseByte2HexStr(encode); System.out.println("密文字符串:" + code); byte[] decode = parseHexStr2Byte(code); // 解密 byte[] decryptResult = decrypt(decode, password); System.out.println("解密后:" + new String(decryptResult, "UTF-8")); //不轉(zhuǎn)碼會亂碼 } }
更多java知識請關(guān)注java基礎(chǔ)教程欄目。
以上是java中rsa亂碼介紹的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費脫衣服圖片

Undresser.AI Undress
人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Clothoff.io
AI脫衣機

Video Face Swap
使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的代碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級代碼編輯軟件(SublimeText3)

要正確處理JDBC事務(wù),必須先關(guān)閉自動提交模式,再執(zhí)行多個操作,最后根據(jù)結(jié)果提交或回滾;1.調(diào)用conn.setAutoCommit(false)以開始事務(wù);2.執(zhí)行多個SQL操作,如INSERT和UPDATE;3.若所有操作成功則調(diào)用conn.commit(),若發(fā)生異常則調(diào)用conn.rollback()確保數(shù)據(jù)一致性;同時應(yīng)使用try-with-resources管理資源,妥善處理異常并關(guān)閉連接,避免連接泄漏;此外建議使用連接池、設(shè)置保存點實現(xiàn)部分回滾,并保持事務(wù)盡可能短以提升性能。

使用java.time包中的類替代舊的Date和Calendar類;2.通過LocalDate、LocalDateTime和LocalTime獲取當(dāng)前日期時間;3.使用of()方法創(chuàng)建特定日期時間;4.利用plus/minus方法不可變地增減時間;5.使用ZonedDateTime和ZoneId處理時區(qū);6.通過DateTimeFormatter格式化和解析日期字符串;7.必要時通過Instant與舊日期類型兼容;現(xiàn)代Java中日期處理應(yīng)優(yōu)先使用java.timeAPI,它提供了清晰、不可變且線

前形式攝取,quarkusandmicronautleaddueTocile timeProcessingandGraalvSupport,withquarkusoftenpernperforminglightbetterine nosserless notelless centarios.2。

NetworkPortSandFireWallsworkTogetHertoEnableCommunication whereSeringSecurity.1.NetWorkPortSareVirtualendPointSnumbered0-655 35,with-Well-with-Newonportslike80(HTTP),443(https),22(SSH)和25(smtp)sindiessingspefificservices.2.portsoperateervertcp(可靠,c

Java的垃圾回收(GC)是自動管理內(nèi)存的機制,通過回收不可達對象釋放堆內(nèi)存,減少內(nèi)存泄漏風(fēng)險。1.GC從根對象(如棧變量、活動線程、靜態(tài)字段等)出發(fā)判斷對象可達性,無法到達的對象被標(biāo)記為垃圾。2.基于標(biāo)記-清除算法,標(biāo)記所有可達對象,清除未標(biāo)記對象。3.采用分代收集策略:新生代(Eden、S0、S1)頻繁執(zhí)行MinorGC;老年代執(zhí)行較少但耗時較長的MajorGC;Metaspace存儲類元數(shù)據(jù)。4.JVM提供多種GC器:SerialGC適用于小型應(yīng)用;ParallelGC提升吞吐量;CMS降

選擇合適的HTMLinput類型能提升數(shù)據(jù)準(zhǔn)確性、增強用戶體驗并提高可用性。1.根據(jù)數(shù)據(jù)類型選用對應(yīng)input類型,如text、email、tel、number和date,可實現(xiàn)自動校驗和適配鍵盤;2.利用HTML5新增類型如url、color、range和search,可提供更直觀的交互方式;3.配合使用placeholder和required屬性,可提升表單填寫效率和正確率,但需注意placeholder不能替代label。

Go中的HTTP日志中間件可記錄請求方法、路徑、客戶端IP和耗時,1.使用http.HandlerFunc包裝處理器,2.在調(diào)用next.ServeHTTP前后記錄開始時間和結(jié)束時間,3.通過r.RemoteAddr和X-Forwarded-For頭獲取真實客戶端IP,4.利用log.Printf輸出請求日志,5.將中間件應(yīng)用于ServeMux實現(xiàn)全局日志記錄,完整示例代碼已驗證可運行,適用于中小型項目起步,擴展建議包括捕獲狀態(tài)碼、支持JSON日志和請求ID追蹤。

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac
