java 哈希码怎么生成_如何使用Java生成具有安全哈希的QR码

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

首先,需要一个可以处理QR码的库,我决定使用Zebra Crossing(“ZXing”)库,因为它简单易用(即有围绕它的社区)。添加以下依赖项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);

Map 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 qrCodeDataMap = 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绝对没问题。

哈希字符串

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

commons-codec

commons-codec

1.12

这里是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);

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值