`
slippy
  • 浏览: 32909 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

RSA Public Key Cryptography in Java

阅读更多

 

Public key cryptography is a well-known concept, but for some reason the JCE (Java Cryptography Extensions) documentation doesn't at all make it clear how to interoperate with common public key formats such as those produced by openssl. If you try to do a search on the web for how to make RSA public key cryptography work in Java, you quickly find a lot of people asking questions and not a lot of people answering them. In this post, I'm going to try to lay out very clearly how I got this working.

Just to set expectations, this is not a tutorial about how to use the cryptography APIs themselves in javax.crypto (look at the JCE tutorials from Sun for this); nor is this a primer about how public key cryptography works. This article is really about how to manage the keys with off-the-shelf utilities available to your friendly, neighborhood sysadmin and still make use of them from Java programs. Really, this boils down to "how do I get these darn keys loaded into a Java program where they can be used?" This is the article I wish I had when I started trying to muck around with this stuff....

Managing the keys

Openssl. This is the de-facto tool sysadmins use for managing public/private keys, X.509 certificates, etc. This is what we want to create/manage our keys with, so that they can be stored in formats that are common across most Un*x systems and utilities (like, say, C programs using the openssl library...). Java has this notion of its own keystore, and Sun will give you the keytool command with Java, but that doesn't do you much good outside of Java world.

Creating the keypair. We are going to create a keypair, saving it in openssl's preferred PEM format. PEM formats are ASCII and hence easy to email around as needed. However, we will need to save the keys in the binary DER format so Java can read them. Without further ado, here is the magical incantation for creating the keys we'll use:

# generate a 2048-bit RSA private key
$ openssl genrsa -out private_key.pem 2048

# convert private Key to PKCS#8 format (so Java can read it)
$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem \
    -out private_key.der -nocrypt

# output public key portion in DER format (so Java can read it)
$ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der

You keep private_key.pem around for reference, but you hand the DER versions to your Java programs.

Loading the keys into Java

Really, this boils down to knowing what type of KeySpec to use when reading in the keys. To read in the private key:

import java.io.*;
import java.security.*;
import java.security.spec.*;

public class PrivateKeyReader {

  public static PrivateKey get(String filename)
    throws Exception {
    
    File f = new File(filename);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int)f.length()];
    dis.readFully(keyBytes);
    dis.close();

    PKCS8EncodedKeySpec spec =
      new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(spec);
  }
}

And now, to read in the public key:

import java.io.*;
import java.security.*;
import java.security.spec.*;

public class PublicKeyReader {

  public static PublicKey get(String filename)
    throws Exception {
    
    File f = new File(filename);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int)f.length()];
    dis.readFully(keyBytes);
    dis.close();

    X509EncodedKeySpec spec =
      new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
  }
}

That's about it. The hard part was figuring out a compatible set of:

  1. openssl DER output options (particularly the PKCS#8 encoding)
  2. which type of KeySpec Java needed to use (strangely enough, the public key needs the "X509" keyspec, even though you would normally handle X.509 certificates with the openssl x509 command, not the openssl rsa command. Real intuitive.)

From here, signing and verifying work as described in the JCE documentation; the only other thing you need to know is that you can use the "SHA1withRSA" algorithm when you get your java.security.Signature instance for signing/verifying, and that you want the "RSA" algorithm when you get your javax.crypto.Cipher instance for encrypting/decrypting.

Many happy security returns to you.

分享到:
评论

相关推荐

    PKCS #1: RSA Cryptography Specifications Version 2.2

    PKCS #1: RSA Cryptography Specifications ... RSA Public Key . . . . . . . . . . . . . . . . . . . . . 8 3.2. RSA Private Key . . . . . . . . . . . . . . . . . . . . . 9 4. Data Conversion Primitives

    An introduction to mathematical cryptography

    for undergraduate independent study, or for the mathematician who wants to see how mathematics is used in public key cryptography." (Jintai Ding and Chris Christensen, Mathematical Reviews, Issue ...

    RSA公司的PKCS系列标准

    RSA公司的PKCS(Public Key Cryptography Standards)系列标准。 官方网站的相关页面和链接好像已经失效。经过精心查找和整理,这可能是目前能收集到的最全的版本,包括如下版本: PKCS #1 v2.2: RSA Cryptography ...

    RSA加密解密(C#)实现

    System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPublicKey); PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString); ...

    Practical Cryptography for Developers

    cipher block modes, authenticated encryption, AEAD, AES-GCM, ChaCha20-Poly1305), asymmetric ciphers and public-key cryptosystems (RSA, ECC, ECIES), elliptic curve cryptography (ECC, secp256k1, curve...

    c#写的rsa类 解密加密 js密码RSA 的密钥产生

    这个类是关于加密,解密的操作,文件的一些高级操作 1.RSACryption RSA 的密钥产生 ... public void RSAKey(out string xmlKeys,out string xmlPublicKey) { System.Security.Cryptography.

    Understanding Cryptography (2010)

    the Advanced Encryption Standard (AES), block ciphers, the RSA cryptosystem, public-key cryptosystems based on the discrete logarithm problem, elliptic-curve cryptography (ECC), digital signatures, ...

    pkcs-11v2-20d3.rar_PKCS#1_PKCS#11 USBKey_RSA PKCS_pkcs_usbkey

    在密码系统中,PKCS#11是公钥加密标准(PKCS, Public-Key Cryptography Standards)中的一份子 ,由RSA实验室(RSA Laboratories)发布[1],它为加密令牌定义了一组平台无关的API ,如硬件安全模块和智能卡。...

    rfc3447(PKCS #1).pdf

    Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1

    RSA:简单的RSA cryptographyc算法实现

    RSA算法的简单实现由RSA通讯社和其他国家的用户组成的Feitoporsãoe aprendizado。 请使用重要的对等物。RSA的“ saber mais sobre”是什么? 执行力: ~$ python enconde.pyInsira o texto que você deseja ...

    lnotes_book.pdf

    3. Signature schemes: These are the public key versions of authentication though interestingly are easier to construct in some sense than the latter. 4. Active attacks for encryption: Chosen ...

    William Stallings,Cryptography and Network Security Principles and Practice(7th)

    9. Public-Key Cryptography and RSA 10. Other Public-Key Cryptosystems 11. Cryptographic Hash Functions 12. Message Authentication Codes 13. Digital Signatures 14. Key Management and Distribution ...

    Network Security: Private Communication in a Public World, Second Edition

    Public Key Cryptography Section 2.6. Hash Algorithms Section 2.7. Homework Chapter 3. Secret Key Cryptography Section 3.1. Introduction Section 3.2. Generic Block Encryption Section 3.3. ...

    Cryptograhpy Theory and Practice 第三版

    The second part contains the following material: Chapter 4 concerns the RSA Public-key Cryptosystem, together w ith a considerable amount of background on number-theoretic topics such as primality ...

    HIME 系列加密lib

    - A cryptography toolkit for Windows with public key and secret key encryption, data security and digital signatures with one-way secure hash functions. - Public (asymmetric) key encryption and ...

    Hacking.Secret.Ciphers.with.Python.B00WOY87ZU

    Title: Hacking Secret Ciphers with Python Author: Al Sweigart Length: 718 pages Edition: 1 Language: English Publication Date: 2015-04-24 ...Chapter 24 - Public Key Cryptography and the RSA Cipher

    python加密解密库cryptography使用openSSL生成的密匙加密解密

    密匙使用步骤一般是:  1. 私匙签名,发送签名后的数据, 公匙验证。  2.公匙加密,发送加密后的数据,私匙解密。...rsa_public_key.pem 公匙 openssl genrsa -out rsa_private_key.pem 1024 openss

    Mathematics in Computing

    8.5.1 RSA Public Key Cryptosystem 8.5.2 Digital Signatures 8.6 Review Questions 8.7 Summary 9 Coding Theory 9.1 Introduction 9.2 Mathematical Foundations 9.2.1 Groups 9.2.2 Rings 9.2.3 Fields 9.2.4 ...

    The Craft of System Security

    7.13 Public-key cryptography 175 7.14 Encrypting with public key 175 7.15 Digital signatures 176 7.16 Signatures with public key 176 7.17 Diffie-Hellman 179 7.18 The Merkle-Damgard approach 181 ...

    RAPWare EasyCrypt for XE10 (Cracked Dcu)

    Both public/private-key and symmetric key cryptography are supported. It also includes functionality for : digital certificate management using certificate stores, creating and sigining certificates...

Global site tag (gtag.js) - Google Analytics