banner
RustyNail

RustyNail

coder. 【blog】https://rustynail.me 【nostr】wss://ts.relays.world/ wss://relays.world/nostr

DES加密的java使用

加密#

public byte[] encrypt(byte[] data, String key) throws Exception {
    try{
        
        SecureRandom random = new SecureRandom();
        
        DESKeySpec desKey = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey securekey = keyFactory.generateSecret(desKey);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
        return cipher.doFinal(data);
    }catch(Throwable e){
        e.printStackTrace();
    }
    return null;
}

Cipher 是真正加密的.

key 的长度应该是 8,太长会截断,不够长会抛异常。

解密#

public byte[] decrypt(byte[] data, String key) throws Exception {
    SecureRandom random = new SecureRandom();
    DESKeySpec desKey = new DESKeySpec(key.getBytes());
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
    SecretKey securekey = keyFactory.generateSecret(desKey);
    Cipher cipher = Cipher.getInstance("DES");
    cipher.init(Cipher.DECRYPT_MODE, securekey, random);
    return cipher.doFinal(data);
}

Hex String#

加密后的数据(byte [])可以转化为 Hex String 储存

public String bytesToHexString(byte[] data){
    return HexBin.encode(data);
}

当然,解密之前先吧 Hex String 转化为 byte []。

public byte[] hexStringToBytes(String hexString){
    byte[] bytes = new byte[hexString.length() / 2];
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = (byte) Integer.parseInt(hexString.substring(2 * i, 2 * i + 2), 16);
    }
    return bytes;
}
加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。