寫 Mobile app 有時需要存一些敏感的資訊,如果只是當做一個認證用途,大概就用 MD5 或 SHA1 來使用,但如果需要保留的,大概就需要能夠加密後又解密的,這時候就可以考慮拿一把 key 進行 AES Encryption/Decryption 動作。
簡易 SHA1:
import java.security.MessageDigest;
public static String sha1(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.reset();
byte[] out = digest.digest(input.getBytes("UTF-8"));
return android.util.Base64.encodeToString(out, android.util.Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
簡易 AES Encryption/Decryption (使用自製的 key):
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
public static String selfKey(String key) { // key.length() must be 16, 24 or 32
int length = key.length();
if( length < 16 ) {
for( int i=length ;i<16; ++i )
key += i%10;
return key;
} else if ( length < 24 ) {
for( int i=length ;i<24; ++i )
key += i%10;
return key;
} else if ( length < 32 ) {
for( int i=length ;i<32; ++i )
key += i%10;
return key;
}
return key.substring(0, 32);
}
public static String selfEncode(String key, String value) {
SecretKeySpec spec = new SecretKeySpec(selfKey(key).getBytes(), "AES");
Cipher cipher;
try {
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, spec);
return Base64.encodeToString(cipher.doFinal(value.getBytes()), android.util.Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String selfDecode(String key, String value) {
SecretKeySpec spec = new SecretKeySpec(selfKey(key).getBytes(), "AES");
Cipher cipher;
try {
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, spec);
return new String( cipher.doFinal(Base64.decode(value, android.util.Base64.NO_WRAP)) );
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
沒有留言:
張貼留言