Android编程加密算法小结(AES、Base64、RAS加密算法)
本文实例总结了Android编程加密算法。分享给大家供大家参考,具体如下:
android常用加密算法之Base64加密算法:
packagecom.long;
/**
*Copyright(C)2010TheAndroidOpenSourceProject
*
*LicensedundertheApacheLicense,Version2.0(the"License");
*youmaynotusethisfileexceptincompliancewiththeLicense.
*YoumayobtainacopyoftheLicenseat
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
*distributedundertheLicenseisdistributedonan"ASIS"BASIS,
*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
*SeetheLicenseforthespecificlanguagegoverningpermissionsand
*limitationsundertheLicense.
*/
importjava.io.ByteArrayOutputStream;
importjava.io.IOException;
importjava.io.OutputStream;
/*
*@authorlong
*
*/
publicclassBase64{
privatestaticfinalchar[]legalChars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.toCharArray();
publicstaticStringencode(byte[]data){
intstart=0;
intlen=data.length;
StringBufferbuf=newStringBuffer(data.length*3/2);
intend=len-3;
inti=start;
intn=0;
while(i<=end){
intd=((((int)data[i])&0x0ff)<<16)
|((((int)data[i+1])&0x0ff)<<8)
|(((int)data[i+2])&0x0ff);
buf.append(legalChars[(d>>18)&63]);
buf.append(legalChars[(d>>12)&63]);
buf.append(legalChars[(d>>6)&63]);
buf.append(legalChars[d&63]);
i+=3;
if(n++>=14){
n=0;
buf.append("");
}
}
if(i==start+len-2){
intd=((((int)data[i])&0x0ff)<<16)
|((((int)data[i+1])&255)<<8);
buf.append(legalChars[(d>>18)&63]);
buf.append(legalChars[(d>>12)&63]);
buf.append(legalChars[(d>>6)&63]);
buf.append("=");
}elseif(i==start+len-1){
intd=(((int)data[i])&0x0ff)<<16;
buf.append(legalChars[(d>>18)&63]);
buf.append(legalChars[(d>>12)&63]);
buf.append("==");
}
returnbuf.toString();
}
privatestaticintdecode(charc){
if(c>='A'&&c<='Z')
return((int)c)-65;
elseif(c>='a'&&c<='z')
return((int)c)-97+26;
elseif(c>='0'&&c<='9')
return((int)c)-48+26+26;
else
switch(c){
case'+':
return62;
case'/':
return63;
case'=':
return0;
default:
thrownewRuntimeException("unexpectedcode:"+c);
}
}
publicstaticbyte[]decode(Strings){
ByteArrayOutputStreambos=newByteArrayOutputStream();
try{
decode(s,bos);
}catch(IOExceptione){
thrownewRuntimeException();
}
byte[]decodedBytes=bos.toByteArray();
try{
bos.close();
bos=null;
}catch(IOExceptionex){
System.err.println("ErrorwhiledecodingBASE64:"+ex.toString());
}
returndecodedBytes;
}
privatestaticvoiddecode(Strings,OutputStreamos)throwsIOException{
inti=0;
intlen=s.length();
while(true){
while(i<len&&s.charAt(i)<='')
i++;
if(i==len)
break;
inttri=(decode(s.charAt(i))<<18)
+(decode(s.charAt(i+1))<<12)
+(decode(s.charAt(i+2))<<6)
+(decode(s.charAt(i+3)));
os.write((tri>>16)&255);
if(s.charAt(i+2)=='=')
break;
os.write((tri>>8)&255);
if(s.charAt(i+3)=='=')
break;
os.write(tri&255);
i+=4;
}
}
}
android常用加密算法之AES加密算法:
packagecom.long;
importjava.security.SecureRandom;
importjavax.crypto.Cipher;
importjavax.crypto.KeyGenerator;
importjavax.crypto.SecretKey;
importjavax.crypto.spec.SecretKeySpec;
/**
*AES加密解密算法
*
*@authorlong
*
*/
publicclassEncryption{
privatefinalstaticStringHEX="0123456789ABCDEF";
publicstaticStringencrypt(Stringseed,Stringcleartext)
throwsException{
byte[]rawKey=getRawKey(seed.getBytes());
byte[]result=encrypt(rawKey,cleartext.getBytes());
returntoHex(result);
}
publicstaticStringdecrypt(Stringseed,Stringencrypted)
throwsException{
byte[]rawKey=getRawKey(seed.getBytes());
byte[]enc=toByte(encrypted);
byte[]result=decrypt(rawKey,enc);
returnnewString(result);
}
privatestaticbyte[]getRawKey(byte[]seed)throwsException{
KeyGeneratorkgen=KeyGenerator.getInstance("AES");
SecureRandomsr=SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128,sr);//192and256bitsmaynotbeavailable
SecretKeyskey=kgen.generateKey();
byte[]raw=skey.getEncoded();
returnraw;
}
privatestaticbyte[]encrypt(byte[]raw,byte[]clear)throwsException{
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");
Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
byte[]encrypted=cipher.doFinal(clear);
returnencrypted;
}
privatestaticbyte[]decrypt(byte[]raw,byte[]encrypted)
throwsException{
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");
Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE,skeySpec);
byte[]decrypted=cipher.doFinal(encrypted);
returndecrypted;
}
publicstaticStringtoHex(Stringtxt){
returntoHex(txt.getBytes());
}
publicstaticStringfromHex(Stringhex){
returnnewString(toByte(hex));
}
publicstaticbyte[]toByte(StringhexString){
intlen=hexString.length()/2;
byte[]result=newbyte[len];
for(inti=0;i<len;i++)
result[i]=Integer.valueOf(hexString.substring(2*i,2*i+2),
16).byteValue();
returnresult;
}
publicstaticStringtoHex(byte[]buf){
if(buf==null)
return"";
StringBufferresult=newStringBuffer(2*buf.length);
for(inti=0;i<buf.length;i++){
appendHex(result,buf[i]);
}
returnresult.toString();
}
privatestaticvoidappendHex(StringBuffersb,byteb){
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
Android常用加密算法之RAS加密算法:
importjava.security.Key;
importjava.security.KeyFactory;
importjava.security.KeyPair;
importjava.security.KeyPairGenerator;
importjava.security.PrivateKey;
importjava.security.PublicKey;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjava.security.spec.PKCS8EncodedKeySpec;
importjava.security.spec.X509EncodedKeySpec;
importjavax.crypto.Cipher;
importsun.misc.BASE64Decoder;
importsun.misc.BASE64Encoder;
publicclassRSAHelper{
publicstaticPublicKeygetPublicKey(Stringkey)throwsException{
byte[]keyBytes;
keyBytes=(newBASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpeckeySpec=newX509EncodedKeySpec(keyBytes);
KeyFactorykeyFactory=KeyFactory.getInstance("RSA");
PublicKeypublicKey=keyFactory.generatePublic(keySpec);
returnpublicKey;
}
publicstaticPrivateKeygetPrivateKey(Stringkey)throwsException{
byte[]keyBytes;
keyBytes=(newBASE64Decoder()).decodeBuffer(key);
PKCS8EncodedKeySpeckeySpec=newPKCS8EncodedKeySpec(keyBytes);
KeyFactorykeyFactory=KeyFactory.getInstance("RSA");
PrivateKeyprivateKey=keyFactory.generatePrivate(keySpec);
returnprivateKey;
}
publicstaticStringgetKeyString(Keykey)throwsException{
byte[]keyBytes=key.getEncoded();
Strings=(newBASE64Encoder()).encode(keyBytes);
returns;
}
publicstaticvoidmain(String[]args)throwsException{
KeyPairGeneratorkeyPairGen=KeyPairGenerator.getInstance("RSA");
//密钥位数
keyPairGen.initialize(1024);
//密钥对
KeyPairkeyPair=keyPairGen.generateKeyPair();
//公钥
PublicKeypublicKey=(RSAPublicKey)keyPair.getPublic();
//私钥
PrivateKeyprivateKey=(RSAPrivateKey)keyPair.getPrivate();
StringpublicKeyString=getKeyString(publicKey);
System.out.println("public:\n"+publicKeyString);
StringprivateKeyString=getKeyString(privateKey);
System.out.println("private:\n"+privateKeyString);
//加解密类
Ciphercipher=Cipher.getInstance("RSA");//Cipher.getInstance("RSA/ECB/PKCS1Padding");
//明文
byte[]plainText="我们都很好!邮件:@sina.com".getBytes();
//加密
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
byte[]enBytes=cipher.doFinal(plainText);
//通过密钥字符串得到密钥
publicKey=getPublicKey(publicKeyString);
privateKey=getPrivateKey(privateKeyString);
//解密
cipher.init(Cipher.DECRYPT_MODE,privateKey);
byte[]deBytes=cipher.doFinal(enBytes);
publicKeyString=getKeyString(publicKey);
System.out.println("public:\n"+publicKeyString);
privateKeyString=getKeyString(privateKey);
System.out.println("private:\n"+privateKeyString);
Strings=newString(deBytes);
System.out.println(s);
}
}
希望本文所述对大家Android程序设计有所帮助。