您的位置:首页 > 编程语言 > Java开发

转载:java加密方法

2008-04-29 09:04 239 查看
原文:http://www.blogjava.net/pdw2009/archive/2008/04/15/193046.html

java加密相关技术
前段时间需要用到这方面的技术,写了几个例子,不加文字说明,只贴代码

package demo.encrypt;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
*
* 摘要加密。检验信息完整性 目前广泛使用的算法有MD4、MD5、SHA-1
* @author peidw 2008-03-02
*
*/
public class MessageDigestExample {
/**
* 信息摘要完整性加密
*
*/

/**
* 单一摘要算法,不使用密码
* @param args
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
String str="www.17lotto.com"; //要加密的字符串
byte[] bstr=str.getBytes("utf-8");
MessageDigest messageDigest=MessageDigest.getInstance("SHA-1"); //获取算法
System.out.println("/n"+messageDigest.getProvider().getInfo());
System.out.println("加密前:/n "+new String(bstr));

messageDigest.update(bstr);
System.out.println("/n加密后结果:");
System.out.println(new String(messageDigest.digest(),"utf-8"));

}

}

package demo.encrypt;

import java.io.*;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

/**
* 私钥加密,也称对称性密码,加/解密双方共享同一密钥
*
* @author peidw
*
*/

public class PrivateExample {
/**
* 加必解密例子
* @throws Exception
*/
public void deendemo()throws Exception{
String str="www.17lotto.com"; //要加密的字符串
byte[] bstr=str.getBytes("utf-8");
//产生密钥
KeyGenerator keyGen=KeyGenerator.getInstance("AES");
keyGen.init(128);

Key key=keyGen.generateKey();
//密钥保存
File fkey=new File("f://key.obj");
OutputStream os=new FileOutputStream(fkey);
os.write(key.getEncoded());
os.flush();
os.close();
//密钥保存问题

//获得一个私鈅加密类Cipher,ECB是加密方式,PKCS5Padding是填充方法
Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
System.out.println("/n"+cipher.getProvider().getInfo());

//使用私鈅加密
cipher.init(Cipher.ENCRYPT_MODE,key);
byte[] cipherText=cipher.doFinal(bstr);
//密文保存
File cryptograph=new File("f://cryptograph.obj");
OutputStream cos=new FileOutputStream(cryptograph);
cos.write(cipherText);
cos.flush();
cos.close();

System.out.println("Finish encryption:");
System.out.println(new String(cipherText,"utf-8"));

System.out.println("/nStart decryption:");
cipher.init(Cipher.DECRYPT_MODE,key);
byte[] newPlainText=cipher.doFinal(cipherText);
System.out.println("Finish decryption:");

System.out.println(new String(newPlainText,"utf-8"));

}

/**
* 从文件加载密钥和密文进行解密例子(新jdk不懂怎么加载)
* @throws Exception
*/
public void decryptionFromFile()throws Exception{
KeyGenerator keyGen=KeyGenerator.getInstance("AES");

}

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
PrivateExample pe=new PrivateExample();
pe.deendemo();
}

}

package demo.encrypt;

import java.io.*;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
* 非对称性加密,也叫公钥加密 产开两个密钥(私钥,公钥)私钥加密只有公钥才能解样,同时公钥加密只有私钥能解开.
* 目前JDK5提供的RSA算法
* @author peidw
*
*/
public class PublicExample {
/**
* 加密解密例子
* @throws Exception
*/
public void deenDemo()throws Exception{
String str="www.17lotto.com";
byte bstr[]=str.getBytes("utf-8");
//构成一个RSA密钥
System.out.println("/nStart generating RSA key");
KeyPairGenerator keyGen=KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key=keyGen.generateKeyPair();
//保存公/私密钥
File pubfile=new File("f://public.dat");
File prifile=new File("f://private.dat");
OutputStream pubos=new FileOutputStream(pubfile);
OutputStream prios=new FileOutputStream(prifile);
pubos.write(key.getPublic().getEncoded());
prios.write(key.getPrivate().getEncoded());
pubos.flush();
prios.flush();
pubos.close();
prios.close();

System.out.println("Finish generating RSA key");
//获得一个RSA的Cipher类,使用公鈅加密
Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
System.out.println("/n"+cipher.getProvider().getInfo());

System.out.println("/nStart encryption");
cipher.init(Cipher.ENCRYPT_MODE,key.getPublic());
byte[] cipherText=cipher.doFinal(bstr);

File pub_cryptograph=new File("f://pub_cryptograph.dat");
OutputStream os=new FileOutputStream(pub_cryptograph);
os.write(cipherText);
os.flush();
os.close();

System.out.println("Finish encryption:");
System.out.println(new String(cipherText,"UTF8"));
//使用私鈅解密
System.out.println("/nStart decryption");
cipher.init(Cipher.DECRYPT_MODE,key.getPrivate());
byte[] newPlainText=cipher.doFinal(cipherText);
System.out.println("Finish decryption:");
System.out.println(new String(newPlainText,"UTF8"));

}
/**
* 加裁私钥,解密公钥加密的文的文件
* @throws Exception
*/
public void fromfielEnDeDemo()throws Exception{
File prifile=new File("f://private.dat");
FileInputStream fsprivateKey = new FileInputStream(prifile);
BufferedInputStream bfsprivateKey = new BufferedInputStream(fsprivateKey);
byte[] byteprivateKey = new byte[bfsprivateKey.available()];
bfsprivateKey.read(byteprivateKey);
bfsprivateKey.close();
//X509EncodedKeySpec priKeySpec = new X509EncodedKeySpec(byteprivateKey); 公钥加载法
PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(byteprivateKey); //私钥加载

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyFactory.generatePrivate(priKeySpec);
System.out.println(priKey.getFormat());

Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE,priKey);

File pubcryptographfile=new File("f://pub_cryptograph.dat");
FileInputStream pubcis = new FileInputStream(pubcryptographfile);
byte cstr[]=new byte[pubcis.available()];
pubcis.read(cstr);
pubcis.close();

byte[] newPlainText=cipher.doFinal(cstr);
System.out.println("Finish decryption:");
System.out.println(new String(newPlainText,"UTF8"));
}

/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
PublicExample pe=new PublicExample();
pe.fromfielEnDeDemo();
}

}

package demo.encrypt;

import java.security.*;

/**
* <p>数字签名</p>
* <pre>
* 使用RSA私钥对信息摘要签名,然后用公钥进行解密
* </pre>
* @author peidw
*
*/
public class DigitalSignature2Example {

public void test () throws Exception {
String str="www.17lotto.com";
byte[] bstr=str.getBytes("utf-8");
//形成RSA公私钥对
System.out.println("/nStart generating RSA key");
KeyPairGenerator keyGen=KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key=keyGen.generateKeyPair();

Signature sig=Signature.getInstance("SHA1WithRSA");
sig.initSign(key.getPrivate());
sig.update(bstr);
byte[] signature=sig.sign();
System.out.println(sig.getProvider().getInfo());
System.out.println("/nSignature:");
System.out.println(new String(signature,"utf-8"));

//使用公鈅验证
System.out.println("/nStart signature verification");
sig.initVerify(key.getPublic());
sig.update(bstr);
try{
if(sig.verify(signature)){
System.out.println("Signature verified");
}else System.out.println("Signature failed");
}catch(SignatureException e){
System.out.println("Signature failed");
}

}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: