`

java aes加密

    博客分类:
  • java
阅读更多
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public class AESTest {

public static void main(String args[])
{
try
{
if(args[0].equals("-genkey"))
{
KeyGenerator keygen=KeyGenerator.getInstance("AES");
SecureRandom random=new SecureRandom();
keygen.init(random);
SecretKey key=keygen.generateKey();
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(args[1]));
out.writeObject(key);
out.close();
}else
{
int mode;
if(args[0].equals("-encrypt"))
mode=Cipher.ENCRYPT_MODE;
else
mode=Cipher.DECRYPT_MODE;

ObjectInputStream keyIn=new ObjectInputStream(new FileInputStream(args[3]));
Key key=(Key) keyIn.readObject();
keyIn.close();

InputStream in=new FileInputStream(args[1]);
OutputStream out=new FileOutputStream(args[2]);
Cipher cipher=Cipher.getInstance("AES");
cipher.init(mode, key);
crypt(in,out,cipher);
in.close();
out.close();

}

}catch(IOException e)
{
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void crypt(InputStream in,OutputStream out,Cipher cipher)throws IOException,GeneralSecurityException
{
int blockSize=cipher.getBlockSize();
int outputSize=cipher.getOutputSize(blockSize);
byte[] inBytes=new byte[blockSize];
byte[] outBytes=new byte[outputSize];

int inLength=0;
boolean more=true;
while(more)
{
inLength=in.read();
if(inLength==blockSize)
{
int outLength=cipher.update(inBytes,0,blockSize,outBytes);
out.write(outBytes,0,outLength);
}else
{
more=false;
}
if(inLength>0)
{
outBytes=cipher.doFinal(inBytes,0,inLength);
}else
{
outBytes=cipher.doFinal();
}
out.write(outBytes);
}
}
}


软件开发者证书
1)javac *.java
生成密钥
2)java AESTest -genkey secret.key
加密
3)java AESTest -encrypt plaintextFile encryptedFile secret.key
解密
4)java AESTest -decrypt encryptedFile decryptedFile secret.key
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics