Android开发安全设置

随机数产生器

禁用:RandomMath.random()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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()方法中添加一行代码即可:

1
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

堆栈打印

禁用:

1
2
3
4
5
try {
...
} catch (IOException e) {
e.printStackTrace();
}

使用:

1
2
3
4
5
try {
...
} catch (IOException e) {
NLog.e(Constants.TAG, Log.getStackTraceString(e));
}

allowBackup属性

1
2
3
4
<application
android:allowBackup="false"
>
</application>

单例双重检查使用volatile限制编译器重排

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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后面跟着一个小括号,把资源的声明代码写进去即可

1
2
3
4
5
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
} catch (IOExcepton e) {

}
1
2
3
4
5
6
7
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-1SHA-3SHA-224SHA-256SHA-384SHA-512

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :