重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設、域名注冊、服務器等服務
為企業(yè)提供網(wǎng)站建設、域名注冊、服務器等服務
這篇文章主要介紹怎么在Java中使用salt生成QR代碼和安全散列字符串,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
成都創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供麻栗坡網(wǎng)站建設、麻栗坡做網(wǎng)站、麻栗坡網(wǎng)站設計、麻栗坡網(wǎng)站制作等企業(yè)網(wǎng)站建設、網(wǎng)頁設計與制作、麻栗坡企業(yè)網(wǎng)站模板建站服務,十載麻栗坡做網(wǎng)站經驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡服務。
這是關于如何在Java中使用salt生成QR代碼和安全散列字符串的分步教程。
首先,需要一個可以處理QR碼的庫,我決定使用Zebra Crossing(“ZXing”)庫,因為它簡單易用(即有圍繞它的社區(qū))。添加以下依賴項pom.xml:
com.google.zxing core 3.4.0 com.google.zxing javase 3.4.0
該庫為生成和讀取代碼提供了相當廣泛的功能。這對我的用例來說已經足夠了,我只需要生成一個帶有簡單JSON對象的QR代碼:
public byte[] qrCodeGenerator(String id) throws IOException, WriterException, InvalidKeySpecException, NoSuchAlgorithmException { String filePath = "QRCode.png"; String charset = "UTF-8"; Map hintMap = new HashMap(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); MapqrCodeDataMap = Map.of( "Name", id, "Key", keyProvider.generateVerificationKey(id) // see next section for ´generateVerificationKey´ method ); String jsonString = new JSONObject(qrCodeDataMap).toString(); createQRCode(jsonString, filePath, charset, hintMap, 500, 500); BufferedImage image = ImageIO.read(new File(filePath)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); byte[] imageData = baos.toByteArray(); return imageData; } private void createQRCode(String qrCodeData, String filePath, String charset, Map hintMap, int qrCodeHeight, int qrCodeWidth) throws WriterException, IOException { BitMatrix matrix = new MultiFormatWriter().encode( new String(qrCodeData.getBytes(charset), charset), BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeHeight, hintMap ); MatrixToImageWriter.writeToPath( matrix, filePath.substring(filePath.lastIndexOf('.') + 1), FileSystems.getDefault().getPath(filePath) ); }
還要注意有趣的小東西 JSONObject:是使用Java將哈希映射轉換為JSON對象。有時,以您希望的方式構建數(shù)據(jù)結構要容易得多,然后序列化為JSON:
MapqrCodeDataMap = Map.of( "Name", "SampleText", "Key", "SomeHashedValue" );
String jsonString = new JSONObject(qrCodeDataMap).toString();
為了能夠使用JSONObject類,您需要將以下依賴項添加到您的pom.xml:
org.json json 20180813
如果您正在尋找更簡化的接口,您可能還會查看QRGen,它聲稱可以進一步簡化用于Java的QR代碼生成API,并且構建在ZXing之上。但是,在我的情況下,ZXing絕對沒問題。
哈希字符串
現(xiàn)在,我需要能夠以快速安全的方式哈希加密字符串。為此,我決定使用OWASP for Java建議的方法。要實現(xiàn)此方法,您需要首先更新pom.xml:
commons-codec commons-codec 1.12
這里是Java中所述方法的(有些簡化)實現(xiàn):
public String generateVerificationKey(String str) throws NoSuchAlgorithmException, InvalidKeySpecException { int iterations = 10000; int keyLength = 512; char[] strChars = str.toCharArray(); byte[] saltBytes = salt.getBytes(); SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); PBEKeySpec spec = new PBEKeySpec(strChars, saltBytes, iterations, keyLength); SecretKey key = skf.generateSecret( spec ); byte[] hashedBytes = key.getEncoded( ); return Hex.encodeHexString(hashedBytes); }
以上是“怎么在Java中使用salt生成QR代碼和安全散列字符串”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!