package com. util ; import java. security. Key ;
import java. security. SecureRandom ; import javax. crypto. Cipher ;
import javax. crypto. KeyGenerator ; import sun. misc. BASE64Decoder ;
import sun. misc. BASE64Encoder ;
@SuppressWarnings ( "restriction" )
public class DESUtil { private static String CHARSETNAME = "UTF-8" ; private static String ALGORITHM = "DES" ; public static String getEncryptString ( String str, String keyStr) { BASE64Encoder base64encoder = new BASE64Encoder ( ) ; try { Key key = getKey ( keyStr) ; byte [ ] bytes = str. getBytes ( CHARSETNAME ) ; Cipher cipher = Cipher . getInstance ( ALGORITHM ) ; cipher. init ( Cipher . ENCRYPT_MODE , key) ; byte [ ] doFinal = cipher. doFinal ( bytes) ; return base64encoder. encode ( doFinal) ; } catch ( Exception e) { throw new RuntimeException ( e) ; } } public static String getDecryptString ( String str, String keyStr) { BASE64Decoder base64decoder = new BASE64Decoder ( ) ; try { Key key = getKey ( keyStr) ; byte [ ] bytes = base64decoder. decodeBuffer ( str) ; Cipher cipher = Cipher . getInstance ( ALGORITHM ) ; cipher. init ( Cipher . DECRYPT_MODE , key) ; byte [ ] doFinal = cipher. doFinal ( bytes) ; return new String ( doFinal, CHARSETNAME ) ; } catch ( Exception e) { throw new RuntimeException ( e) ; } } public static Key getKey ( String keyStr) { Key key; try { KeyGenerator generator = KeyGenerator . getInstance ( ALGORITHM ) ; SecureRandom secureRandom = SecureRandom . getInstance ( "SHA1PRNG" ) ; secureRandom. setSeed ( keyStr. getBytes ( ) ) ; generator. init ( secureRandom) ; key = generator. generateKey ( ) ; generator = null ; } catch ( Exception e) { throw new RuntimeException ( e) ; } return key; } public static void main ( String [ ] args) { System . out. println ( getEncryptString ( "123456" , "System1_System2_2024" ) ) ; System . out. println ( getDecryptString ( getEncryptString ( "123456" , "System1_System2_2024" ) , "System1_System2_2024" ) ) ; }
}