Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3515702
  • 博文数量: 864
  • 博客积分: 14125
  • 博客等级: 上将
  • 技术积分: 10634
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-27 16:53
个人简介

https://github.com/zytc2009/BigTeam_learning

文章分类

全部博文(864)

文章存档

2023年(1)

2021年(1)

2019年(3)

2018年(1)

2017年(10)

2015年(3)

2014年(8)

2013年(3)

2012年(69)

2011年(103)

2010年(357)

2009年(283)

2008年(22)

分类: Java

2010-11-11 11:17:45

关键字: rsa, 公钥, 私钥, 非对称加密

RSA
    这种算法1978年就出现了,它是第一个既能用于数据加密也能用于数字签名的算法。它易于理解和操作,也很流行。算法的名字以发明者的名字命名:Ron Rivest, AdiShamir 和Leonard Adleman。
    这种加密算法的特点主要是密钥的变化,上文我们看到DES只有一个密钥。相当于只有一把钥匙,如果这把钥匙丢了,数据也就不安全了。RSA同时有两把钥匙,公钥与私钥。
    公钥公开,私钥保密。我们用公钥加密数据,用私钥解密数据。能不能反过来呢,用私钥加密,用公钥解密呢?不可以!

通过java代码实现如下:Coder类见 java加密技术(一)
Java代码
import java.security.Key;  
import java.security.KeyFactory;  
import java.security.KeyPair;  
import java.security.KeyPairGenerator;  
import java.security.interfaces.RSAPrivateKey;  
import java.security.interfaces.RSAPublicKey;  
import java.security.spec.PKCS8EncodedKeySpec;  
import java.security.spec.X509EncodedKeySpec;  
 
import java.util.HashMap;  
import java.util.Map;  
 
import javax.crypto.Cipher;  
 
/** 
* RSA安全编码组件 
*  
*/ 
public abstract class RSACoder extends Coder {  
    public static final String ALGORITHM = "RSA";  
    private static final String PUBLIC_KEY = "RSAPublicKey";  
    private static final String PRIVATE_KEY = "RSAPrivateKey";  
 
    /** 
     * 解密
 
     * 用私钥解密 
     *  
     * @param data 
     * @param key 
     * @return 
     * @throws Exception 
     */ 
    public static byte[] decrypt(byte[] data, String key) throws Exception {  
        // 对密钥解密  
        byte[] keyBytes = decryptBASE64(key);  
 
        // 取得私钥  
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);  
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);  
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);  
 
        // 对数据解密  
        Cipher cipher = Cipher.getInstance(ALGORITHM);  
        cipher.init(Cipher.DECRYPT_MODE, privateKey);  
 
        return cipher.doFinal(data);  
    }  
 
    /** 
     * 加密
 
     * 用公钥加密 
     *  
     * @param data 
     * @param key 
     * @return 
     * @throws Exception 
     */ 
    public static byte[] encrypt(byte[] data, String key) throws Exception {  
        // 对公钥解密  
        byte[] keyBytes = decryptBASE64(key);  
 
        // 取得公钥  
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);  
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);  
        Key publicKey = keyFactory.generatePublic(x509KeySpec);  
 
        // 对数据加密  
        Cipher cipher = Cipher.getInstance(ALGORITHM);  
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
 
        return cipher.doFinal(data);  
    }  
 
    /** 
     * 取得私钥 
     *  
     * @param keyMap 
     * @return 
     * @throws Exception 
     */ 
    public static String getPrivateKey(Map keyMap)  
            throws Exception {  
        Key key = (Key) keyMap.get(PRIVATE_KEY);  
 
        return encryptBASE64(key.getEncoded());  
    }  
 
    /** 
     * 取得公钥 
     *  
     * @param keyMap 
     * @return 
     * @throws Exception 
     */ 
    public static String getPublicKey(Map keyMap)  
            throws Exception {  
        Key key = (Key) keyMap.get(PUBLIC_KEY);  
 
        return encryptBASE64(key.getEncoded());  
    }  
 
    /** 
     * 初始化密钥 
     *  
     * @return 
     * @throws Exception 
     */ 
    public static Map initKey() throws Exception {  
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);  
        keyPairGen.initialize(1024);  
 
        KeyPair keyPair = keyPairGen.generateKeyPair();  
 
        // 公钥  
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
 
        // 私钥  
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
 
        Map keyMap = new HashMap(2);  
 
        keyMap.put(PUBLIC_KEY, publicKey);  
        keyMap.put(PRIVATE_KEY, privateKey);  
 
        return keyMap;  
    }  


import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

/**
* RSA安全编码组件
*
*/
public abstract class RSACoder extends Coder {
public static final String ALGORITHM = "RSA";
private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey";

/**
* 解密

* 用私钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, String key) throws Exception {
// 对密钥解密
byte[] keyBytes = decryptBASE64(key);

// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

// 对数据解密
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);

return cipher.doFinal(data);
}

/**
* 加密

* 用公钥加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String key) throws Exception {
// 对公钥解密
byte[] keyBytes = decryptBASE64(key);

// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);

// 对数据加密
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);

return cipher.doFinal(data);
}

/**
* 取得私钥
*
* @param keyMap
* @return
* @throws Exception
*/
public static String getPrivateKey(Map keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);

return encryptBASE64(key.getEncoded());
}

/**
* 取得公钥
*
* @param keyMap
* @return
* @throws Exception
*/
public static String getPublicKey(Map keyMap)
throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);

return encryptBASE64(key.getEncoded());
}

/**
* 初始化密钥
*
* @return
* @throws Exception
*/
public static Map initKey() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGen.initialize(1024);

KeyPair keyPair = keyPairGen.generateKeyPair();

// 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

// 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

Map keyMap = new HashMap(2);

keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);

return keyMap;
}
}

再给出一个测试类:
Java代码
import static org.junit.Assert.*;  
 
import org.junit.Test;  
 
import java.util.Map;  
 
/** 
*  
*/ 
public class RSACoderTest {  
 
    @Test 
    public void test() throws Exception {  
        String inputStr = "abc";  
        byte[] data = inputStr.getBytes();  
 
        Map keyMap = RSACoder.initKey();  
 
        String publicKey = RSACoder.getPublicKey(keyMap);  
        String privateKey = RSACoder.getPrivateKey(keyMap);  
        System.err.println("公钥: \n\r" + publicKey);  
        System.err.println("私钥: \n\r" + privateKey);  
 
        byte[] encodedData = RSACoder.encrypt(data, publicKey);  
 
        byte[] decodedData = RSACoder.decrypt(encodedData, privateKey);  
        String outputStr = new String(decodedData);  
        System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);  
        assertEquals(inputStr, outputStr);  
    }  
 


import static org.junit.Assert.*;

import org.junit.Test;

import java.util.Map;

/**
*
*/
public class RSACoderTest {

@Test
public void test() throws Exception {
String inputStr = "abc";
byte[] data = inputStr.getBytes();

Map keyMap = RSACoder.initKey();

String publicKey = RSACoder.getPublicKey(keyMap);
String privateKey = RSACoder.getPrivateKey(keyMap);
System.err.println("公钥: \n\r" + publicKey);
System.err.println("私钥: \n\r" + privateKey);

byte[] encodedData = RSACoder.encrypt(data, publicKey);

byte[] decodedData = RSACoder.decrypt(encodedData, privateKey);
String outputStr = new String(decodedData);
System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);
assertEquals(inputStr, outputStr);
}

}

控制台输出:
Console代码
公钥:   
 
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAiF0wxZP16aO4ZjUAj1bxFzhx157bB/hBpKyi  
lh68cg5cTm5QQvWcc1duLdXyR4EH0O557qONMKopsTNIGGrpDRWVU1RIlpCOk+53MmEVm/R/Gmj7  
l0ccckrDl4Dx1hWEtxqgXh6H/DDk6Ldns4RYVj0evqj7l1KESNvNWjQlBwIDAQAB  
 
私钥:   
 
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAICIXTDFk/Xpo7hmNQCPVvEXOHHX  
ntsH+EGkrKKWHrxyDlxOblBC9ZxzV24t1fJHgQfQ7nnuo40wqimxM0gYaukNFZVTVEiWkI6T7ncy  
YRWb9H8aaPuXRxxySsOXgPHWFYS3GqBeHof8MOTot2ezhFhWPR6+qPuXUoRI281aNCUHAgMBAAEC  
gYBGJiZ2T98I/5LTOTUEMTcKLdooh72zXQ4pBW8S7UupHbaoukWKmIDj+i9leq6hpFTPp0AAXDX3  
APBeANA0MN9nvCY9Bxs7IwKlfsi2/IiQbacCwEvvnl7MDVD3BoOBLijLXylr2vWez2M1/+DcEfLf  
hFCx85j/8KWxha3RKrQMwQJBALmeFACUwGD9LgNXXB9GAPCbec/hKBkgPWQP+MDQsATWukAXGRMT  
JKET2AUiWqQjE1aNS87H6PapGR+M6Cf38zsCQQCxRQ1zyLwKTfoexj61b2LWz3v93yUgQp/BlSvk  
/CBAmQSyTHQUlOisdmQvZluKYKETRHpUDzKCKQfoyITxJyClAkEAgcPy5ekYiXXWyj0zySVOmOeJ  
BHy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cPy5ekYiXXWyj0zySVOmOeJ
BHy7ZL12TdMgq+P5epiHwzCitgQnEnlmB0jaJ2/iIBtOCTUXOAJF7xm6X97nawJBAKZFjbOfgfjs
YQHCkwkdXAj+fl+GkU0sEKrDn3NdpWbR4BzZJzwy2/b/6UKocI5fylXHMjJsOsTpdXi7tC55s90C
QEyv+TwMomqkUU/X/I3JfWnh027RS3cOH1jEQA+xL5oPYnD1zI8FYdV2q0knFwMMVpJQDD+KbAdC
1uWAAj3fbls=

加密前: abc

解密后: abc


如果公钥只能加密,私钥只能解密,但是双方都需要互通加密数据该怎么办?使用DH加密算法!
阅读(1409) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~