使用充气城堡和python PKCS1-OAEP进行java RSA加密

时间:2014-04-10 07:09:33

标签: java python encryption bouncycastle public-key

一个多星期以来,我一直在使用this与我在python中的服务器实现RSA安全通信。

然而,我不能为我的生活找出所有罐子的正确进口。

我已经包含了在充气城堡网站上发现的所有罐子,但仍然没有骰子!

我读到他们搬了东西。如果这段代码是旧的或破坏了,那么带有pkcs1填充的RSA的其他实现是什么?

修改

pub键位于名为key.pub的文件中。如何读取该文件以用作密钥

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv2B0wo+QJ6tCqeyTzhZ3
AtPLgAHEQ/fRYDcR0BkQ+lXEhD277P2fPZwla5AW6szqsjR1olkZEF7IuoI27Hxm
tQHJU0ROhrzstHgK42emz5Ya3BWcm+oq5pLDZnsNDnNlrPncaCT7gHQQJn3YjH8q
aibtB1WCoy7ZJ127QxoKoLfeonBDtt7Qw6P5iXE57IbQ63oLq1EaYUfg8ZpADvJF
b2H3MASJSSDrSDgrtCcKAUYuu3cZw16XShuKCNb5QLsj3tR0QC++7qjM3VcG311K
7gHVjB6zybw+5vX2UWTgZuL6WVtCvRK+WY7nhL3cc5fmXZhkW1Jbx6wLPK3K/JcR
NQIDAQAB
-----END PUBLIC KEY-----

编辑2:根据答案添加损坏的代码

package Main;


import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.X509EncodedKeySpec;

public class EncDecRSA {
    public static byte[] pemToDer(String pemKey) throws GeneralSecurityException {
        String[] parts = pemKey.split("-----");
        return DatatypeConverter.parseBase64Binary(parts[parts.length / 2]);
    }

    public static PublicKey derToPublicKey(byte[] asn1key) throws GeneralSecurityException {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(asn1key);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        return keyFactory.generatePublic(spec);
    }

    public static byte[] encrypt(PublicKey publicKey, String text) throws GeneralSecurityException {
        Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC");//PKCS1-OAEP
        rsa.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] cipher =  rsa.doFinal(text.getBytes());
        String s = new String(cipher);
        System.out.print(s);
//        return cipher;
//        return Base64.encode(rsa.doFinal(text.getBytes()));
        cipher = Base64.encode(cipher);
        return cipher;

    }

    static String readFile(String path)
            throws IOException
    {
        String line = null;
        BufferedReader br = new BufferedReader(new FileReader(path));
        try {
            StringBuilder sb = new StringBuilder();
            line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            return sb.toString();
        } finally {
            br.close();

        }

    }
    public static void main(String[] args) throws IOException, GeneralSecurityException {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        System.out.println("Working Directory = " +
                System.getProperty("user.dir"));
        String publicKey = readFile("key.public");
        byte[] pem = pemToDer(publicKey);
        PublicKey myKey = derToPublicKey(pem);
        String sendMessage = "{'vid_hash': '917ef7e7be4a84e279b74a257953307f1cff4a2e3d221e363ead528c6b556edb', 'state': 'ballot_response', 'userInfo': {'ssn': '700-33-6870', 'pin': '1234', 'vid': '265jMeges'}}";
        byte[] encryptedDATA = encrypt(myKey, sendMessage);
        Socket smtpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            smtpSocket = new Socket("192.168.1.124", 9999);
            os = new DataOutputStream(smtpSocket.getOutputStream());
            is = new DataInputStream(smtpSocket.getInputStream());
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: hostname");
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: hostname");
        }

        if (smtpSocket != null && os != null && is != null) {
            try {
                System.out.println("sending message");
                os.writeBytes(encryptedDATA+"\n");
                os.close();
                is.close();
                smtpSocket.close();
            } catch (UnknownHostException e) {
                System.err.println("Trying to connect to unknown host: " + e);
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        }
    }
}

出现以下错误:

enter image description here

以下是执行该操作的python代码:

def _decrypt_RSA(self, private_key_loc, package):
    '''
    param: public_key_loc Path to your private key
    param: package String to be decrypted
    return decrypted string
    '''
    from Crypto.PublicKey import RSA 
    from Crypto.Cipher import PKCS1_OAEP 
    from base64 import b64decode 
    key = open('key.private', "r").read() 
    rsakey = RSA.importKey(key) 
    rsakey = PKCS1_OAEP.new(rsakey) 

    decrypted = rsakey.decrypt(package)
    # decrypted = rsakey.decrypt(b64decode(package)) 
    return decrypted

最后:

此填充方案是否为PKCS1-OAEP。

这是实现这一目标的主要要求。

请注意,我已尝试使用base64编码和不使用

1 个答案:

答案 0 :(得分:1)

此示例适用于SpongyCastle - Android重新打包BouncyCastle。你发现它们有所不同。但是,在Java中进行加密就像这个

一样简单

将Base64编码的密钥字符串转换为ASN.1 DER编码的字节数组

public static byte[] pemToDer(String pemKey) throws GeneralSecurityException {
    String[] parts = pemKey.split("-----");
    return DatatypeConverter.parseBase64Binary(parts[parts.length / 2]);
}

将ASN.1 DER编码的公钥转换为PublicKey对象

public static PublicKey derToPublicKey(byte[] asn1key) throws GeneralSecurityException {
    X509EncodedKeySpec spec = new X509EncodedKeySpec(asn1key);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    return keyFactory.generatePublic(spec);
}

加密数据

public static byte[] encrypt(PublicKey publicKey, String text) throws GeneralSecurityException {
    Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC");
    rsa.init(Cipher.ENCRYPT_MODE, publicKey);
    return rsa.doFinal(text.getBytes());
}

bcprov-jdk15on-150.jar是唯一需要的罐子。