用java实现DES加密主要有四步:
import java.security.Key;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class DESImpl {
public static void main(String[] args) throws Exception {
String string = "Hello World!";
byte[] bytes = string.getBytes();
// Step 1: Provider support
Security.addProvider(new com.sun.crypto.provider.SunJCE());
// Step 2: Get algorithm instance
Cipher cipher = Cipher.getInstance("DES");
// Step 3: Initial
byte[] keyBytes = "64BitKEY".getBytes();
Key key = new SecretKeySpec(keyBytes, "DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
// Step 4: Do final
byte[] result = cipher.doFinal(bytes);
}
}
其中密钥KEY为64bit