android绑定keystore,Android密钥库系统KeyStore

1.什么是密钥库系统?

利用 Android 密钥库系统,您可以在容器中存储加密密钥,从而提高从设备中提取密钥的难度。在密钥进入密钥库后,可以将它们用于加密操作,而密钥材料仍不可导出。此外,它提供了密钥使用的时间和方式限制措施,例如要求进行用户身份验证才能使用密钥,或者限制为只能在某些加密模式中使用。

密钥库系统并不是让程序直接进行存储程序的私密信息的,比如说用户账号密码,其提供了一个密钥安全容器,保护密钥材料免遭未经授权的使用,一个应用程序可以在密钥库中存储多个密钥并且只允许应用自身访问,应用程序可以在密钥库系统中生成,存储,获取存储其中的公钥或者私钥,因此可使用密钥库系统中的密钥来进行数据的加密。

密钥库系统由 KeyChain API 以及在 Android 4.3(API 级别 18)中引入的 Android 密钥库提供程序功能使用。

安卓系统提供了下面几种KeyStore类型:

0a2d5a1596b4

image.png

下面操作都是基于AndroidKeyStore

2.密钥库的操作(生成密钥,删除密钥,加密,解密)

先创建一个Activity,自定义布局从页面上来实现几种功能

android:layout_width="match_parent"

android:layout_height="match_parent"

xmlns:tools="http://schemas.android.com/tools">

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context=".MainActivity">

android:id="@+id/edit_text"

android:layout_width="match_parent"

android:layout_height="50dp"

android:layout_marginTop="5dp" />

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="5dp"

android:gravity="center"

android:orientation="horizontal">

android:id="@+id/btn_add"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:onClick="onAddKey"

android:text="添加" />

android:id="@+id/btn_delete"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:onClick="onDeleteKey"

android:text="删除" />

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:orientation="horizontal">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:padding="5dp"

android:text="明文:" />

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="5dp"

android:text="@string/plaintext" />

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="5dp"

android:text="加密/解密(Base64):" />

android:id="@+id/tv_cipher"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="5dp" />

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="5dp"

android:gravity="center"

android:orientation="horizontal">

android:id="@+id/btn_encrypt"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:onClick="doEncrypt"

android:text="加密" />

android:id="@+id/btn_decrypt"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:onClick="doDecrypt"

android:text="解密" />

android:id="@+id/tv_current"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#FFDBD9"

android:gravity="center|left"

android:padding="5dp"

android:text="@string/current_key"

android:textSize="12sp" />

android:id="@+id/recyclerview"

android:layout_width="match_parent"

android:layout_height="match_parent">

效果图:

0a2d5a1596b4

device-2018-06-14-162258.png

0a2d5a1596b4

device-2018-06-14-162604.png

说明:

1.输入框输入要增加的密钥的名称,点击添加按钮进行添加一个新密钥;

2.输入框输入要删除的密钥的名称,点击删除按钮进行删除一个已存在的密钥;

3.这里指定了数据明文,点击密钥列表中的item可选中指定的密钥,用于使用密钥进行加密和解密,选中密钥后,可点击加密按钮进行加密,加密后可点击解密按钮进行解密;

4.密钥列表显示当前应用在密钥库系统中生成了的密钥,长按可删除密钥;

MainActivity

package com.iigo.keystore;

import android.os.Bundle;

import android.support.annotation.NonNull;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.DividerItemDecoration;

import android.support.v7.widget.LinearLayoutManager;

import android.support.v7.widget.RecyclerView;

import android.text.TextUtils;

import android.util.Base64;

import android.view.View;

import android.view.ViewGroup;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

import java.util.ArrayList;

import java.util.Enumeration;

import java.util.List;

public class MainActivity extends AppCompatActivity {

private RecyclerView recyclerView;

private Adapter adapter;

private List aliasList = new ArrayList<>();

private EditText editText;

private TextView tvKey;

private TextView tvCipher;

private String plainText; //明文

private String encryptData; //加密后字符串

private String currentSelectedKeyAlias;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

initViews();

updateKeys();

//验证数据签名

String data = "1234";

byte[] sign = KeyStoreUtil.get().sign(data.getBytes(), "qq");

System.out.println("verify: "+KeyStoreUtil.get().verify(data.getBytes(), sign, "qq"));

}

private void updateKeys() {

aliasList.clear();

Enumeration aliases = KeyStoreUtil.get().getAliases();

if (aliases!= null){

while (aliases.hasMoreElements()){

aliasList.add(aliases.nextElement());

}

}

adapter.notifyDataSetChanged();

}

private void initViews() {

recyclerView = findViewById(R.id.recyclerview);

recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

recyclerView.addItemDecoration(new DividerItemDecoration(getBaseContext(), DividerItemDecoration.VERTICAL));

adapter = new Adapter();

adapter.setItemClickListener(itemClickListener);

recyclerView.setAdapter(adapter);

editText = findViewById(R.id.edit_text);

tvKey = findViewById(R.id.tv_current);

tvCipher = findViewById(R.id.tv_cipher);

tvKey.setText(getString(R.string.current_key, ""));

plainText = getString(R.string.plaintext);

}

@Override

protected void onPause() {

super.onPause();

if (isFinishing()){

aliasList.clear();

}

}

public void onAddKey(View view){

String alias = editText.getText().toString();

if (!TextUtils.isEmpty(alias)){

KeyStoreUtil.get().generateKey(getBaseContext(), alias);

updateKeys();

}

}

public void onDeleteKey(View view){

deleteKey(editText.getText().toString());

}

private void deleteKey(String alias){

if (!TextUtils.isEmpty(alias)){

KeyStoreUtil.get().deleteKey(alias);

updateKeys();

}

}

private OnItemClickListener itemClickListener = new OnItemClickListener() {

@Override

public void onItemClick(View view, int position) {

currentSelectedKeyAlias = aliasList.get(position);

tvKey.setText(getString(R.string.current_key, currentSelectedKeyAlias));

}

@Override

public boolean onItemLongClick(View view, int position) {

deleteKey(aliasList.get(position));

return true;

}

};

public void doEncrypt(View view) {

if (currentSelectedKeyAlias == null){

Toast.makeText(getApplicationContext(), "请先选取alias", Toast.LENGTH_SHORT).show();

return;

}

byte[] data = KeyStoreUtil.get().encrypt(plainText.getBytes(), currentSelectedKeyAlias);

if (data != null){

encryptData = Base64.encodeToString(data, Base64.DEFAULT);

tvCipher.setText(getString(R.string.encrypt_content, encryptData));

}

}

public void doDecrypt(View view) {

if (currentSelectedKeyAlias == null){

Toast.makeText(getApplicationContext(), "请先选取alias", Toast.LENGTH_SHORT).show();

return;

}

byte[] data = KeyStoreUtil.get().decrypt(Base64.decode(encryptData, Base64.DEFAULT), currentSelectedKeyAlias);

if (data != null){

tvCipher.setText(getString(R.string.decrypt_content, new String(data)));

}

}

private class ViewHolder extends RecyclerView.ViewHolder{

TextView textView;

public ViewHolder(View itemView) {

super(itemView);

textView = itemView.findViewById(R.id.tv_name);

}

}

private class Adapter extends RecyclerView.Adapter {

private OnItemClickListener itemClickListener;

@NonNull

@Override

public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

View view = getLayoutInflater().inflate(R.layout.layout_item, parent, false);

return new ViewHolder(view);

}

@Override

public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {

holder.textView.setText(aliasList.get(position));

holder.itemView.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (itemClickListener != null){

itemClickListener.onItemClick(v, position);

}

}

});

holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {

@Override

public boolean onLongClick(View v) {

if (itemClickListener != null){

return itemClickListener.onItemLongClick(v, position);

}

return false;

}

});

}

@Override

public int getItemCount() {

return aliasList.size();

}

public void setItemClickListener(OnItemClickListener itemClickListener){

this.itemClickListener = itemClickListener;

}

}

public interface OnItemClickListener{

void onItemClick(View view, int position);

boolean onItemLongClick(View view, int position);

}

}

密钥库系统工具类

package com.iigo.keystore;

import android.content.Context;

import android.security.KeyPairGeneratorSpec;

import android.text.TextUtils;

import java.io.IOException;

import java.math.BigInteger;

import java.security.InvalidAlgorithmParameterException;

import java.security.InvalidKeyException;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.KeyStore;

import java.security.KeyStoreException;

import java.security.NoSuchAlgorithmException;

import java.security.NoSuchProviderException;

import java.security.PrivateKey;

import java.security.Signature;

import java.security.SignatureException;

import java.security.UnrecoverableEntryException;

import java.security.cert.CertificateException;

import java.security.interfaces.RSAPublicKey;

import java.util.Calendar;

import java.util.Enumeration;

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

import javax.security.auth.x500.X500Principal;

/**

* @author SamLeung

* @Emial 729717222@qq.com

* @date 2018/6/14 0014 12:15

*/

public class KeyStoreUtil {

private static KeyStoreUtil INSTANCE;

private static Object LOCK = new Object();

private KeyStore keyStore;

private X500Principal x500Principal; //自签署证书

private static final String CIPHER_TRANSFORMATION = "RSA/ECB/PKCS1Padding";

private KeyStoreUtil(){

init();

}

private void init() {

try {

keyStore = KeyStore.getInstance("AndroidKeyStore");

keyStore.load(null);

/**

* CN commonName

* O organizationName

* OU organizationalUnitName

* C countryName

* */

x500Principal = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US");

} catch (KeyStoreException e) {

e.printStackTrace();

} catch (CertificateException e) {

e.printStackTrace();

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

public static KeyStoreUtil get(){

if (INSTANCE == null){

synchronized (LOCK){

if (INSTANCE == null){

INSTANCE = new KeyStoreUtil();

}

}

}

return INSTANCE;

}

/**

* 获取当前应用密钥库中的条目

*

* @return

* */

public Enumeration getAliases(){

if (keyStore == null) {

return null;

}

try {

return keyStore.aliases();

} catch (KeyStoreException e) {

e.printStackTrace();

}

return null;

}

/**

* 先判断是否存在该别名

* */

public boolean containsAlias(String alias) {

if (keyStore == null || TextUtils.isEmpty(alias)){

return false;

}

boolean contains = false;

try{

contains = keyStore.containsAlias(alias);

}catch (Exception e){

e.printStackTrace();

}

return contains;

}

/**

* 生成新的密钥

*

* @param context

* @param alias 存储在KeyStore中的别名

* */

public KeyPair generateKey(Context context, String alias){

if (containsAlias(alias)){

return null;

}

try {

Calendar endDate = Calendar.getInstance();

endDate.add(Calendar.YEAR, 10);

KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context.getApplicationContext())

.setAlias(alias)

.setSubject(x500Principal)

.setSerialNumber(BigInteger.ONE)

.setStartDate(Calendar.getInstance().getTime())

.setEndDate(endDate.getTime())

.build();

KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");

generator.initialize(spec);

return generator.generateKeyPair();

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (NoSuchProviderException e) {

e.printStackTrace();

} catch (InvalidAlgorithmParameterException e) {

e.printStackTrace();

} catch (NullPointerException e){

e.printStackTrace();

}

return null;

}

public void deleteKey(final String alias){

try{

keyStore.deleteEntry(alias);

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 加密

*

* @param data 要加密的数据

* @param alias KeyStore中的别名

* */

public byte[] encrypt(byte[] data, String alias){

try {

//取出密钥

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);

RSAPublicKey publicKey = (RSAPublicKey) privateKeyEntry.getCertificate().getPublicKey();

Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

return cipher.doFinal(data);

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (InvalidKeyException e) {

e.printStackTrace();

} catch (UnrecoverableEntryException e) {

e.printStackTrace();

} catch (NoSuchPaddingException e) {

e.printStackTrace();

} catch (KeyStoreException e) {

e.printStackTrace();

} catch (BadPaddingException e) {

e.printStackTrace();

} catch (IllegalBlockSizeException e) {

e.printStackTrace();

}

return null;

}

/**

* 解密

*

* @param data 要解密的数据

* @param alias KeyStore中的别名

* */

public byte[] decrypt(byte[] data, String alias){

try {

//取出密钥

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);

PrivateKey privateKey = privateKeyEntry.getPrivateKey();

Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);

cipher.init(Cipher.DECRYPT_MODE, privateKey);

return cipher.doFinal(data);

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (InvalidKeyException e) {

e.printStackTrace();

} catch (UnrecoverableEntryException e) {

e.printStackTrace();

} catch (NoSuchPaddingException e) {

e.printStackTrace();

} catch (KeyStoreException e) {

e.printStackTrace();

} catch (BadPaddingException e) {

e.printStackTrace();

} catch (IllegalBlockSizeException e) {

e.printStackTrace();

}

return null;

}

/**

* 对数据进行签名

*

* @param data

* @param alias

* */

public byte[] sign(byte[] data, String alias){

try{

//取出密钥

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);

Signature s = Signature.getInstance("SHA1withRSA");

s.initSign(privateKeyEntry.getPrivateKey());

s.update(data);

return s.sign();

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (KeyStoreException e) {

e.printStackTrace();

} catch (UnrecoverableEntryException e) {

e.printStackTrace();

} catch (SignatureException e) {

e.printStackTrace();

} catch (InvalidKeyException e) {

e.printStackTrace();

}

return null;

}

/**

* 验证数据签名

*

* @param data 原始数据

* @param signatureData 签署的数据

* @param alias

* */

public boolean verify (byte[] data, byte[] signatureData, String alias){

try{

//取出密钥

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);

Signature s = Signature.getInstance("SHA1withRSA");

s.initVerify(privateKeyEntry.getCertificate());

s.update(data);

return s.verify(signatureData);

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (InvalidKeyException e) {

e.printStackTrace();

} catch (SignatureException e) {

e.printStackTrace();

} catch (UnrecoverableEntryException e) {

e.printStackTrace();

} catch (KeyStoreException e) {

e.printStackTrace();

}

return false;

}

}

生成新密钥

生成密钥时使用X500Principal指定了自签署证书,参数分别代表

CN:通用名称

O:组织

OU:组织单元

C:国家

并且指定密钥的有效时间,并且指定了用于生成密钥对的自签名证书的序列号。

这里指定了通过密钥库系统生成RSA密钥。

/**

* CN commonName

* O organizationName

* OU organizationalUnitName

* C countryName

* */

x500Principal = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US");

Calendar endDate = Calendar.getInstance();

endDate.add(Calendar.YEAR, 10);

KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context.getApplicationContext())

.setAlias(alias)

.setSubject(x500Principal)

.setSerialNumber(BigInteger.ONE)

.setStartDate(Calendar.getInstance().getTime())

.setEndDate(endDate.getTime())

.build();

KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");

generator.initialize(spec);

return generator.generateKeyPair();

删除密钥

keyStore.deleteEntry(alias);

使用密钥加密

先从密钥库中取出密钥,使用公钥进行加密

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);

RSAPublicKey publicKey = (RSAPublicKey) privateKeyEntry.getCertificate().getPublicKey();

Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

return cipher.doFinal(data);

使用密钥解密

先从密钥库中取出密钥,使用私钥进行解密

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);

PrivateKey privateKey = privateKeyEntry.getPrivateKey();

Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);

cipher.init(Cipher.DECRYPT_MODE, privateKey);

return cipher.doFinal(data);

使用密钥对数据签名

使用密钥对数据签名,签名算法须与秘钥算法保持一致。

public byte[] sign(byte[] data, String alias){

try{

//取出密钥

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);

Signature s = Signature.getInstance("SHA1withRSA");

s.initSign(privateKeyEntry.getPrivateKey());

s.update(data);

return s.sign();

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (KeyStoreException e) {

e.printStackTrace();

} catch (UnrecoverableEntryException e) {

e.printStackTrace();

} catch (SignatureException e) {

e.printStackTrace();

} catch (InvalidKeyException e) {

e.printStackTrace();

}

return null;

}

数据签名认证

使用密钥对数据进行签名认证,签名算法须与秘钥算法保持一致。

public boolean verify (byte[] data, byte[] signatureData, String alias){

try{

//取出密钥

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);

Signature s = Signature.getInstance("SHA1withRSA");

s.initVerify(privateKeyEntry.getCertificate());

s.update(data);

return s.verify(signatureData);

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (InvalidKeyException e) {

e.printStackTrace();

} catch (SignatureException e) {

e.printStackTrace();

} catch (UnrecoverableEntryException e) {

e.printStackTrace();

} catch (KeyStoreException e) {

e.printStackTrace();

}

return false;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值