Example about Java encryption

xiaoxiao2021-03-06  22

Although DES is a relatively backward algorithm, the encryption decryption in Java is similar.

Example from http://javaalmanac.com/egs/javax.crypto/desstring.html

public class DesEncrypter {Cipher ecipher; Cipher dcipher; DesEncrypter (SecretKey key) {try {ecipher = Cipher.getInstance ( "DES"); dcipher = Cipher.getInstance ( "DES"); ecipher.init (Cipher.ENCRYPT_MODE, key) ; dcipher.init (Cipher.DECRYPT_MODE, key);} catch (javax.crypto.NoSuchPaddingException e) {} catch (java.security.NoSuchAlgorithmException e) {} catch (java.security.InvalidKeyException e) {}} public String encrypt (String str) {Try {// encode the string @Tes use UTF-8 byte [] UTF8 = str.getbytes ("utf8"); // encrypt byte [] eNC = ECIPHER.DOFINAL (UTF8); // Encode Bytes to base64 to get a string return new sun.misc.base64encoder (). Encode (enc);} catch (javax.crypto.badpaddingexception e) { } Catch (IllegalBlockSizeException e) {} catch (UnsupportedEncodingException e) {} catch (java.io.IOException e) {} return null;} public String decrypt (String str) {try {// Decode base64 to get bytes byte [] Dec = new sun.misc.base64decoder (). decodeBuffer (STR); // decrypt byte [] utf8 = dcipher.dofinal (DEC); // decode using utf-8 return new string (utf8, "utf8");

} Catch (javax.crypto.BadPaddingException e) {} catch (IllegalBlockSizeException e) {} catch (UnsupportedEncodingException e) {} catch (java.io.IOException e) {} return null;}} Here's an example that uses the class: Try {

...............

SecretKey Key = KeyGenerator.GetInstance ("des"). GenerateKey ();

// Create Encrypter / Decrypter Class

Desencrypter Encrypter = New Desencrypter (key);

// encrypt

String Encrypted = Encrypter.Encrypt ("Don't Tell Anybody!");

// Decrypt

String Decrypted = Encrypter.Decrypt (Encrypted);

} catch (exception e) {

}

转载请注明原文地址:https://www.9cbs.com/read-43143.html

New Post(0)