Android 获取签名公钥和公钥私钥加解密的方法(推荐)
如下所示:
publicclassGetPublicKey{
/**
*获取签名公钥
*@parammContext
*@return
*/
protectedstaticStringgetSignInfo(ContextmContext){
Stringsigncode="";
try{
PackageInfopackageInfo=mContext.getPackageManager().getPackageInfo(
GetAppInfo.getPackageName(mContext),PackageManager.GET_SIGNATURES);
Signature[]signs=packageInfo.signatures;
Signaturesign=signs[0];
signcode=parseSignature(sign.toByteArray());
signcode=signcode.toLowerCase();
}catch(Exceptione){
Log.e(Constants.TAG,e.getMessage(),e);
}
returnsigncode;
}
protectedstaticStringparseSignature(byte[]signature){
Stringsign="";
try{
CertificateFactorycertFactory=CertificateFactory
.getInstance("X.509");
X509Certificatecert=(X509Certificate)certFactory
.generateCertificate(newByteArrayInputStream(signature));
StringpubKey=cert.getPublicKey().toString();
Stringss=subString(pubKey);
ss=ss.replace(",","");
ss=ss.toLowerCase();
intaa=ss.indexOf("modulus");
intbb=ss.indexOf("publicexponent");
sign=ss.substring(aa+8,bb);
}catch(CertificateExceptione){
Log.e(Constants.TAG,e.getMessage(),e);
}
returnsign;
}
publicstaticStringsubString(Stringsub){
Patternpp=Pattern.compile("\\s*|\t|\r|\n");
Matchermm=pp.matcher(sub);
returnmm.replaceAll("");
}
}
packagecom.example.xscamera;
importjava.io.ByteArrayOutputStream;
importjava.security.Key;
importjava.security.KeyFactory;
importjava.security.KeyPair;
importjava.security.KeyPairGenerator;
importjava.security.PrivateKey;
importjava.security.PublicKey;
importjava.security.Signature;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjava.security.spec.PKCS8EncodedKeySpec;
importjava.security.spec.X509EncodedKeySpec;
importjava.util.HashMap;
importjava.util.Map;
importjavax.crypto.Cipher;
/**
*<p>
*RSA公钥/私钥/签名工具包
*<p>
*字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
*由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
*非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
*</p>
*
*/
publicclassRSAUtils{
/**
*加密算法RSA
*/
publicstaticfinalStringKEY_ALGORITHM="RSA";
/**
*签名算法
*/
publicstaticfinalStringSIGNATURE_ALGORITHM="MD5withRSA";
/**
*获取公钥的key
*/
privatestaticfinalStringPUBLIC_KEY="LocatorPublicKey";
/**
*获取私钥的key
*/
privatestaticfinalStringPRIVATE_KEY="LocatorPrivateKey";
/**
*RSA最大加密明文大小
*/
privatestaticfinalintMAX_ENCRYPT_BLOCK=117;
/**
*RSA最大解密密文大小
*/
privatestaticfinalintMAX_DECRYPT_BLOCK=128;
/**
*<p>
*生成密钥对(公钥和私钥)
*</p>
*
*@return
*@throwsException
*/
publicstaticMap<String,Object>genKeyPair()throwsException{
KeyPairGeneratorkeyPairGen=KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPairkeyPair=keyPairGen.generateKeyPair();
RSAPublicKeypublicKey=(RSAPublicKey)keyPair.getPublic();
RSAPrivateKeyprivateKey=(RSAPrivateKey)keyPair.getPrivate();
Map<String,Object>keyMap=newHashMap<String,Object>(2);
keyMap.put(PUBLIC_KEY,publicKey);
keyMap.put(PRIVATE_KEY,privateKey);
returnkeyMap;
}
/**
*<p>
*用私钥对信息生成数字签名
*</p>
*
*@paramdata已加密数据
*@paramprivateKey私钥(BASE64编码)
*
*@return
*@throwsException
*/
publicstaticStringsign(byte[]data,StringprivateKey)throwsException{
byte[]keyBytes=Base64Utils.decode(privateKey);
PKCS8EncodedKeySpecpkcs8KeySpec=newPKCS8EncodedKeySpec(keyBytes);
KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKeyprivateK=keyFactory.generatePrivate(pkcs8KeySpec);
Signaturesignature=Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(data);
returnBase64Utils.encode(signature.sign());
}
/**
*<p>
*校验数字签名
*</p>
*
*@paramdata已加密数据
*@parampublicKey公钥(BASE64编码)
*@paramsign数字签名
*
*@return
*@throwsException
*
*/
publicstaticbooleanverify(byte[]data,StringpublicKey,Stringsign)
throwsException{
byte[]keyBytes=Base64Utils.decode(publicKey);
X509EncodedKeySpeckeySpec=newX509EncodedKeySpec(keyBytes);
KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
PublicKeypublicK=keyFactory.generatePublic(keySpec);
Signaturesignature=Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
returnsignature.verify(Base64Utils.decode(sign));
}
/**
*<P>
*私钥解密
*</p>
*
*@paramencryptedData已加密数据
*@paramprivateKey私钥(BASE64编码)
*@return
*@throwsException
*/
publicstaticbyte[]decryptByPrivateKey(byte[]encryptedData,StringprivateKey)
throwsException{
byte[]keyBytes=Base64Utils.decode(privateKey);
PKCS8EncodedKeySpecpkcs8KeySpec=newPKCS8EncodedKeySpec(keyBytes);
KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
KeyprivateK=keyFactory.generatePrivate(pkcs8KeySpec);
Ciphercipher=Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE,privateK);
intinputLen=encryptedData.length;
ByteArrayOutputStreamout=newByteArrayOutputStream();
intoffSet=0;
byte[]cache;
inti=0;
//对数据分段解密
while(inputLen-offSet>0){
if(inputLen-offSet>MAX_DECRYPT_BLOCK){
cache=cipher.doFinal(encryptedData,offSet,MAX_DECRYPT_BLOCK);
}else{
cache=cipher.doFinal(encryptedData,offSet,inputLen-offSet);
}
out.write(cache,0,cache.length);
i++;
offSet=i*MAX_DECRYPT_BLOCK;
}
byte[]decryptedData=out.toByteArray();
out.close();
returndecryptedData;
}
/**
*<p>
*公钥解密
*</p>
*
*@paramencryptedData已加密数据
*@parampublicKey公钥(BASE64编码)
*@return
*@throwsException
*/
publicstaticbyte[]decryptByPublicKey(byte[]encryptedData,StringpublicKey)
throwsException{
byte[]keyBytes=Base64Utils.decode(publicKey);
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(keyBytes);
KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
KeypublicK=keyFactory.generatePublic(x509KeySpec);
Ciphercipher=Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE,publicK);
intinputLen=encryptedData.length;
ByteArrayOutputStreamout=newByteArrayOutputStream();
intoffSet=0;
byte[]cache;
inti=0;
//对数据分段解密
while(inputLen-offSet>0){
if(inputLen-offSet>MAX_DECRYPT_BLOCK){
cache=cipher.doFinal(encryptedData,offSet,MAX_DECRYPT_BLOCK);
}else{
cache=cipher.doFinal(encryptedData,offSet,inputLen-offSet);
}
out.write(cache,0,cache.length);
i++;
offSet=i*MAX_DECRYPT_BLOCK;
}
byte[]decryptedData=out.toByteArray();
out.close();
returndecryptedData;
}
/**
*<p>
*公钥加密
*</p>
*
*@paramdata源数据
*@parampublicKey公钥(BASE64编码)
*@return
*@throwsException
*/
publicstaticbyte[]encryptByPublicKey(byte[]data,StringpublicKey)
throwsException{
byte[]keyBytes=Base64Utils.decode(publicKey);
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(keyBytes);
KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
KeypublicK=keyFactory.generatePublic(x509KeySpec);
//对数据加密
Ciphercipher=Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE,publicK);
intinputLen=data.length;
ByteArrayOutputStreamout=newByteArrayOutputStream();
intoffSet=0;
byte[]cache;
inti=0;
//对数据分段加密
while(inputLen-offSet>0){
if(inputLen-offSet>MAX_ENCRYPT_BLOCK){
cache=cipher.doFinal(data,offSet,MAX_ENCRYPT_BLOCK);
}else{
cache=cipher.doFinal(data,offSet,inputLen-offSet);
}
out.write(cache,0,cache.length);
i++;
offSet=i*MAX_ENCRYPT_BLOCK;
}
byte[]encryptedData=out.toByteArray();
out.close();
returnencryptedData;
}
/**
*<p>
*私钥加密
*</p>
*
*@paramdata源数据
*@paramprivateKey私钥(BASE64编码)
*@return
*@throwsException
*/
publicstaticbyte[]encryptByPrivateKey(byte[]data,StringprivateKey)
throwsException{
byte[]keyBytes=Base64Utils.decode(privateKey);
PKCS8EncodedKeySpecpkcs8KeySpec=newPKCS8EncodedKeySpec(keyBytes);
KeyFactorykeyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
KeyprivateK=keyFactory.generatePrivate(pkcs8KeySpec);
Ciphercipher=Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE,privateK);
intinputLen=data.length;
ByteArrayOutputStreamout=newByteArrayOutputStream();
intoffSet=0;
byte[]cache;
inti=0;
//对数据分段加密
while(inputLen-offSet>0){
if(inputLen-offSet>MAX_ENCRYPT_BLOCK){
cache=cipher.doFinal(data,offSet,MAX_ENCRYPT_BLOCK);
}else{
cache=cipher.doFinal(data,offSet,inputLen-offSet);
}
out.write(cache,0,cache.length);
i++;
offSet=i*MAX_ENCRYPT_BLOCK;
}
byte[]encryptedData=out.toByteArray();
out.close();
returnencryptedData;
}
/**
*<p>
*获取私钥
*</p>
*
*@paramkeyMap密钥对
*@return
*@throwsException
*/
publicstaticStringgetPrivateKey(Map<String,Object>keyMap)
throwsException{
Keykey=(Key)keyMap.get(PRIVATE_KEY);
returnBase64Utils.encode(key.getEncoded());
}
/**
*<p>
*获取公钥
*</p>
*
*@paramkeyMap密钥对
*@return
*@throwsException
*/
publicstaticStringgetPublicKey(Map<String,Object>keyMap)
throwsException{
Keykey=(Key)keyMap.get(PUBLIC_KEY);
returnBase64Utils.encode(key.getEncoded());
}
}
以上这篇Android获取签名公钥和公钥私钥加解密的方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
