이 예제는 모든 사람이 배울 수있는 Javase/Javaee/Android에 적합한 Java 암호화 및 암호 해독 도구를 공유합니다. 특정 내용은 다음과 같습니다
패키지 longshu.utils.security; import java.lang.reflect.method; import java.security.invalidkeyexception; import java.security.key; import java.security.messagegedigest; import java.security.nosuchalgorithmexception; import java.security.securerandom; import javax.crypto.badpaddingexception; import javax.crypto.cipher; import javax.crypto.illegalblocksizeexception; import javax.crypto.keygenerator; import javax.crypto.nosuchpaddingection; import javax.crypto.secretkey; javax.crypto.spec.secretkeyspec; /*** Java 암호화 및 암호 해독 도구. * javase/javaee/android 모두 적용 가능** @author Longshu 2016 년 4 월 13 일*/public class alcryptdecrypt {// 객체 개인 encryptdecrypt () {}/*** SHA1 암호화 비트 데이터* @Param 소스 배열* @Rettin Bytate (sha1bte) {try {MessageDigest Sha1digest = messageDigest.getInstance ( "SHA-1"); sha1digest.update (소스); 바이트 targetDigest [] = sha1digest.digest (); 대상 디그리스트 리턴; } catch (nosuchalgorithmexception e) {새로운 runtimeexception (e); }} / *** SHA1 암호화 된 문자열 데이터* @Param 소스 문자열 암호화* @return 암호화 문자열* / public static string sha1 (문자열 소스) {return byte2Hexstr (sha1bit ()); } / *** MD5 암호화 비트 데이터* @param 소스 바이트 배열* @return 암호화 바이트 배열* / public static byte [] md5bit (byte [] source) {try {// md5 digest 알고리즘의 MessageStance MessageDigest = messageStance ( "md5")의 messageDigest 개체를 얻습니다. // 다이제스트 업데이트 md5digest.update (source); // ciphertext return md5digest.digest ()를 가져옵니다. } catch (nosuchalgorithmexception e) {새로운 runtimeexception (e); }} / *** MD5 암호화 된 문자열, 32 비트 길이* @param 소스 컨텐츠 암호화* @return 암호화 된 컨텐츠* / public static string md5 (문자열 소스) {return byte2Hexstr (md5bit (source.getBytes ()); } / *** base64 인코딩* @param 소스 문자열 인코딩* @return 인코딩 된 문자열* / public static string encodebase64 (문자열 소스) {class <?> clazz = null; 메소드 encodemethod = null; 시도 {// 타사 라이브러리의 우선 순위 사용 clazz = class.forname ( "org.apache.commons.codec.binary.base64"); encodemethod = clazz.getMethod ( "encodebase64", byte []. class); System.out.println ( "encodebase64->" + Clazz); system.out.println ( "encodemethod->" + encodemethod); // 반사 방법의 정적 메소드는 return 새 문자열을 실행하기 위해 객체가 필요하지 않습니다 ((byte []) encodemethod.invoke (null, source.getBytes ())); } catch (classNotFoundException e) {문자열 vm = system.getProperty ( "java.vm.name"); System.out.println (vm); try {if ( "dalvik".equals (vm)) {// android clazz = class.forname ( "android.util.base64"); // byte [] base64.encode (byte [] input, int flags) encodemethod = clazz.getMethod ( "encode", byte []. class, int.class); System.out.println ( "encodebase64->" + Clazz); system.out.println ( "encodemethod->" + encodemethod); 새 문자열 ((byte []) encodemethod.invoke (null, source.getBytes (), 0)); } else {// javase/javaee clazz = class.forname ( "sun.misc.base64encoder"); encodemethod = clazz.getMethod ( "encode", byte []. class); System.out.println ( "encodebase64->" + Clazz); system.out.println ( "encodemethod->" + encodemethod); return (string) encodemethod.invoke (clazz.newinstance (), source.getBytes ()); }} catch (classNotFoundException e1) {return null; } catch (예외 e1) {return null; }} catch (예외 e) {return null; } / * * android * android.util.base64 * // return base64.encodetoString (source, base64.default); // 새 문자열을 반환합니다 (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 // 새 문자열을 반환합니다 (base64.encodebase64 (source.getBytes ())); } / *** Base64 Decoding* @param alcodesource encodesource encodesource* @return string* / public static string decodebase64 (String encodesource) {class <?> clazz = null; 방법 decodemethod = null; 시도 {// 타사 라이브러리의 우선 순위 사용 clazz = class.forname ( "org.apache.commons.codec.binary.base64"); decodemethod = clazz.getMethod ( "decodebase64", byte []. class); System.out.println ( "DecodeBase64->" + Clazz); System.out.println ( "decodemethod->" + decodemethod); // 객체없이 정적 반사 메소드를 실행합니다. 리턴 새 문자열 ((byte []) decodemethod.invoke (null, encodesource.getBytes ())); } catch (classNotFoundException e) {문자열 vm = system.getProperty ( "java.vm.name"); System.out.println (vm); try {if ( "dalvik".equals (vm)) {// android clazz = class.forname ( "android.util.base64"); // byte [] base64.decode (byte [] input, int flags) decodemethod = clazz.getMethod ( "decode", byte []. class, int.class); System.out.println ( "DecodeBase64->" + Clazz); System.out.println ( "decodemethod->" + decodemethod); 새 문자열 ((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); 새 문자열 ((byte []) decodemethod.invoke (clazz.newinstance (), encodesource)를 반환합니다. }} catch (classNotFoundException e1) {return null; } catch (예외 e1) {return null; }} catch (예외 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 (); // 새 문자열을 반환합니다 (decoder.decodebuffer (encodesource)); //} catch (ioException e) {// 새로운 runtimeexception (e)을 던집니다. //} // org.apache.commons.codec.binary.base64 // 새 문자열 (base64.decodebase64 (encodesource.getBytes ())); }/*** aes 암호화* @param 컨텐츠 컨텐츠 암호화* @param 비밀번호 암호화 암호* @return*/public static byte [] alcryptbitaes (byte [] content, string password) {try {cipher alcyptcipher = cipher.getinstance ( "aes/ecb/pkcs5padding"); EncryptCipher.init (cipher.encrypt_mode, getkey (password)); // byte 초기화 [] result = encryptCipher.dofinal (content); 반환 결과; // encrypt} catch (nosuchalgorithmexception e) {e.printstacktrace (); } catch (nosuchPaddingException e) {e.printstacktrace (); } catch (invalidkeyException e) {e.printstacktrace (); } catch (delegalBlocksizeexception e) {e.printstacktrace (); } catch (badpaddingException e) {e.printstacktrace (); } return null; }/*** aes deScrypt* @param 컨텐츠 콘텐츠는 해독 될* @param password decrypt key* @return*/public static byte [] decryptbitaes (byte [] content, string password) {try {cipher decryptcipher = cipher.getInstance ( "aes/ecb/pkcs5padding"; // create password "; decryptCipher.init (cipher.decrypt_mode, getkey (password)); // byte 초기화 [] result = decryptCipher.dofinal (content); 반환 결과; // 암호화 결과} catch (invalidkeyException e) {e.printstacktrace (); } catch (nosuchalgorithmexception e) {e.printstacktrace (); } catch (nosuchPaddingException e) {e.printstacktrace (); } catch (delegalBlocksizeexception e) {e.printstacktrace (); } catch (badpaddingException e) {e.printstacktrace (); } return null; } / *** AES 문자열 암호화* @param 컨텐츠 컨텐츠 암호화* @param 비밀번호 암호화 암호* @return* / public static string alcryptaes (문자열 콘텐츠, 문자열 암호) {return byte2Hexstr (content.getBytes (), password)); } / *** AES 문자열 암호 해독* @Param 컨텐츠 해독 될* @Param 비밀번호 해독 키* @return* / public static String decryptaes (문자열 내용, 문자열 암호) {return new String (decryptbitaes (content), password)); } / *** 지정된 문자열에서 키를 생성* @param 비밀번호 키를 구성하는 문자열* @return 생성 된 키* @throws nosuchalgorithmexception* / private static key getkey (string password)는 nosuchalgorithmexception {securerandom securrandom = new securerandom (password.getbytes ()); // key keygenerator kgen = keygenerator.getInstance ( "aes")를 생성합니다. kgen.init (128, Securerandom); Secretkey Secretkey = Kgen.generatekey (); 바이트 [] encodeformat = secretkey.getencoded (); // 키 SecretKeyspec Key = New SecretKeyspec 변환 (EncodeFormat, "AES"); 리턴 키; } /*** 바이트 배열을 16 진수 값을 나타내는 문자열로 변환합니다. * 예 : 바이트 [] {8,18} ~ : 0812 * 및 바이트 [] hexstr2Bytes (String)는 상호 가역적 변환 프로세스입니다. * @Param 바이트 변환 해야하는 바이트 배열* @Return 변환 된 문자열*/ public static String byte2Hexstr (byte [] bytes) {int byteslen = bytes.length; // 각 바이트는 두 문자로 표시되므로 문자열의 길이는 배열의 길이의 두 배입니다. for (int i = 0; i <byteslen; i ++) {// 각 바이트를 0xff로 수행 한 다음 10 진수로 변환 한 다음 정수로 16 진로 변환합니다. 문자열 hex = integer.toHexString (바이트 [i] & 0xff); if (hex.length () <2) {hexstring.append (0); // hexstring.append (hex); } return hexstring.toString (); } /** * 육각형을 나타내는 문자열을 바이트 배열로 변환하십시오. * 및 String Byte2Hexstr (byte [] bytes)는 상호 가역적 변환 프로세스입니다. * @param bytes * @return 변환 바이트 배열 */ public static byte [] hexstr2bytes (String strin) {byte [] arrb = strin.getBytes (); int ilen = arrb.length; // 두 문자는 바이트를 나타내므로 바이트 배열의 길이는 문자열 길이를 2 바이트 [] Arrout = new Byte [ilen / 2]로 나눈 값입니다. for (int i = 0; i <ilen; i = i + 2) {string strtmp = new String (arrb, i, 2); Arrout [I / 2] = (바이트) integer.parseint (strtmp, 16); } return arrout; }}위의 내용은이 기사에 관한 모든 것입니다. 모든 사람들이 Java 프로그래밍을 배우는 것이 도움이되기를 바랍니다.