当前位置:首页 » 密码管理 » javarsa加密文件

javarsa加密文件

发布时间: 2023-05-15 04:21:07

java里面RSA加密算法的使用

RSA的Java实现不能一次加密很大的字符,自己处理了一下,见下面的代码。Base64编码类用的是一个Public domain Base64 for java http://iharder.sourceforge.net/current/java/base64/其他的保存公钥到文件等简单的实现,就不详细说了,看代码吧。==============================================import java.security.*;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.HashMap;import java.util.Map;import javax.crypto.*;import java.io.*;public class Encryptor {private static final String KEY_FILENAME = "c:\\mykey.dat";private static final String OTHERS_KEY_FILENAME = "c:\\Otherskey.dat";// private static final int KEY_SIZE = 1024;// private static final int BLOCK_SIZE = 117;// private static final int OUTPUT_BLOCK_SIZE = 128;private static final int KEY_SIZE = 2048; //RSA key 是多少位的private static final int BLOCK_SIZE = 245; //一次RSA加密操作所允许的最大长度//这个值与 KEY_SIZE 已经padding方法有关。因为 1024的key的输出是128,2048key输出是256字节//可能11个字节用于保存padding信息了,所以最多可用的就只有245字节了。private static final int OUTPUT_BLOCK_SIZE = 256;private SecureRandom secrand;private Cipher rsaCipher;private KeyPair keys;private Map<String, Key> allUserKeys;public Encryptor() throws Exception {try {allUserKeys = new HashMap<String, Key>();secrand = new SecureRandom();//SunJCE Provider 中只支持ECB mode,试了一下只有PKCS1PADDING可以直接还原原始数据,//NOPadding导致解压出来的都是blocksize长度的数据,还要自己处理//参见 http://java.sun.com/javase/6/docs/technotes/guides/security/SunProviders.html#SunJCEProvider////另外根据 Open-JDK-6.b17-src( http://www.docjar.com/html/api/com/sun/crypto/provider/RSACipher.java.html)// 中代码的注释,使用RSA来加密大量数据不是一种标准的用法。所以现有实现一次doFinal调用之进行一个RSA操作,//如果用doFinal来加密超过的一个操作所允许的长度数据将抛出异常。//根据keysize的长度,典型的1024个长度的key和PKCS1PADDING一起使用时//一次doFinal调用只能加密117个byte的数据。(NOPadding 和1024 keysize时128个字节长度)//(2048长度的key和PKCS1PADDING 最多允许245字节一次)//想用来加密大量数据的只能自己用其他办法实现了。可能RSA加密速度比较慢吧,要用AES才行rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();throw e;}ObjectInputStream in;try {in = new ObjectInputStream(new FileInputStream(KEY_FILENAME));} catch (FileNotFoundException e) {if (false == GenerateKeys()){throw e;}LoadKeys();return;}keys = (KeyPair) in.readObject();in.close();LoadKeys();}/** 生成自己的公钥和私钥*/private Boolean GenerateKeys() {try {KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");// secrand = new SecureRandom();// sedSeed之后会造成 生成的密钥都是一样的// secrand.setSeed("chatencrptor".getBytes()); // 初始化随机产生器//key长度至少512长度,不过好像说现在用2048才算比较安全的了keygen.initialize(KEY_SIZE, secrand); // 初始化密钥生成器keys = keygen.generateKeyPair(); // 生成密钥组AddKey("me", EncodeKey(keys.getPublic()));} catch (NoSuchAlgorithmException e) {e.printStackTrace();return false;}ObjectOutputStream out;try {out = new ObjectOutputStream(new FileOutputStream(KEY_FILENAME));} catch (IOException e) {e.printStackTrace();return false;}try {out.writeObject(keys);} catch (IOException e) {e.printStackTrace();return false;} finally {try {out.close();} catch (IOException e) {e.printStackTrace();return false;}}return true;}public String EncryptMessage(String toUser, String Message) throws IOException {Key pubkey = allUserKeys.get(toUser);if ( pubkey == null ){throw new IOException("NoKeyForThisUser") ;}try {//PublicKey pubkey = keys.getPublic();rsaCipher.init(Cipher.ENCRYPT_MODE, pubkey, secrand);//System.out.println(rsaCipher.getBlockSize()); 返回0,非block 加密算法来的?//System.out.println(Message.getBytes("utf-8").length);//byte[] encryptedData = rsaCipher.doFinal(Message.getBytes("utf-8"));byte[] data = Message.getBytes("utf-8");int blocks = data.length / BLOCK_SIZE ;int lastBlockSize = data.length % BLOCK_SIZE ;byte [] encryptedData = new byte[ (lastBlockSize == 0 ? blocks : blocks + 1)* OUTPUT_BLOCK_SIZE];for (int i=0; i < blocks; i++){//int thisBlockSize = ( i + 1 ) * BLOCK_SIZE > data.length ? data.length - i * BLOCK_SIZE : BLOCK_SIZE ;rsaCipher.doFinal(data,i * BLOCK_SIZE, BLOCK_SIZE, encryptedData ,i * OUTPUT_BLOCK_SIZE);}if (lastBlockSize != 0 ){rsaCipher.doFinal(data, blocks * BLOCK_SIZE, lastBlockSize,encryptedData ,blocks * OUTPUT_BLOCK_SIZE);}//System.out.println(encrypted.length); 如果要机密的数据不足128/256字节,加密后补全成为变为256长度的。//数量比较小时,Base64.GZIP产生的长度更长,没什么优势//System.out.println(Base64.encodeBytes(encrypted,Base64.GZIP).length());//System.out.println(Base64.encodeBytes(encrypted).length());//System.out.println (rsaCipher.getOutputSize(30));//这个getOutputSize 只对 输入小于最大的block时才能得到正确的结果。其实就是补全 数据为128/256 字节return Base64.encodeBytes(encryptedData);} catch (InvalidKeyException e) {e.printStackTrace();throw new IOException("InvalidKey") ;}catch (ShortBufferException e) {e.printStackTrace();throw new IOException("ShortBuffer") ;}catch (UnsupportedEncodingException e) {e.printStackTrace();throw new IOException("UnsupportedEncoding") ;} catch (IllegalBlockSizeException e) {e.printStackTrace();throw new IOException("IllegalBlockSize") ;} catch (BadPaddingException e) {e.printStackTrace();throw new IOException("BadPadding") ;}finally {//catch 中 return 或者throw之前都会先调用一下这里}}public String DecryptMessage(String Message) throws IOException {byte[] decoded = Base64.decode(Message);PrivateKey prikey = keys.getPrivate();try {rsaCipher.init(Cipher.DECRYPT_MODE, prikey, secrand);int blocks = decoded.length / OUTPUT_BLOCK_SIZE;ByteArrayOutputStream decodedStream = new ByteArrayOutputStream(decoded.length);for (int i =0 ;i < blocks ; i ++ ){decodedStream.write (rsaCipher.doFinal(decoded,i * OUTPUT_BLOCK_SIZE, OUTPUT_BLOCK_SIZE));}return new String(decodedStream.toByteArray(), "UTF-8");} catch (InvalidKeyException e) {e.printStackTrace();throw new IOException("InvalidKey");} catch (UnsupportedEncodingException e) {e.printStackTrace();throw new IOException("UnsupportedEncoding");} catch (IllegalBlockSizeException e) {e.printStackTrace();throw new IOException("IllegalBlockSize");} catch (BadPaddingException e) {e.printStackTrace();throw new IOException("BadPadding");} finally {// catch 中 return 或者throw之前都会先调用一下这里。}}public boolean AddKey(String user, String key) {PublicKey publickey;try {publickey = DecodePublicKey(key);} catch (Exception e) {return false;}allUserKeys.put(user, publickey);SaveKeys();return true;}private boolean LoadKeys() {BufferedReader input;try {input = new BufferedReader(new InputStreamReader(new FileInputStream(OTHERS_KEY_FILENAME)));} catch (FileNotFoundException e1) {// e1.printStackTrace();return false;}

Ⅱ 基于java的rsa对文件加密。java写的后台

一定要把逻辑写进jsp吗?如果是,可以把你的java类import进jsp,然后直接在jsp的<%%>里new一个调用就行。比如<%MyClass myClass = new MyClass(); String encData = myClass.rsaEncrypt(myData);%>

Ⅲ Java中RSA的方式如何实现非对称加密的示例

代码如下,需要依赖一个jar包commons-codec-1.9.jar,用于Base64转换,请自行下载。

importorg.apache.commons.codec.binary.Base64;

importjavax.crypto.BadPaddingException;
importjavax.crypto.Cipher;
importjavax.crypto.IllegalBlockSizeException;
importjava.io.ByteArrayOutputStream;
importjava.io.UnsupportedEncodingException;
importjava.security.*;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjava.security.spec.PKCS8EncodedKeySpec;
importjava.security.spec.X509EncodedKeySpec;

publicclassRSAUtils{

//加密方式
="RSA";
//签名算法
_ALGORITHM="SHA1WithRSA";
//创建密钥对初始长度
privatestaticfinalintKEY_SIZE=512;
//字符编码格式
="UTF-8";
//RSA最大加密明文大小
privatestaticfinalintMAX_ENCRYPT_BLOCK=117;
//RSA最大解密密文大小
privatestaticfinalintMAX_DECRYPT_BLOCK=128;

privateKeyFactorykeyFactory;

publicRSAUtils(){
keyFactory=KeyFactory.getInstance(ALGORITHM);
}

/**
*私钥加密
*
*@paramcontent待加密字符串
*@paramprivateKey私钥
*@return加密后字符串(BASE64编码)
*/
(Stringcontent,StringprivateKey)throwsException{
Stringresult;

try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeypKey=keyFactory.generatePrivate(pkcs8KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,pKey);

byte[]data=content.getBytes(CHARSET);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();

result=Base64.encodeBase64String(resultBytes);
}catch(Exceptione){
thrownewException(e);
}

returnresult;
}

/**
*公钥解密
*
*@paramcontent已加密字符串(BASE64加密)
*@parampublicKey公钥
*@return
*/
(Stringcontent,StringpublicKey)throwsException{
Stringresult="";

try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypKey=keyFactory.generatePublic(x509KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,pKey);

byte[]data=Base64.decodeBase64(content);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();

result=newString(resultBytes);
}catch(Exceptione){
thrownewException(e);
}

returnresult;
}

/**
*公钥加密
*
*@paramcontent待加密字符串
*@parampublicKey公钥
*@return加密后字符串(BASE64编码)
*/
(Stringcontent,StringpublicKey)throwsException{
Stringresult="";

try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypKey=keyFactory.generatePublic(x509KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,pKey);

byte[]data=content.getBytes(CHARSET);
write2Stream(cipher,
data,out);
byte[]resultBytes=out.toByteArray();
result=Base64.encodeBase64String(resultBytes);
}catch(Exceptione){
thrownewException(e);
}

returnresult;
}

/**
*私钥解密
*
*@paramcontent已加密字符串
*@paramprivateKey私钥
*@return解密后字符串
*/
(Stringcontent,StringprivateKey)throwsException{
Stringresult="";

try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeypKey=keyFactory.generatePrivate(pkcs8KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,pKey);

byte[]data=Base64.decodeBase64(content);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();
result=newString(resultBytes);
}catch(Exceptione){
thrownewException(e);
}

returnresult;
}

privatestaticvoidwrite2Stream(Ciphercipher,byte[]data,ByteArrayOutputStreamout)throws
BadPaddingException,IllegalBlockSizeException{
intdataLen=data.length;
intoffSet=0;
byte[]cache;
inti=0;
//对数据分段解密
while(dataLen-offSet>0){
if(dataLen-offSet>MAX_DECRYPT_BLOCK){
cache=cipher.doFinal(data,offSet,MAX_DECRYPT_BLOCK);
}else{
cache=cipher.doFinal(data,offSet,dataLen-offSet);
}
out.write(cache,0,cache.length);
i++;
offSet=i*MAX_DECRYPT_BLOCK;
}
}

/**
*用私钥对信息生成数字签名
*
*@paramdata已加密数据
*@paramprivateKey私钥(BASE64编码)
*@returnsign
*/
publicStringsign(Stringdata,StringprivateKey)throwsException{
Stringresult="";
try{
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeyprivateK=keyFactory.generatePrivate(pkcs8KeySpec);
Signaturesignature=Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(parse2HexStr(data).getBytes(CHARSET));

result=newBase64().encodeToString(signature.sign());
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}

/**
*校验数字签名
*
*@paramdata已加密数据
*@parampublicKey公钥(BASE64编码)
*@paramsign数字签名
*@return
*@throwsException
*/
publicbooleanverify(Stringdata,StringpublicKey,Stringsign)throwsException{
booleanresult;

try{
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpeckeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypublicK=keyFactory.generatePublic(keySpec);
Signaturesignature=Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(parse2HexStr(data).getBytes(CHARSET));
result=signature.verify(newBase64().decode(sign));
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}

/**
*将二进制转换成16进制
*
*@paramdata
*@return
*/
(Stringdata)throwsException{
Stringresult="";
try{
byte[]buf=data.getBytes(CHARSET);

StringBuffersb=newStringBuffer();
for(inti=0;i<buf.length;i++){
Stringhex=Integer.toHexString(buf[i]&0xFF);
if(hex.length()==1){
hex='0'+hex;
}
sb.append(hex.toUpperCase());
}
result=sb.toString();
}catch(UnsupportedEncodingExceptione){
thrownewException(e);
}
returnresult;
}

/**
*生成公钥与私钥
*/
publicstaticvoidcreateKey()throwsException{
try{
=KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
KeyPairkeyPair=keyPairGenerator.generateKeyPair();
RSAPublicKeyrsaPublicKey=(RSAPublicKey)keyPair.getPublic();
RSAPrivateKeyrsaPrivateKey=(RSAPrivateKey)keyPair.getPrivate();

StringpublicKey=Base64.encodeBase64String(rsaPublicKey.getEncoded());
StringprivateKey=Base64.encodeBase64String(rsaPrivateKey.getEncoded());

System.out.println("publicKey="+publicKey+" privateKey="+privateKey);
}catch(NoSuchAlgorithmExceptione){
thrownewException(e);
}
}

publicstaticvoidmain(String[]args)throwsException{

StringPRIVATE_KEY="+m+/fNs1bmgfJhI8lhr/o/Hy8EFB/I/DDyLcCcU4bCLtxpki8edC+KJR2WvyYfnVmWEe//++W5C+lesEOAqdO5nahRZsL8BIDoxTEn2j+DSa///1qX+t8f5wD8i/8GU702PeCwkGI5ymrARq+/+/nkefTq0SNpUDVbGxVpJi9/FOUf";
StringPUBLIC_KEY="+lc///NfOvKvQndzDH60DzLGOMdE0NBrTn/5zEjGwJbVdlvCfOiHwIDAQAB";

RSAUtilsrsaUtil=newRSAUtils();
StringencryptByPublicKey=rsaUtil.encryptByPublicKey("你好!",PUBLIC_KEY);
System.out.println(encryptByPublicKey);
StringdecryptByPrivateKey=rsaUtil.decryptByPrivateKey(encryptByPublicKey,PRIVATE_KEY);
System.out.println(decryptByPrivateKey);
StringencryptByPrivateKey=rsaUtil.encryptByPrivateKey("你好!",PRIVATE_KEY);
System.out.println(encryptByPrivateKey);
StringdecryptByPublicKey=rsaUtil.decryptByPublicKey(encryptByPrivateKey,PUBLIC_KEY);
System.out.println(decryptByPublicKey);
Stringsign=rsaUtil.sign("1234",PRIVATE_KEY);
System.out.println("sign:"+sign);
System.out.println(rsaUtil.verify("1234",PUBLIC_KEY,sign));
}
}

Ⅳ JAVA写RSA加密,公钥私钥都是一样的,为什么每次加密的结果不一样

因为rsa是非对称加密,它使用的是随机大素数的抽取,每次随机生成的,所以每次加密的结果不可能一样

Ⅳ java rsa私钥加密

java rsa私钥加密是什么?让我们一起来了解一下吧!

java rsa私钥加密是一种加密算法。私钥加密算法是用私钥来进行加密与解密信息。私钥加密也被称作对称加密,原因是加密与解密使用的秘钥是同一个。

RSA加密需要注意的事项如下:

1. 首先产生公钥与私钥

2. 设计加密与解密的算法

3. 私钥加密的数据信息只能由公钥可以解密

4. 公钥加密的数据信息只能由私钥可以解密

实战演练,具体步骤如下: public class RsaCryptTools {     private static final String CHARSET = "utf-8";     private static final Base64.Decoder decoder64 = Base64.getDecoder();     private static final Base64.Encoder encoder64 = Base64.getEncoder();       /**      * 生成公私钥      * @param keySize      * @return      * @throws NoSuchAlgorithmException      */     public static SecretKey generateSecretKey(int keySize) throws NoSuchAlgorithmException {         //生成密钥对         KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");         keyGen.initialize(keySize, new SecureRandom());         KeyPair pair = keyGen.generateKeyPair();         PrivateKey privateKey = pair.getPrivate();         PublicKey publicKey = pair.getPublic();         //这里可以将密钥对保存到本地         return new SecretKey(encoder64.encodeToString(publicKey.getEncoded()), encoder64.encodeToString(privateKey.getEncoded()));     }     /**      * 私钥加密      * @param data      * @param privateInfoStr      * @return      * @throws IOException      * @throws InvalidCipherTextException      */     public static String encryptData(String data, String privateInfoStr) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {           Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");         cipher.init(Cipher.ENCRYPT_MODE, getPrivateKey(privateInfoStr));         return encoder64.encodeToString(cipher.doFinal(data.getBytes(CHARSET)));     }       /**      * 公钥解密      * @param data      * @param publicInfoStr      * @return      */     public static String decryptData(String data, String publicInfoStr) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {         byte[] encryptDataBytes=decoder64.decode(data.getBytes(CHARSET));         //解密         Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");         cipher.init(Cipher.DECRYPT_MODE, getPublicKey(publicInfoStr));         return new String(cipher.doFinal(encryptDataBytes), CHARSET);     }     private static PublicKey getPublicKey(String base64PublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes()));         KeyFactory keyFactory = KeyFactory.getInstance("RSA");         return keyFactory.generatePublic(keySpec);     }     private static PrivateKey getPrivateKey(String base64PrivateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {         PrivateKey privateKey = null;         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.getBytes()));         KeyFactory keyFactory = null;         keyFactory = KeyFactory.getInstance("RSA");         privateKey = keyFactory.generatePrivate(keySpec);         return privateKey;     }       /**      * 密钥实体      * @author hank      * @since 2020/2/28 0028 下午 16:27      */     public static class SecretKey {         /**          * 公钥          */         private String publicKey;         /**          * 私钥          */         private String privateKey;           public SecretKey(String publicKey, String privateKey) {             this.publicKey = publicKey;             this.privateKey = privateKey;         }           public String getPublicKey() {             return publicKey;         }           public void setPublicKey(String publicKey) {             this.publicKey = publicKey;         }           public String getPrivateKey() {             return privateKey;         }           public void setPrivateKey(String privateKey) {             this.privateKey = privateKey;         }           @Override         public String toString() {             return "SecretKey{" +                     "publicKey='" + publicKey + '\'' +                     ", privateKey='" + privateKey + '\'' +                     '}';         }     }       private static void writeToFile(String path, byte[] key) throws IOException {         File f = new File(path);         f.getParentFile().mkdirs();           try(FileOutputStream fos = new FileOutputStream(f)) {             fos.write(key);             fos.flush();         }     }       public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, InvalidKeySpecException {         SecretKey secretKey = generateSecretKey(2048);         System.out.println(secretKey);         String enStr = encryptData("你好测试测试", secretKey.getPrivateKey());         System.out.println(enStr);         String deStr = decryptData(enStr, secretKey.getPublicKey());         System.out.println(deStr);         enStr = encryptData("你好测试测试hello", secretKey.getPrivateKey());         System.out.println(enStr);         deStr = decryptData(enStr, secretKey.getPublicKey());         System.out.println(deStr);     }   }

Ⅵ 求JAVA编写的RSA加密算法

代码如下:main方法用于测试的,不是算法本身。

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

import javax.crypto.Cipher;

public class RSACrypto
{
private final static String RSA = "RSA";
public static PublicKey uk;
public static PrivateKey rk;

public static void generateKey() throws Exception
{
KeyPairGenerator gen = KeyPairGenerator.getInstance(RSA);
gen.initialize(512, new SecureRandom());
KeyPair keyPair = gen.generateKeyPair();
uk = keyPair.getPublic();
rk = keyPair.getPrivate();
}

private static byte[] encrypt(String text, PublicKey pubRSA) throws Exception
{
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, pubRSA);
return cipher.doFinal(text.getBytes());
}

public final static String encrypt(String text)
{
try {
return byte2hex(encrypt(text, uk));
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}

public final static String decrypt(String data)
{
try{
return new String(decrypt(hex2byte(data.getBytes())));
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}

private static byte[] decrypt(byte[] src) throws Exception
{
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, rk);
return cipher.doFinal(src);
}

public static String byte2hex(byte[] b)
{
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n ++)
{
stmp = Integer.toHexString(b[n] & 0xFF);
if (stmp.length() == 1)
hs += ("0" + stmp);
else
hs += stmp;
}
return hs.toUpperCase();
}

public static byte[] hex2byte(byte[] b)
{
if ((b.length % 2) != 0)
throw new IllegalArgumentException("长度不是偶数");

byte[] b2 = new byte[b.length / 2];

for (int n = 0; n < b.length; n += 2)
{
String item = new String(b, n, 2);
b2[n/2] = (byte)Integer.parseInt(item, 16);
}
return b2;
}

//just for test
public static void main(String args[])
{
try
{
RSACrypto.generateKey();
String cipherText = RSACrypto.encrypt("asdfghjh");
System.out.println(cipherText);
String plainText = RSACrypto.decrypt(cipherText);
System.out.println(plainText);
}
catch(Exception e)
{
e.printStackTrace();
}
}

}

Ⅶ Java 第三方公钥 RSA加密求助

下面是RSA加誉春密代码。

/**
* RSA算法,实现数据的加密解密。
* @author ShaoJiang
*
*/
public class RSAUtil {

private static Cipher cipher;

static{
try {
cipher = Cipher.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}

/**
* 生成密钥对
* @param filePath 生成密钥做含的路径
* @return
*/
public static Map<String,String> generateKeyPair(String filePath){
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 密钥位数
keyPairGen.initialize(1024);
// 密钥对
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//得到公钥字符串
String publicKeyString = getKeyString(publicKey);
//得到私钥字符串
String privateKeyString = getKeyString(privateKey);

FileWriter pubfw = new FileWriter(filePath+"/publicKey.keystore"纯虚笑);
FileWriter prifw = new FileWriter(filePath+"/privateKey.keystore");
BufferedWriter pubbw = new BufferedWriter(pubfw);
BufferedWriter pribw = new BufferedWriter(prifw);
pubbw.write(publicKeyString);
pribw.write(privateKeyString);
pubbw.flush();
pubbw.close();
pubfw.close();
pribw.flush();
pribw.close();
prifw.close();
//将生成的密钥对返回
Map<String,String> map = new HashMap<String,String>();
map.put("publicKey",publicKeyString);
map.put("privateKey",privateKeyString);
return map;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 得到公钥
*
* @param key
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}

/**
* 得到私钥
*
* @param key
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}

/**
* 得到密钥字符串(经过base64编码)
*
* @return
*/
public static String getKeyString(Key key) throws Exception {
byte[] keyBytes = key.getEncoded();
String s = (new BASE64Encoder()).encode(keyBytes);
return s;
}

/**
* 使用公钥对明文进行加密,返回BASE64编码的字符串
* @param publicKey
* @param plainText
* @return
*/
public static String encrypt(PublicKey publicKey,String plainText){
try {
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] enBytes = cipher.doFinal(plainText.getBytes());
return (new BASE64Encoder()).encode(enBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}

/**
* 使用keystore对明文进行加密
* @param publicKeystore 公钥文件路径
* @param plainText 明文
* @return
*/
public static String encrypt(String publicKeystore,String plainText){
try {
FileReader fr = new FileReader(publicKeystore);
BufferedReader br = new BufferedReader(fr);
String publicKeyString="";
String str;
while((str=br.readLine())!=null){
publicKeyString+=str;
}
br.close();
fr.close();
cipher.init(Cipher.ENCRYPT_MODE,getPublicKey(publicKeyString));
byte[] enBytes = cipher.doFinal(plainText.getBytes());
return (new BASE64Encoder()).encode(enBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 使用私钥对明文密文进行解密
* @param privateKey
* @param enStr
* @return
*/
public static String decrypt(PrivateKey privateKey,String enStr){
try {
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));
return new String(deBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

/**
* 使用keystore对密文进行解密
* @param privateKeystore 私钥路径
* @param enStr 密文
* @return
*/
public static String decrypt(String privateKeystore,String enStr){
try {
FileReader fr = new FileReader(privateKeystore);
BufferedReader br = new BufferedReader(fr);
String privateKeyString="";
String str;
while((str=br.readLine())!=null){
privateKeyString+=str;
}
br.close();
fr.close();
cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyString));
byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));
return new String(deBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

Ⅷ Java RSA 加密解密中 密钥保存并读取,数据加密解密并保存读取 问题

帮你完善了下代码。

importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.FileReader;
importjava.io.OutputStream;
importjava.io.PrintWriter;
importjava.io.Reader;
importjava.util.Map;

publicclassTest{
staticStringpublicKey;
staticStringprivateKey;

publicTest()throwsException{
//TODOAuto-generatedconstructorstub
Map<String,Object>keyMap=RSAUtils.genKeyPair();
publicKey=RSAUtils.getPublicKey(keyMap);
privateKey=RSAUtils.getPrivateKey(keyMap);

//保存密钥,名字分别为publicKey。txt和privateKey。txt;
PrintWriterpw1=newPrintWriter(newFileOutputStream(
"D:/publicKey.txt"));
PrintWriterpw2=newPrintWriter(newFileOutputStream(
"D:/privateKey.txt"));
pw1.print(publicKey);
pw2.print(privateKey);
pw1.close();
pw2.close();

//从保存的目录读取刚才的保存的公钥,
Stringpubkey=readFile("D:/publicKey.txt");//读取的公钥内容;
Stringdata=readFile("D:/1.txt");//需要公钥加密的文件的内容(如D:/1.txt)
byte[]encByPubKeyData=RSAUtils.encryptByPublicKey(data.getBytes(),
pubkey);
//将加密数据base64后写入文件
writeFile("D:/Encfile.txt",Base64Utils.encode(encByPubKeyData).getBytes("UTF-8"));
//加密后的文件保存在

Stringprikey=readFile("D:/privateKey.txt");//从保存的目录读取刚才的保存的私钥,
StringEncdata=readFile("D:/Encfile.txt");//刚才加密的文件的内容;
byte[]encData=Base64Utils.decode(Encdata);
byte[]decByPriKeyData=RSAUtils.decryptByPrivateKey(encData,prikey);
//解密后后的文件保存在D:/Decfile.txt
writeFile("D:/Decfile.txt",decByPriKeyData);
}

privatestaticStringreadFile(StringfilePath)throwsException{
FileinFile=newFile(filePath);
longfileLen=inFile.length();
Readerreader=newFileReader(inFile);

char[]content=newchar[(int)fileLen];
reader.read(content);
System.out.println("读取到的内容为:"+newString(content));
returnnewString(content);
}

privatestaticvoidwriteFile(StringfilePath,byte[]content)
throwsException{
System.out.println("待写入文件的内容为:"+newString(content));
FileoutFile=newFile(filePath);
OutputStreamout=newFileOutputStream(outFile);
out.write(content);
if(out!=null)out.close();
}

publicstaticvoidmain(String[]args)throwsException{
//TODOAuto-generatedmethodstub

newTest();
}

}

测试结果:

读取到的内容为:++lXfZxzNpeA+rHaxmeQ2qI+5ES9AF7G6KIwjzakKsA08Ly+1y3dp0BnoyHF7/Pj3AS28fDmE5piea7w36vp4E3Ts+F9vwIDAQAB
读取到的内容为:锘县ahaha

Ⅸ 怎样用Java实现RSA加密

提供加密,解密,生成密钥对等方法。�梢愿�模��遣灰��螅�裨蛐�驶岬� keyPairGen.initialize(KEY_SIZE, new SecureRandom()); KeyPair keyPair = keyPairGen.genKeyPair(); return keyPair; } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * 生成公钥 * @param molus * @param publicExponent * @return RSAPublicKey * @throws Exception */ public static RSAPublicKey generateRSAPublicKey(byte[] molus, byte[] publicExponent) throws Exception { KeyFactory keyFac = null; try { keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); } catch (NoSuchAlgorithmException ex) { throw new Exception(ex.getMessage()); } RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(molus), new BigInteger(publicExponent)); try { return (RSAPublicKey) keyFac.generatePublic(pubKeySpec); } catch (InvalidKeySpecException ex) { throw new Exception(ex.getMessage()); } } /** * 生成私钥 * @param molus * @param privateExponent * @return RSAPrivateKey * @throws Exception */ public static RSAPrivateKey generateRSAPrivateKey(byte[] molus, byte[] privateExponent) throws Exception { KeyFactory keyFac = null; try { keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); } catch (NoSuchAlgorithmException ex) { throw new Exception(ex.getMessage()); } RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(molus), new BigInteger(privateExponent)); try { return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec); } catch (InvalidKeySpecException ex) { throw new Exception(ex.getMessage()); } } /** * 加密 * @param key 加密的密钥 * @param data 待加密的明文数据 * @return 加密后的数据 * @throws Exception */ public static byte[] encrypt(Key key, byte[] data) throws Exception { try { Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); cipher.init(Cipher.ENCRYPT_MODE, key); int blockSize = cipher.getBlockSize();//获得加密块大小� i++; } return raw; } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * 解密 * @param key 解密的密钥 * @param raw 已经加密的数据 * @return 解密后的明文 * @throws Exception */ public static byte[] decrypt(Key key, byte[] raw) throws Exception { try { Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); cipher.init(cipher.DECRYPT_MODE, key); int blockSize = cipher.getBlockSize(); ByteArrayOutputStream bout = new ByteArrayOutputStream(64); int j = 0; while (raw.length - j * blockSize > 0) { bout.write(cipher.doFinal(raw, j * blockSize, blockSize)); j++; } return bout.toByteArray(); } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { File file = new File("c:/test.html"); FileInputStream in = new FileInputStream(file); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] tmpbuf = new byte[1024]; int count = 0; while ((count = in.read(tmpbuf)) != -1) { bout.write(tmpbuf, 0, count); tmpbuf = new byte[1024]; } in.close(); byte[] orgData = bout.toByteArray(); KeyPair keyPair = RSA.generateKeyPair(); RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate(); byte[] pubModBytes = pubKey.getMolus().toByteArray(); byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray(); byte[] priModBytes = priKey.getMolus().toByteArray(); byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray(); RSAPublicKey recoveryPubKey = RSA.generateRSAPublicKey(pubModBytes,pubPubExpBytes); RSAPrivateKey recoveryPriKey = RSA.generateRSAPrivateKey(priModBytes,priPriExpBytes); byte[] raw = RSA.encrypt(priKey, orgData); file = new File("c:/encrypt_result.dat"); OutputStream out = new FileOutputStream(file); out.write(raw); out.close(); byte[] data = RSA.decrypt(recoveryPubKey, raw); file = new File("c:/decrypt_result.html"); out = new FileOutputStream(file); out.write(data); out.flush(); out.close(); } } (责任编辑:云子)

Ⅹ java非对称加密的源代码(RSA)

鉴于rsa加密的重要性和相关源代码的匮乏 经过整理特此贴出 需要下载bcprov jdk jar import javax crypto Cipher;import java security *;import java security spec RSAPublicKeySpec;清纳import java security spec RSAPrivateKeySpec;import java security spec InvalidKeySpecException;import java security interfaces RSAPrivateKey;import java security interfaces RSAPublicKey;import java io *;import java math BigInteger;/*** RSA 工具类 提供加密 解密 生成密钥对等方法 * 需要到下载bcprov jdk jar **/public class RSAUtil {/*** 生成密钥对* @return KeyPair* @throws EncryptException*/public static KeyPair generateKeyPair() throws EncryptException {try {槐码KeyPairGenerator keyPairGen = KeyPairGenerator getInstance( RSA new bouncycastle jce provider BouncyCastleProvider());final int KEY_SIZE = ;//没什么好说的了 这个值关系到块加密的大小 可以更改 但是不要太大 否则效率会低keyPairGen initialize(KEY_SIZE new SecureRandom());KeyPair keyPair = keyPairGen genKeyPair();return keyPair;} catch (Exception e) {throw new EncryptException(e getMessage());}}/*** 生成公钥* @param molus* @param publicExponent* @return RSAPublicKey* @throws EncryptException*/public static RSAPublicKey generateRSAPublicKey(byte[] molus byte[] publicExponent) throws EncryptException {KeyFactory keyFac = null;try {keyFac = KeyFactory getInstance( RSA new bouncycastle jce provider BouncyCastleProvider());} catch (NoSuchAlgorithmException ex) {throw new EncryptException(ex getMessage());}RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(molus) new BigInteger(publicExponent));try {return (RSAPublicKey) keyFac generatePublic(pubKeySpec);} catch (InvalidKeySpecException ex) {throw new EncryptException(ex getMessage());}}/*** 生成私钥* @param molus铅正哪* @param privateExponent* @return RSAPrivateKey* @throws EncryptException*/public static RSAPrivateKey generateRSAPrivateKey(byte[] molus byte[] privateExponent) throws EncryptException {KeyFactory keyFac = null;try {keyFac = KeyFactory getInstance( RSA new bouncycastle jce provider BouncyCastleProvider());} catch (NoSuchAlgorithmException ex) {throw new EncryptException(ex getMessage());}RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(molus) new BigInteger(privateExponent));try {return (RSAPrivateKey) keyFac generatePrivate(priKeySpec);} catch (InvalidKeySpecException ex) {throw new EncryptException(ex getMessage());}}/*** 加密* @param key 加密的密钥* @param data 待加密的明文数据* @return 加密后的数据* @throws EncryptException*/public static byte[] encrypt(Key key byte[] data) throws EncryptException {try {Cipher cipher = Cipher getInstance( RSA new bouncycastle jce provider BouncyCastleProvider());cipher init(Cipher ENCRYPT_MODE key);int blockSize = cipher getBlockSize();//获得加密块大小 如 加密前数据为 个byte 而key_size= 加密块大小为 byte 加密后为 个byte;因此共有 个加密块 第一个 byte第二个为 个byteint outputSize = cipher getOutputSize(data length);//获得加密块加密后块大小int leavedSize = data length % blockSize;int blocksSize = leavedSize != ? data length / blockSize + : data length / blockSize;byte[] raw = new byte[outputSize * blocksSize];int i = ;while (data length i * blockSize > ) {if (data length i * blockSize > blockSize)cipher doFinal(data i * blockSize blockSize raw i * outputSize);elsecipher doFinal(data i * blockSize data length i * blockSize raw i * outputSize);//这里面doUpdate方法不可用 查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到ByteArrayOutputStream中 而最后doFinal的时候才将所有的byte[]进行加密 可是到了此时加密块大小很可能已经超出了OutputSize所以只好用dofinal方法 i++;}return raw;} catch (Exception e) {throw new EncryptException(e getMessage());}}/*** 解密* @param key 解密的密钥* @param raw 已经加密的数据* @return 解密后的明文* @throws EncryptException*/public static byte[] decrypt(Key key byte[] raw) throws EncryptException {try {Cipher cipher = Cipher getInstance( RSA new bouncycastle jce provider BouncyCastleProvider());cipher init(cipher DECRYPT_MODE key);int blockSize = cipher getBlockSize();ByteArrayOutputStream bout = new ByteArrayOutputStream( );int j = ;while (raw length j * blockSize > ) {bout write(cipher doFinal(raw j * blockSize blockSize));j++;}return bout toByteArray();} catch (Exception e) {throw new EncryptException(e getMessage());}}/**** @param args* @throws Exception*/public static void main(String[] args) throws Exception {File file = new File( l );FileInputStream in = new FileInputStream(file);ByteArrayOutputStream bout = new ByteArrayOutputStream();byte[] tmpbuf = new byte[ ];int count = ;while ((count = in read(tmpbuf)) != ) {bout write(tmpbuf count);tmpbuf = new byte[ ];}in close();byte[] Data = bout toByteArray();KeyPair keyPair = RSAUtil generateKeyPair();RSAPublicKey pubKey = (RSAPublicKey) keyPair getPublic();RSAPrivateKey priKey = (RSAPrivateKey) keyPair getPrivate();byte[] pubModBytes = pubKey getMolus() toByteArray();byte[] pubPubExpBytes = pubKey getPublicExponent() toByteArray();byte[] priModBytes = priKey getMolus() toByteArray();byte[] priPriExpBytes = priKey getPrivateExponent() toByteArray();RSAPublicKey recoveryPubKey = RSAUtil generateRSAPublicKey(pubModBytes pubPubExpBytes);RSAPrivateKey recoveryPriKey = RSAUtil generateRSAPrivateKey(priModBytes priPriExpBytes);byte[] raw = RSAUtil encrypt(priKey Data);file = new File( encrypt_result dat );OutputStream out = new FileOutputStream(file);out write(raw);out close();byte[] data = RSAUtil decrypt(recoveryPubKey raw);file = new File( l );out = new FileOutputStream(file);out write(data);out flush();out close();}}加密可以用公钥 解密用私钥 或者加密用私钥 通常非对称加密是非常消耗资源的 因此可以对大数据用对称加密如 des(具体代码可以看我以前发的贴子) 而对其对称密钥进行非对称加密 这样既保证了数据的安全 还能保证效率 lishixin/Article/program/Java/gj/201311/27391

热点内容
中国首个具有世界影响力的编译器 发布:2025-02-09 01:56:21 浏览:719
tomcat上传超时 发布:2025-02-09 01:41:42 浏览:483
androidactivity竖屏 发布:2025-02-09 01:41:40 浏览:377
家庭配置怎么合理 发布:2025-02-09 01:36:14 浏览:807
头条军事源码 发布:2025-02-09 01:31:53 浏览:997
androidintent视频 发布:2025-02-09 01:31:43 浏览:858
欧姆龙plc密码如何设置 发布:2025-02-09 01:24:31 浏览:687
php支持jpeg 发布:2025-02-09 01:24:22 浏览:803
反编译去注册码 发布:2025-02-09 01:19:48 浏览:887
安卓如何查找旧密码 发布:2025-02-09 01:17:21 浏览:418