Cet exemple partage un outil de cryptage Java et de décryptage adapté à Javase / Javaee / Android pour que tout le monde puisse apprendre. Le contenu spécifique est le suivant
Package Longshu.utils.Security; import java.lang.reflect.method; import java.security.invalidkeyException; import java.security.key; import java.security.messagedigest; import java.security.nosuchalgorithmexception; import java.security.seurandom; Importer javax.crypto.badpaddingException; import javax.crypto.cipher; importer javax.crypto.illegalblocksizexception; import javax.crypto.keygenerator; import javax.crypto.nosuchpaddindin javax.crypto.spec.SecretKeyspec; / ** * outil de cryptage et de décryptage Java. * À la fois javase / javaee / android s'appliquent * * @author longshu 13 avril 2016 * / classe publique EncryptDecrypt {// pas besoin de créer un objet privé encryptdecrypt () {} / ** * sha1 crypted bit data {try {messagediGest sha1digest = MessagediGest.getInstance ("sha-1"); sha1digest.update (source); BYTE TargetDigest [] = sha1digest.digest (); return TargetDigest; } catch (NoSuchalgorithMexception e) {Throw New RuntimeException (e); }} / ** * SHA1 Données de chaîne cryptées * @param Source String à crypter * @return String chiffré * / String statique publique Sha1 (chaîne source) {return byte2hexstr (sha1bit (source.getBytes ())); } / ** * MD5 Données de bits cryptées * @param Source Byte Array * @return Array d'octets crypté * / octet statique public [] md5bit (byte [] source) {try {// Obtenez l'objet Messagedigest de l'algorithme Md5 Digest ("DsagediGest; // Mette à jour le digest md5digest.update (source); // obtient le retour de chiffre de chiffrement md5digest.digest (); } catch (NoSuchalgorithMexception e) {Throw New RuntimeException (e); }} / ** * MD5 Crypted String, 32 bits long * @Param Source Contenu à crypter * @return Contenu chiffré * / public static String md5 (chaîne source) {return byte2hexstr (md5bit (source.getbytes ())); } / ** * Base64 Encoding * @param Source String à coder * @return String encodé * / String statique publique EncodeBase64 (source de chaîne) {class <?> Clazz = null; Méthode EncodeMethod = NULL; essayez {// utilisation prioritaire des bibliothèques tierces cllazz = class.forname ("org.apache.commons.codec.binary.base64"); EncodeMethod = Clazz.getMethod ("EncodeBase64", byte []. Classe); System.out.println ("EncodeBase64 ->" + Clazz); System.out.println ("EncodeMethod ->" + EncodeMethod); // La méthode statique de la méthode de réflexion ne nécessite pas d'objet pour exécuter Return New String ((byte []) EncodeMethod.Invoke (NULL, source.getBytes ())); } catch (classNotFoundException e) {String vm = System.getProperty ("java.vm.name"); System.out.println (VM); essayez {if ("dalvik" .equals (vm)) {// Android Clazz = class.forname ("android.util.base64"); // byte [] base64.encode (byte [] entrée, intlade int) EncodeMethod = Clazz.getMethod ("Encode", byte []. class, int.class); System.out.println ("EncodeBase64 ->" + Clazz); System.out.println ("EncodeMethod ->" + EncodeMethod); return new String ((byte []) EncodeMethod.invoke (null, source.getBytes (), 0)); } else {// javase / javaee Clazz = class.forname ("Sun.Misc.Base64Encoder"); EncodeMethod = Clazz.getMethod ("Encoder", Byte []. Classe); System.out.println ("EncodeBase64 ->" + Clazz); System.out.println ("EncodeMethod ->" + EncodeMethod); return (String) EncodeMethod.invoke (Clazz.NewInstance (), source.getBytes ()); }} catch (classNotFoundException e1) {return null; } catch (exception e1) {return null; }} catch (exception e) {return null; } / * * Android * Android.util.base64 * / // return Base64.EncodetoString (source, base64.default); // return new String (base64.encode (source.getBytes (), base64.default)); / * * Javase / Javaee * / // Sun.Misc.Base64Encoder // Base64Encoder Encoder = new Base64Encoder (); // return Encoder.encode (source.getBytes ()); // org.apache.commons.codec.binary.base64 // return new String (base64.encodeBase64 (source.getBytes ())); } / ** * Base64 Decoding * @param EncodeSource EncodeSource EncodeSource * @return String avant le codage * / public static static decodeBase64 (chaîne EncodeSource) {class <?> Clazz = null; Méthode DecodeMethod = NULL; essayez {// utilisation prioritaire des bibliothèques tierces cllazz = class.forname ("org.apache.commons.codec.binary.base64"); DecodeMethod = Clazz.getMethod ("DecodeBase64", byte []. Classe); System.out.println ("DecodeBase64 ->" + Clazz); System.out.println ("Decodemethod ->" + DecodeMethod); // Exécuter les méthodes statiques de la méthode de réflexion sans objet renvoie une nouvelle chaîne ((byte []) decodemethod.invoke (null, EncodeSource.getBytes ())); } catch (classNotFoundException e) {String vm = System.getProperty ("java.vm.name"); System.out.println (VM); essayez {if ("dalvik" .equals (vm)) {// Android Clazz = class.forname ("android.util.base64"); // byte [] base64.decode (byte [] entrée, intlade int) decodeMethod = Clazz.getMethod ("decode", byte []. class, int.class); System.out.println ("DecodeBase64 ->" + Clazz); System.out.println ("Decodemethod ->" + DecodeMethod); return new String ((byte []) decodemethod.invoke (null, EncodeSource.getBytes (), 0)); } else {// javase / javaee Clazz = class.forname ("Sun.Misc.Base64Decoder"); DecodeMethod = Clazz.getMethod ("DecodeBuffer", String.class); System.out.println ("DecodeBase64 ->" + Clazz); System.out.println ("Decodemethod ->" + DecodeMethod); Renvoie une nouvelle chaîne ((byte []) decodemethod.invoke (Clazz.newinstance (), EncodeSource)); }} catch (classNotFoundException e1) {return null; } catch (exception e1) {return null; }} catch (exception e) {return null; } / * * Android * android.util.base64 * / // return new // String (base64.decode (Encodesource.getBytes (), base64.default)); / * * Javase / Javaee * / // Sun.Misc.Base64Decoder // Try {// Base64DecOder Decoder = new Base64DEcoder (); // return new String (decoder.decodeBuffer (EncodeSource)); //} catch (ioException e) {// Throw New RuntimeException (e); //} // org.apache.commons.codec.binary.base64 // return new String (base64.decodeBase64 (Encodesource.getBytes ())); } / ** * AES Encryption * @param contenu contenu contenu à crypter * @param mot de passe de mot de passe du mot de passe * @return * / public static byte [] encryptbitaes (byte [] contenu, mot de passe de chaîne) {try {cipher EncryptCipher = Cipher.getInstance ("aes / ecb / pkcs5padding"); // créer awsword EncryptCipher.init (cipher.encrypt_mode, getKey (mot de passe)); // initialiser l'octet [] result = encryptcipher.dofinal (contenu); Résultat de retour; // Encrypt} catch (NosuchalgorithMexception e) {e.printStackTrace (); } catch (nosuchpaddingException e) {e.printStackTrace (); } catch (invalidKeyException e) {e.printStackTrace (); } catch (illégalblockSizeException e) {e.printStackTrace (); } catch (badpaddingException e) {e.printStackTrace (); } return null; } / ** * aes decrypt * @param contenu contenu contenu à décrypter * @param mot de passe décrypt key * @return * / public static byte [] decryptbitaes (byte [] contenu, chaîne mot de passe) {try {cipher decryptcipher = cipher.getInstance ("aes / ecb / pkcs5padding"); //re decryptCipher.init (cipher.decrypt_mode, getKey (mot de passe)); // initialiser l'octet [] result = decryptcipher.dofinal (contenu); Résultat de retour; // Encrypt résultat} catch (invalidKeyException e) {e.printStackTrace (); } catch (NosuchalgorithMexception e) {e.printStackTrace (); } catch (nosuchpaddingException e) {e.printStackTrace (); } catch (illégalblockSizeException e) {e.printStackTrace (); } catch (badpaddingException e) {e.printStackTrace (); } return null; } / ** * AES STRING Encryption * @param Contenu Contenu à chiffrer * @param mot de passe de mot de passe mot de passe * @return * / public static String Encryptaes (String Content, String Password) {return byte2hexstr (EncryptBitaes (contenu.getbytes (), mot de passe)); } / ** * Decryption de chaîne AES * @param Contenu contenu à décrypter * @param mot de passe de décrypt de Decrypt * @return * / public static string decryptaes (String Content, String Motword) {return new String (decryptBitaes (hexstr2bytes (contenu), mot de passe)); } / ** * Générer la clé à partir de la chaîne spécifiée * @param mot de passe la chaîne qui constitue la clé * @return la clé générée * @throws noSuchalgorithMexception * / private static key getKey (String Password) lève NosuchalgorithMexception {SecureRandom SecureRandom = new SecureRandom (Passway.getBytes ()); // Générer Key KeyGenerator Kgen = keyGenerator.getInstance ("AES"); Kgen.Init (128, SecureRandom); SecretKey SecretKey = Kgen.GenateReyKey (); Byte [] EncodeFormat = SecretKey.getEncoded (); // convertit Key SecretKeyspec Key = new SecretKeyspec (EncodeFormat, "AES"); return clé; } / ** * Convertir le tableau d'octets en une chaîne représentant des valeurs hexadécimales. * Par exemple: octet [] {8,18} à: 0812 * et byte [] hexstr2bytes (String strin) sont des processus de conversion mutuellement réversibles. * @param bytes le tableau d'octet qui doit être converti * @return la chaîne convertie * / chaîne statique publique byte2hexstr (byte [] bytes) {int byteslen = bytes.length; // chaque octet est représenté par deux caractères, donc la longueur de la chaîne est deux fois la longueur du tableau StringBuffer hexstring = new StringBuffer (Byteslen * 2); pour (int i = 0; i <byteslen; i ++) {// effectuez chaque octet avec 0xff, puis convertissez-le en décimal, puis convertissez-le en hex par entier. String hex = Integer.tohexString (bytes [i] & 0xff); if (hex.length () <2) {hexstring.append (0); // si vous ajoutez 0 à 1 bit avant} hexString.append (hex); } return hexstring.toString (); } / ** * Convertir une chaîne représentant des HexValues en un tableau d'octets, * et une chaîne byte2hexstr (octet [] octets) sont des processus de conversion mutuellement réversibles. * @param bytes * @return Tableau d'octet converti * / octet statique public [] hexstr2bytes (String strin) {byte [] arrb = strin.getBytes (); int ilen = arrb.length; // Deux caractères représentent un octet, donc la longueur du tableau d'octet est la longueur de chaîne divisée par 2 octets [] Arrtif = New Byte [Ilen / 2]; for (int i = 0; i <ilen; i = i + 2) {String strtmp = new String (arrb, i, 2); Artire [i / 2] = (byte) Integer.ParseInt (strtmp, 16); } return arrout; }}Ce qui précède concerne cet article, j'espère qu'il sera utile pour tout le monde d'apprendre la programmation Java.