1 25 26 package com.j2biz.blogunity.util; 27 28 import java.io.UnsupportedEncodingException ; 29 import java.security.MessageDigest ; 30 import java.security.NoSuchAlgorithmException ; 31 import java.security.NoSuchProviderException ; 32 33 import com.j2biz.blogunity.BlogunityManager; 34 import com.j2biz.blogunity.exception.BlogunityException; 35 import com.j2biz.blogunity.i18n.I18NStatusFactory; 36 import com.j2biz.blogunity.pojo.SystemConfiguration; 37 import com.j2biz.blogunity.pojo.User; 38 39 import sun.misc.BASE64Encoder; 40 41 public class PasswordEncryptionService { 42 43 public static final int MD5 = 1; 44 45 public static final int SHA = 2; 46 47 public static synchronized String encrypt(String text, int encryptionType) 48 throws NoSuchProviderException , NoSuchAlgorithmException , 49 UnsupportedEncodingException { 50 51 switch (encryptionType) { 52 53 case MD5: 54 return createMD5HashCode(text); 55 56 case SHA: 57 return createSHAHashCode(text); 58 59 default: 60 throw new NoSuchAlgorithmException ( 61 "Requested encription type ont found!"); 62 63 } 64 65 } 66 67 75 public static synchronized User encryptPasswordIfNecessary(User user) 76 throws BlogunityException { 77 boolean isEncryptionEnbaled = false; 78 SystemConfiguration config = BlogunityManager.getSystemConfiguration(); 79 if (config != null) 80 isEncryptionEnbaled = config.isPasswordEncriptionEnabled(); 81 82 if (isEncryptionEnbaled) { 84 try { 85 String encodedPass = PasswordEncryptionService.encrypt(user 86 .getPassword(), BlogunityManager 87 .getSystemConfiguration().getPasswordEncryptionType()); 88 user.setPassword(encodedPass); 89 } catch (Throwable t) { 90 throw new BlogunityException(I18NStatusFactory.createUnknown(t)); 91 } 92 } 93 94 return user; 95 } 96 97 106 private synchronized static String createMD5HashCode(String text) 107 throws NoSuchAlgorithmException , NoSuchProviderException { 108 String result = text; 109 110 if (text != null) { 111 StringBuffer code = new StringBuffer (); MessageDigest messageDigest = MessageDigest.getInstance("MD5", 113 "SUN"); 114 String plain = text; 115 byte bytes[] = plain.getBytes(); 116 byte digest[] = messageDigest.digest(bytes); for (int i = 0; i < digest.length; ++i) { 118 code.append(Integer.toHexString(0x0100 + (digest[i] & 0x00FF)) 119 .substring(1)); 120 } 121 122 result = code.toString(); 123 } 125 return result; 126 } 128 137 private synchronized static String createSHAHashCode(String plaintext) 138 throws NoSuchAlgorithmException , UnsupportedEncodingException { 139 MessageDigest md = null; 140 141 md = MessageDigest.getInstance("SHA"); 143 md.update(plaintext.getBytes("UTF-8")); 145 byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } 149 150 } | Popular Tags |