给初学者的 Android 加密工具

本文深入探讨了移动应用开发中安全性的重要性,着重介绍了如何在Android平台上使用简单且安全的方法进行数据加密。文章详细分析了流行的加密库如BouncyCastle、SpongyCastle、OpenSSL等,并提供了在开发安全应用时的选择指南。此外,文章还讨论了如何在应用中正确使用这些工具,以确保数据隐私和完整性。通过对比不同的加密算法和模式,如AES、DES、ECB、CBC等,读者将学会如何为特定需求选择最佳方案。

    Mobile applications draw the attention of hackers more and more each day because they have something that the attackers want, user data. Hard-coded secret keys, personal information stored in plain text on SD cards, usernames and passwords found unencrypted in databases, analytics collected and sent in the clear to remote servers, are just a few cases that make the life of an attacker easier.

  越来越多的黑客盯上了移动应用,每天都会增加,因为移动应用中有黑客感兴趣的东西,如用户数据。硬编码(Hard-coded,注,固定写死,不能修改的)安全秘钥,SD 卡中以明文存放的个人信息,数据库中未加密存储的用户名和密码,收集的分析(analytics)并以明文方式发到远程服务器,这些情况都使得攻击更容易(得手)。

     Cryptography is the right tool to use in order to protect sensitive data, and ensure confidentiality and/or integrity. On the other hand, cryptography is hard to use and easy to misuse. Note that broken cryptography (e.g. using insecure algorithms or hard-coding keys into binaries), is listed in the top 10 mobile risks for 2014. So what’s the lesson to be learned? Well, whereas not using cryptography can be bad, not using cryptography in the right way is just as bad (not to mention time-consuming).

  正确使用Cryptography 工具,能保护我们的敏感数据,确保隐私和数据完整。另一方面,加密难用且容易误用( cryptography is hard to use and easy to misuse)。 注意容易被破解的加密方式(broken cryptography) (如,使用不安全算法,或硬编码秘钥到二进制包),请查阅列表2014年,移动领域10大风险。因此,从中得到什么教训?不用加密不可取,不能正确加密同样不可取 (不提耗费的时间)。

     Let’s see then how cryptography can be used in a way that’s both easy and appropriate, in order to develop secure applications for the Android platform.

  为了能在安卓平台上开发出安全的应用,接下来我们将介绍如何能既简单又安全地进行加密。

     First, an overview of some popular cryptographic libraries that can be integrated into Android applications. Cryptographic libraries can be seen as cryptographic toolsets that contain tools, such as encryption algorithms, padding schemes, and hash functions.

  首先,概括性地介绍一些常见的可集成到安卓应用中的加密库。加密库是包含诸如加密算法、填充方式和散列函数等工具的加密工具集合。

  Bouncy Castle

          The  Legion of the Bouncy Castle  is a charity from Australia that has written  Bouncy Castle , a widely used library that provides both a light-weight cryptography API and a Java Cryptography Extension (JCE) provider. The Android platform already ships with a cut-down and outdated version of Bouncy Castle (with small changes in order to make it work on Android). Consequently any attempt to build and use the latest full version of the library in your application, results in classloader conflicts.

  充气城堡军团(Legion of the Bouncy Castle)是一个来自澳大利亚的公益团体,他们编写了Bouncy Castle 这个广泛使用的类库。该库既提供了一个轻量级的密码学 API,也是一个 Java 密码扩展(JCE)的提供者。安卓平台已经内置了一个精简过的老版本 Bouncy Castle(同时为了适配安卓平台也做了一些细小的改动)。结果就是任何在应用程序中构建和使用最新版本 BouncyCastle 类库的尝试都将导致类加载冲突。

  Spongy Castle

     The motivation behind Spongy Castle is to allow Android developers to bundle any version of the Bouncy Castle library they want with their applications. Spongy Castle is basically a repackage of the latest version of the Bouncy Castle library; all org.bouncycastle.* packages have been renamed to org.spongycastle.*, and the Java Security API provider’s name has been changed from BC to SC.

  Spongy Castle 背后的动机是允许安卓开发者在应用程序中使用任意版本的 BouncyCastle 类库。SpongyCastle 就是对最新版本的 BouncyCastle 进行了简单地重新打包;所有的 org.bouncycastle.* 包重命名为了 org.spongycastle.*,所有 Java安全 API 提供者的名字由 BC 改为了 SC。

  OpenSSL

      OpenSSL is an open-source toolkit that provides implementation for the SSL and TLS protocols, as well as a general-purpose cryptography library. OpenSSL has been ported to many platforms, including Android. As an alternative, you can also build it from source (using the Android NDK) and bundle it with your application.

  OpenSSL 是一个实现了 SSL 和 TLS 协议以及通用密码库的开源工具包。OpenSSL 已经被移植到了很多平台,包括安卓。做为一个替代方案,你也可以从源码构建(使用安卓 NDK),然后绑定到应用程序中。

      Let’s assume now, that for application purposes, you want to encrypt some data. What encryption algorithm should you use, AES or DES? How long should your key be, 128 or 256 bits? Which encryption mode should you use, ECB or CBC? If you do not have an answer to all these questions, along with a good reason for each answer, then it seems that you have found yourself in a position where, although you probably have all the tools you need, you are not absolutely sure which ones to use and how.

  现在我们假设出于应用程序的目的,你想要加密一些数据。你会使用哪个加密算法,AES 还是 DES?你的秘钥多长,128 还是 256 比特?你会使用哪种加密模式,ECB 还是 CBC?如果你对所有这些问题都没有答案,也没有好的理由,那么你可能发现你正处在一个微妙的位置,虽然你拥有所有你想要的工具,但是你一点儿都不确定使用哪个、如何使用。

     This is exactly the point where cryptographic toolkits for dummies come into play. These toolkits do not implement any exotic cryptographic functionalities, nor do they intend to replace the cryptographic libraries presented above; they rather built on some of them with the sole purpose of making cryptography easier and safer to use.

  这正是傻瓜密码学工具包发挥作用的场景。这些工具包并没有实现任何奇特的加密功能,也没有尝试替代任一上述的密码学库;相反它们基于这些类库构建,唯一的目的是使得使用加密功能更简单更安全。

     Contrary to a general-purpose cryptographic library, such a toolkit normally supports only a subset of the algorithms, modes, schemes, parameters, and other cryptographic tools that are out there. Instead it provides you with sensible defaults in case you (a) know what you want to do but don’t know how to do it, or (b) don’t really care as long as you end up with a safe solution. Let’s examine some of these toolkits to better understand their role.

  与通用密码学库相反,这些工具包通常只支持一部分算法、模式、结构、参数。对于通用加密工具需要设定的部分,这些工具包为你提供了合理的默认值,以防你知道想要什么,但是不知道如何使用,或者只在乎最终有个安全的解决方案。让我们检查几个这类工具包以便来更好的理解它们的运行规则。

  Keyczar

     Keyczar is an open-source toolkit originally developed by two members of the Google Security Team. It has implementations in Java, Python and C++. It supports authentication as well as both symmetric and asymmetric encryption. Keyczar provides safe defaults for algorithms, key lengths and modes, key rotation and versioning, automated generation of initialisation vectors and authentication codes, and internationalisation. This specific toolkit is based on JCE, and its demo for Android (available here), uses Spongy Castle’s security provider.

  Keyczar 是一组开源工具包,最初由两位 Google Security Team(谷歌安全团队)成员开发。 它用 Java,Python 和 C++ 语言实现。它支持对称加密和费堆成加密两种鉴权方式。Keyczar 提供安全的默认设定,包括算法,秘钥长度和模式,秘钥循环和版本化,初始向量(vector)和授权码自动生成,支持国际化。该工具包基于JCE构建,( here),使用了Spongy Castle的安全提供程序。

  AeroGear Crypto

     AeroGear Crypto is a small Java library provided by AeroGear. It supports authenticated symmetric encryption, elliptic curve cryptography, and password-based key derivation. It also provides sensible defaults for algorithms. AeroGear Crypto depends on Spongy Castle for Android and Bouncy Castle for other platforms. The library is also available for iOS, Windows Phone and Cordova.

  AeroGear Crypto 是 AeroGear 提供的一个小的 Java 库。 它支持可认证的对称加密,椭圆曲线加密,基于密码的秘钥推导。它也提供了算法的显式设定。AeroGear Crypto 在 android 平台依赖Spongy Castle,在其他平台上依赖 Bouncy Castle。该库在 iOS,Windows Phone 和 Cordova 上同样可用。

  Conceal

     In an attempt to find a fast and memory-efficient way to encrypt and authenticate large files on SD cards, Facebook developed Conceal. Conceal supports both authentication and encryption, and provides default implementations for key management. It uses OpenSSL, but includes only the necessary parts of it, thereby keeping its size at 85KB. Results published on the site of the library show that Conceal outperforms Bouncy Castle.

  为了能够快速并使用很少内存对SD卡上的大型文件实现加密和认证,脸谱开发出了 Conceal。Conceal既可以进行认证,也可以进行加密,同时默认也提供了密钥管理功能。它使用的是 OpenSSL,不过仅包含自己需要的那部分,因此其大小仅为 85KB。Conceal 站点上公布的结果显示它优于 Bouncy Castle。

     A summarised view of the libraries presented above is given in the following table. Note that, although all these libraries aim to safely fill in the gaps for developers that are new to cryptography, advanced developers can skip the defaults and specify all the details themselves (as they would do when using any crypto library).

  下表对上面所介绍的加密库做了总结。请注意:上面介绍的所有的库可以让加密方面的新手安全地进行加密,不过高级开发人员可以不使用这些默认做法,可以按照自己的意愿指定所有的加密细节(就像他们在使用其他加密库那样)。

AeroGear CryptoAeroGearApache 2.0
ConcealFacebookBSD
KeyczarApache 2.0
加密库开发公司许可证

  总结(To sum up)

      If you are a mobile developer, you need to spend time making your applications usable, functional, and attractive BUT you also have to spend time making your application secure.  If you do not know how to do so or if you’re worried that you might not get it right, then use one of the libraries described in this article in order to get started. No matter what cryptographic tools you decide to use, avoid implementing your own cryptographic algorithms and/or protocols; use only algorithms and protocols that are widely used, accepted, and ones that users have already spent enough time trying to break.

  如果你是一个移动应用开发者,你得花时间(精力)使你的应用程序便于使用,功能丰富,抓人眼球,但是,你不要忘了改善你应用的安全性。 如果你不懂怎么着手,或者担心做不对,那就从文中提到的工具包中选择一个,以便能够开始。不管你决定选用哪个加密工具都好,都应避免自己实现加密算法和加密协议; 应该只使用那些广泛应用的,普遍认可的,经受考验的算法和协议。

原文地址:http://www.developereconomics.com/android-cryptography-tools-for-beginners/

### 常见哈希函数及其实现 #### 1. **除留取余法** 这是最简单的一种哈希函数,其基本形式为 `H(key) = key % m`,其中 `key` 是输入的关键字,`m` 是哈希表的大小。这种方法的优点在于计算简便,但在实际应用中容易受到关键字分布的影响。 ```python def hash_modulo(key, table_size): return key % table_size ``` 此方法适用于关键字均匀分布在整数范围内的场景[^1]。 --- #### 2. **乘法散列法** 该方法通过将关键字与某个常量相乘后再提取部分位的方式生成哈希值。具体公式如下: \[ H(\text{key}) = \lfloor A \cdot (\text{key} \mod W) \rfloor \% M \] 其中 \(A\) 是一个小于 1 的正实数,\(W\) 和 \(M\) 分别表示机器字长和哈希表长度。这种算法能够有效降低因模运算带来的偏移影响。 ```python import math def hash_multiplication(key, table_size, constant=0.618033): scaled_key = key * constant fractional_part = scaled_key - math.floor(scaled_key) return int(table_size * fractional_part) ``` 它广泛应用于需要高随机性的场合,比如密码学领域[^4]。 --- #### 3. **双重哈希(Double Hashing)** 当单个哈希函数无法满足需求时,可以采用双哈希技术解决冲突问题。其核心思想是在发生碰撞后利用另一个辅助哈希函数调整探查序列。例如, \[ H_i = (H_1(\text{key}) + i \times H_2(\text{key})) \% M \] 这里 \(i\) 表示尝试次数,而 \(H_1\) 和 \(H_2\) 则分别代表主次两套不同的哈希规则[^2]。 ```python def double_hashing(key, primary_func, secondary_func, table_size): h1 = primary_func(key, table_size) h2 = secondary_func(key, table_size) def probe(i): return (h1 + i * h2) % table_size return probe ``` 这种方式特别适合那些对性能敏感的应用程序,如数据库管理系统中的索引设计。 --- #### 4. **FNV 哈希算法** 快速非加密型哈希(Fast Non-cryptographic Hash Algorithm,FNV)因其速度优势成为许多现代软件系统的默认选项之一。它的更新过程遵循以下模式: \[ \begin{aligned} &\text{hash} := FNV\_offset \\ &\forall c \in \text{input}: \\ &\quad \text{hash} *= FNV\_prime\\ &\quad \text{hash} ^= c\\ \end{aligned} \] 最终返回经过多次迭代后的累积结果作为目标位置指示符[^3]。 ```python def fnv_hash(input_string, prime=16777619, offset_basis=2166136261): hash_value = offset_basis for byte in input_string.encode('utf-8'): hash_value = hash_value ^ byte hash_value = hash_value * prime return hash_value & 0xFFFFFFFF ``` 由于具备良好的抗聚类特性,因此非常适合文件路径名解析或者网络包分类等领域。 --- #### 5. **MD5/SHA 系列消息摘要算法** 尽管严格意义上讲这些属于安全散列家族成员而非传统意义上的定位工具,但由于它们产生的固定长度指纹同样可用于构建分布式缓存机制或其他一致性哈希方案之中,故也在此提及一下。 ```python import hashlib def md5_hash(input_data): hasher = hashlib.md5() hasher.update(str(input_data).encode('utf-8')) return int(hasher.hexdigest(), 16) % (2**32) ``` 这类强健型解决方案更多服务于身份验证协议或是防止篡改检测等方面的需求。 --- ### 应用场景分析 每种类型的哈希函数都有各自适用的最佳环境: - 对于小型项目或资源受限设备来说,简单的线性同余变换可能已经足够; - 如果追求更高的质量,则推荐选用基于数学理论精心构造出来的复杂模型; - 而涉及到隐私保护或者是大规模并发访问控制的时候,则务必考虑引入工业标准级的安全框架支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值