banner
RustyNail

RustyNail

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

DES encryption in Java

Encryption#

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 is the actual encryption.

The length of key should be 8. If it is too long, it will be truncated. If it is not long enough, an exception will be thrown.

Decryption#

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#

The encrypted data (byte[]) can be converted to a Hex String for storage.

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

Of course, before decryption, the Hex String should be converted back to a 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;
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.