JAVA 下的 pgp加密解密示例


文中包含PGP的加密、解密,其中用到的jar包如下



加密:


public class PgpEncry {


/**
* 加密入口  .txt---->.pgp
* @param encryFile
* @param publicasc
* @return
* @throws Exception 
*/
public static String  Encry(String encryFile, String publicasc ) throws Exception 
{
encryFile = encryFile.replace('\\', '/');
String encryedFile = PgpTool.DestFileName(encryFile);

Encry(encryFile,encryedFile,publicasc);

return encryedFile;
}


/**
* .txt---->.txt.pgp
* @param encryFile
* @param publicasc
* @return
* @throws Exception
*/
public static String  Encry2(String encryFile, String publicasc ) throws Exception 
{
encryFile = encryFile.replace('\\', '/');
String encryedFile = PgpTool.DestFileName2(encryFile);

Encry(encryFile,encryedFile,publicasc);

return encryedFile;
}

/**
* 加密主程序
* @param encryFile
* @param encryedFile
* @param publicasc
* @throws Exception 
*/
private static void Encry(String encryFile, String encryedFile,
String publicasc) throws Exception  {
java.security.Security
.addProvider(new cryptix.jce.provider.CryptixCrypto());
java.security.Security
.addProvider(new cryptix.openpgp.provider.CryptixOpenPGP());

KeyBundle publicBob = null;
FileInputStream inEncry = null;

try 
{
Collection msgs;
KeyBundleMessage kbm;

MessageFactory mf = MessageFactory.getInstance("OpenPGP");
inEncry = new FileInputStream(publicasc);

msgs = mf.generateMessages(inEncry);
kbm = (KeyBundleMessage) msgs.iterator().next();

publicBob = kbm.getKeyBundle();

inEncry.close();
inEncry = null;


catch (Exception me) 
{
System.err.println("读密钥出错.");
me.printStackTrace();
throw me;

} finally {
try 
{
if (inEncry != null)
inEncry.close();
inEncry = null;


catch (Exception e) 
{
e.printStackTrace();
}
}


FileOutputStream fileos = null;
LiteralMessageOutputStream litmos = null;
EncryptedMessageOutputStream encmos = null;

FileInputStream  inputEncryStream = null;
try
{
inputEncryStream =  new FileInputStream(encryFile);
fileos = new FileOutputStream(encryedFile);

litmos = LiteralMessageOutputStream.getInstance("OpenPGP");
encmos = EncryptedMessageOutputStream.getInstance("OpenPGP");


SecureRandom sr = new SecureRandom();
litmos.init(encmos, sr); 
encmos.init(fileos, sr); 
encmos.addRecipient(publicBob);



byte[] buf = new byte[4096];
int len = inputEncryStream.read(buf);

while (len > 0) 
{
litmos.write(buf, 0, len);
len = inputEncryStream.read(buf);
}

litmos.close();
fileos.close();
inputEncryStream.close();

encmos = null;
litmos = null;
inputEncryStream = null;
fileos = null;
sr = null;


catch (Exception ioe) 
{
System.err.println("IO error.");
ioe.printStackTrace();
throw ioe;
}
finally 
{
try {
if (inputEncryStream != null)
inputEncryStream.close();
inputEncryStream = null;

if (fileos != null)
fileos.close();
fileos = null;

if (litmos != null)
litmos.close();
litmos = null;

} catch (Exception e) {
e.printStackTrace();
}
}
}






public static void main(String[] args) throws Exception {    
                         
PgpEncryUtil.Encry("需要加密的文件“, "加密后的文件" ,"公钥");


}


}




解密:



public class PgpDecry implements DecryptionKeyCallback,VerificationKeyCallback {


private PGPKeyBundle publicAlice = null;
private PGPKeyBundle secretBob = null;
private String Passphrase;



public String getPassphrase() 
{
return Passphrase;
}



public void setPassphrase(String passphrase) 
{
Passphrase = passphrase;
}




public void DecryUtil(String decryFile, String decryedFile, String secretasc) throws Exception 
{
java.security.Security.addProvider(new cryptix.jce.provider.CryptixCrypto());

java.security.Security.addProvider(new cryptix.openpgp.provider.CryptixOpenPGP());


FileInputStream inAsc = null;;

try {
Collection msgs;
KeyBundleMessage kbm;

MessageFactory mf = MessageFactory.getInstance("OpenPGP");

inAsc = new FileInputStream(secretasc);
msgs = mf.generateMessages(inAsc);

kbm = (KeyBundleMessage) msgs.iterator().next();
secretBob = (PGPKeyBundle) kbm.getKeyBundle();

inAsc.close();
inAsc = null;


catch (Exception me)
{
System.err.println("Reading keybundle failed.");
me.printStackTrace();
throw me;

}
finally
{
try {
if (inAsc != null)
inAsc.close();
inAsc = null;


catch (Exception e)
{
e.printStackTrace();
}

}




FileInputStream inDecry = null;
FileOutputStream outDecryed = null;

try 
{
inDecry = new FileInputStream(decryFile);
outDecryed = new FileOutputStream(decryedFile);

DecodedMessageInputStream decodedInputStream 

                                           =  DecodedMessageInputStream.getInstance("OpenPGP");
decodedInputStream.init(inDecry, this, this);


System.out.println("Decoding message...");

byte[] buf = new byte[4096];
int len = decodedInputStream.read(buf);

while (len > 0) 
{
outDecryed.write(buf, 0, len);
len = decodedInputStream.read(buf);
}



System.out.println("Decoding done.");


catch (Exception ioe)
{
System.err.println("IO error.");
ioe.printStackTrace();
throw ioe;

} finally
{
try 
{
if (inDecry != null)
inDecry.close();
inDecry = null;

if (outDecryed != null)
outDecryed.close();
outDecryed = null;

}
catch (Exception e) 
{
e.printStackTrace();

}
}
}


public VerificationKeyReturnValue getVerificationKey(
VerificationKeyRequest request) {
try {

if (request.getRetryCount() >= 1)
return new VerificationKeyReturnValue(
VerificationKeyReturnValue.IGNORE);


KeyID[] hintIDs = request.getKeyIDHints();


KeyIDFactory kidf = KeyIDFactory.getInstance("OpenPGP");

KeyID aliceID = kidf.generateKeyID((PublicKey) publicAlice
.getPublicKeys().next());


for (int i = 0; i < hintIDs.length; i++)
if (hintIDs[i].match(aliceID))
return new VerificationKeyReturnValue(publicAlice);


return new VerificationKeyReturnValue(
VerificationKeyReturnValue.IGNORE);



catch (NoSuchAlgorithmException nsae)
{
System.err.println("Cannot find OpenPGP implementation."
+ " This usually means that the Cryptix " +
"OpenPGP provider is not "
+ "installed correctly.");

nsae.printStackTrace();
throw new RuntimeException();

catch (InvalidKeyException ike)
{
System.err.println("Invalid key.");
ike.printStackTrace();
throw new RuntimeException();
}
}


public DecryptionKeyReturnValue getDecryptionKey(
DecryptionKeyRequest request) {
try 
{
if (request.getRetryCount() >= 1)
return new DecryptionKeyReturnValue(
DecryptionKeyReturnValue.FAIL);

KeyID[] hintIDs = request.getKeyIDHints();
KeyIDFactory kidf = KeyIDFactory.getInstance("OpenPGP");

KeyID bobID = kidf.generateKeyID((PublicKey) 
   secretBob.getPublicKeys().next());


for (int i = 0; i < hintIDs.length; i++)
{
if (hintIDs[i].match(bobID))
return new DecryptionKeyReturnValue(secretBob,
                           Passphrase.toCharArray());

Iterator it = secretBob.getPublicSubKeys();

while (it.hasNext()) 
{
KeyID bobSubID = kidf.generateKeyID((PublicKey) it.next());

if (hintIDs[i].match(bobSubID))
return new DecryptionKeyReturnValue(secretBob,
Passphrase.toCharArray());
}
}


return new DecryptionKeyReturnValue(DecryptionKeyReturnValue.FAIL);


}
catch (Exception ike) 
{
System.err.println("Invalid key.");
ike.printStackTrace();
throw new RuntimeException();
}
}


public static void main(String[] args) {
try{


/**
* 定义解密类
*/
PgpDecryUtil decryU = new PgpDecryUtil();
/**
* 设置密码
*/
decryU.setPassphrase("BOCHQ_FORMS_P3WD");
/**
* 需要解密的文件名 、解密后的文件名、 私钥 、
*/
decryU.DecryUtil("需要解密的文件",  "解密后的文件", "私钥");



}
catch(Exception e)
{
e.printStackTrace();
}
}


}


猜你喜欢

转载自blog.csdn.net/mashengjun1989/article/details/75043159