Android开发安全设置
随机数产生器
禁用:Random
,Math.random()
public class RandomUtil {
private static final String digitalChars = "0123456789";
public static String generateRandomDigits(int num) {
char[] rands = new char[num];
for (int i = 0; i < num; i++) {
int rand = (int) (Math.random() * 10);
rands[i] = digitalChars.charAt(rand);
}
return new String(rands);
}
}
使用:SecureRandom
public class RandomUtil {
private static final String SHA1PRNG = "SHA1PRNG";
private static final String digitalChars = "0123456789";
public static String generateRandomDigits(int num) {
try {
SecureRandom sr = SecureRandom.getInstance(SHA1PRNG);
char[] rands = new char[num];
for (int i = 0; i < num; i++) {
int rand = sr.nextInt(10);
rands[i] = digitalChars.charAt(rand);
}
return new String(rands);
} catch (NoSuchAlgorithmException e) {
NLog.e(Constants.TAG, Log.getStackTraceString(e));
}
return "";
}
}
禁止用户截屏
禁止截屏的实现方式并不是很难,在需要设置禁止截屏的 Activity 的生命周期onCreate()
方法中添加一行代码即可:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
堆栈打印
禁用:
try {
...
} catch (IOException e) {
e.printStackTrace();
}
使用:
try {
...
} catch (IOException e) {
NLog.e(Constants.TAG, Log.getStackTraceString(e));
}
allowBackup属性
<application
android:allowBackup="false"
>
</application>
单例双重检查使用volatile限制编译器重排
public class AuthHelper {
private static volatile AuthHelper mAuthHelper;
private AuthHelper(Context context) {
}
public static AuthHelper getInstance(Context context) {
if (mAuthHelper == null) {
synchronized (AuthHelper.class) {
if (mAuthHelper == null) {
mAuthHelper = new AuthHelper(context.getApplicationContext());
}
}
}
return mAuthHelper;
}
}
务必增加finally代码对数据流进行关闭
(1)在finally代码对数据流进行关闭
(2)使用try-with-statement
语法糖
try-with-statement
用来替代繁琐的try-catch-finnally
,它会自动close所有实现java.lang.AutoCloseable
接口的资源
写法是在try后面跟着一个小括号,把资源的声明代码写进去即可
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
} catch (IOExcepton e) {
}
private static void saveBitmapFile(Bitmap bm, String filePath) throws IOException {
File file = new File(filePath);
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
}
}
禁用MD5作为摘要算法
弱加密散列不能保证数据完整性,不应在安全关键的上下文中使用
推荐使用SHA-1
、SHA-3
、SHA-224
、SHA-256
、SHA-384
、SHA-512
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/18/android-development-security-settings/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
共有 0 条评论