使用Java生成具有安全哈希的QR码 | Rustam Mehmandarov


这是关于如何在Java中使用salt生成QR代码和安全散列字符串的分步教程。

首先,需要一个可以处理QR码的库,我决定使用Zebra Crossing(“ZXing”)库,因为它简单易用(即有围绕它的社区)。添加以下依赖项pom.xml:

<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>core</artifactId>
  <version>3.4.0</version>
</dependency>
<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>javase</artifactId>
  <version>3.4.0</version>
</dependency>

该库为生成和读取代码提供了相当广泛的功能。这对我的用例来说已经足够了,我只需要生成一个带有简单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);

    Map<String, String> qrCodeDataMap = 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对象。有时,以您希望的方式构建数据结构要容易得多,然后序列化为JSON:

Map<String, String> qrCodeDataMap = Map.of(
        "Name", "SampleText",
       
"Key", "SomeHashedValue"
);
String jsonString = new JSONObject(qrCodeDataMap).toString();

为了能够使用JSONObject类,您需要将以下依赖项添加到您的pom.xml:

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20180813</version>
</dependency>

如果您正在寻找更简化的接口,您可能还会查看QRGen,它声称可以进一步简化用于Java的QR代码生成API,并且构建在ZXing之上。但是,在我的情况下,ZXing绝对没问题。

哈希字符串
现在,我需要能够以快速安全的方式哈希加密字符串。为此,我决定使用OWASP for Java建议方法。要实现此方法,您需要首先更新pom.xml:

<dependency>
  <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  <version>1.12</version>
</dependency>

这里是Java中所述方法的(有些简化)实现:

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);
}