最近在做保密的一些东西,看了大概有不到两天了,稍微有了一点小收获,再次做个记录,见证我android成长的经历
之前并没有做过加密这方面的东西,前两天有人告诉了我一个trustzone,我开始翻阅这方面的资料,开始的时候我是懵逼的,因为有一篇基础文章写着,trustzone基础开发之hello_world,我还以为很简单,就进去看了看,要求Linux环境。。。还要有一堆我没有掌握的知识,还要用eclipse,望天。。。当时整个人是崩溃的,只能再一点点翻阅别的资料,不得不说,有的时候网上资料也很匮乏。。。最后我在android官方文档上看到了这一块的解决方案,keystory是已经由google提供好了的api,可以实现trustzone的安全世界环境,将私钥放入安全世界,永远不会出现在进程世界,以此来实现保密,不过前些日子除了一个trustzone可以被降级攻破的新闻,算了,我一个小小的android程序员,写着一个小小的APP,不至于会有大神来攻破我。。。。
下面放上四处搜罗来的代码,全是血与泪,痛苦与挣扎的产物。。。
首先这个EC加签验签(有大神看到的话能解答下我疑惑么,就是加签和加密的区别,我就知道加签是校验合法性,加密是保密性,然后这个EC算法的话为什么我只能用signature来做,用Cipher就不行呢,还是说我那里没理解,反正到现在也是蒙蒙的 手动摊手表示无奈:-( )
private static String src = "ecdsa security";
public static void jdkECDSA(){
try {
//1.初始化密钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
keyPairGenerator.initialize(256);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic();
String format = ecPublicKey.getFormat();
byte[] encoded = ecPublicKey.getEncoded();
ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate();
//2.执行签名
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Signature signature = Signature.getInstance("SHA1withECDSA");
signature.initSign(privateKey);
signature.update(src.getBytes());
byte[] res = signature.sign();
//System.out.println("签名:"+HexBin.encode(res));
//3.验证签名
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
keyFactory = KeyFactory.getInstance("EC");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
signature = Signature.getInstance("SHA1withECDSA");
signature.initVerify(publicKey);
signature.update(src.getBytes());
boolean bool = signature.verify(res);
System.out.println("验证:"+bool);
} catch (Exception e) {
e.printStackTrace();
}
}
然后是RSA的一个加密解密
public class EncryUtils {
static EncryUtils encryUtilsInstance;
KeyStore keyStore;
private PublicKey mpublicKey;
private PrivateKey mprivateKey;
public String getPublicKey() {
byte[] encoded = mpublicKey.getEncoded();
String s = new String(Base64.encode(encoded, Base64.DEFAULT));
Log.e("==============", s);
return s;
}
public static EncryUtils getInstance() {
synchronized (EncryUtils.class) {
if (null == encryUtilsInstance) {
encryUtilsInstance = new EncryUtils();
}
}
return encryUtilsInstance;
}
public EncryUtils() {
// initKeyStore();
}
private void initKeyStore(String alias){
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
}
catch(Exception e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
createNewKeys(alias);
}
}
private void createNewKeys(String alias){
if(!"".equals(alias)){
try {
// Create new key if needed
if (!keyStore.containsAlias(alias)) {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.YEAR, 1);
KeyPairGeneratorSpec spec = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
spec = new KeyPairGeneratorSpec.Builder(Application.getApplication())
.setAlias(alias)
.setSubject(new X500Principal("CN=Sample Name, O=Android Authority"))
.setSerialNumber(BigInteger.ONE)
.setStartDate(start.getTime())
.setEndDate(end.getTime())
.build();
}
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
generator.initialize(spec);
}
KeyPair keyPair = generator.generateKeyPair();
mpublicKey = keyPair.getPublic();
String publicKey = getPublicKey();
// mprivateKey = keyPair.getPrivate();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 加密方法
* @param needEncryptWord 需要加密的字符串
* @param alias 加密秘钥
* @return
*/
public String encryptString(String needEncryptWord, String alias) {
if(!"".equals(alias)&&!"".equals(needEncryptWord)){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
initKeyStore(alias);
}
String encryptStr="";
byte [] vals=null;
try {
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);
// RSAPublicKey publicKey = (RSAPublicKey) privateKeyEntry.getCertificate().getPublicKey();
if(needEncryptWord.isEmpty()) {
// Toast.makeText(this, "Enter text in the 'Initial Text' widget", Toast.LENGTH_LONG).show();
return encryptStr;
}
// Cipher inCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
Cipher inCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
// inCipher.init(Cipher.ENCRYPT_MODE, publicKey);
inCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(
outputStream, inCipher);
cipherOutputStream.write(needEncryptWord.getBytes("UTF-8"));
cipherOutputStream.close();
vals = outputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return Base64.encodeToString(vals, Base64.DEFAULT);
}
return "";
}
public String decryptString(String needDecryptWord, String alias) {
if(!"".equals(alias)&&!"".equals(needDecryptWord)){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
initKeyStore(alias);
}
String decryptStr="";
try {
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);
// RSAPrivateKey privateKey = (RSAPrivateKey) privateKeyEntry.getPrivateKey();
// Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding");
// output.init(Cipher.DECRYPT_MODE, privateKey);
output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());
CipherInputStream cipherInputStream = new CipherInputStream(
new ByteArrayInputStream(Base64.decode(needDecryptWord, Base64.DEFAULT)), output);
ArrayList values = new ArrayList<>();
int nextByte;
while ((nextByte = cipherInputStream.read()) != -1) {
values.add((byte)nextByte);
}
byte[] bytes = new byte[values.size()];
for(int i = 0; i < bytes.length; i++) {
bytes[i] = values.get(i).byteValue();
}
decryptStr = new String(bytes, 0, bytes.length, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return decryptStr;
}
return "";
}
}