com.hfg.security.RSAUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of com_hfg Show documentation
Show all versions of com_hfg Show documentation
com.hfg xml, html, svg, and bioinformatics utility library
package com.hfg.security;
import javax.crypto.Cipher;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.X509EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
//------------------------------------------------------------------------------
/**
* RSA-related functions.
*
* @author J. Alex Taylor, hairyfatguy.com
*/
//------------------------------------------------------------------------------
// com.hfg XML/HTML Coding Library
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// J. Alex Taylor, President, Founder, CEO, COO, CFO, OOPS hairyfatguy.com
// [email protected]
//------------------------------------------------------------------------------
public class RSAUtil
{
private static final String ALGORITHM = "RSA";
private static int sDefaultKeySize = 2048;
//--------------------------------------------------------------------------
public static KeyPair generateKeyPair(File inOutputDir)
{
return generateKeyPair(inOutputDir, sDefaultKeySize);
}
//--------------------------------------------------------------------------
public static KeyPair generateKeyPair(File inOutputDir, int inKeySize)
{
KeyPair keyPair;
try
{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keyGen.initialize(inKeySize, random);
keyPair = keyGen.generateKeyPair();
PrivateKey priv = keyPair.getPrivate();
PublicKey pub = keyPair.getPublic();
// Save the public key in a file
File publicKeyFile = new File(inOutputDir, "rsa.pub");
byte[] key = pub.getEncoded();
FileOutputStream keyfos = new FileOutputStream(publicKeyFile);
keyfos.write(key);
keyfos.close();
// Set permissions
publicKeyFile.setReadable(true);
publicKeyFile.setWritable(false, false);
publicKeyFile.setWritable(true, true);
publicKeyFile.setExecutable(false, false);
// Save the private key in a file
File privateKeyFile = new File(inOutputDir, "rsa.key");
key = priv.getEncoded();
keyfos = new FileOutputStream(privateKeyFile);
keyfos.write(key);
keyfos.close();
// Set strict user-only permissions
privateKeyFile.setReadable(false, false);
privateKeyFile.setReadable(true, true);
privateKeyFile.setWritable(false, false);
privateKeyFile.setWritable(true, true);
privateKeyFile.setExecutable(false, false);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return keyPair;
}
//--------------------------------------------------------------------------
public static byte[] signData(PrivateKey inPrivateKey, byte[] inData)
{
return signData(inPrivateKey, new ByteArrayInputStream(inData));
}
//--------------------------------------------------------------------------
public static byte[] signData(PrivateKey inPrivateKey, InputStream inData)
{
byte[] sig;
try
{
try
{
Signature rsa = Signature.getInstance("SHA1withRSA");
rsa.initSign(inPrivateKey);
byte[] buffer = new byte[1024];
int len;
while (inData.available() != 0)
{
len = inData.read(buffer);
rsa.update(buffer, 0, len);
}
sig = rsa.sign();
}
finally
{
if (inData != null) inData.close();
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return sig;
}
//--------------------------------------------------------------------------
public static boolean verifySignature(PublicKey inPublicKey, byte[] inData, byte[] inSignature)
{
return verifySignature(inPublicKey, new ByteArrayInputStream(inData), inSignature);
}
//--------------------------------------------------------------------------
public static boolean verifySignature(PublicKey inPublicKey, InputStream inData, byte[] inSignature)
{
boolean result = false;
try
{
try
{
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(inPublicKey);
byte[] buffer = new byte[1024];
int len;
while (inData.available() != 0)
{
len = inData.read(buffer);
sig.update(buffer, 0, len);
}
result = sig.verify(inSignature);
}
finally
{
if (inData != null) inData.close();
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return result;
}
//--------------------------------------------------------------------------
public static PublicKey readPublicKey(File inX509EncodedPublicKeyFile)
{
byte[] encKey;
try
{
FileInputStream keyfis = new FileInputStream(inX509EncodedPublicKeyFile);
encKey = new byte[keyfis.available()];
keyfis.read(encKey);
keyfis.close();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return readPublicKey(encKey);
}
//--------------------------------------------------------------------------
public static PublicKey readPublicKey(InputStream inX509EncodedPublicKeyStream)
{
byte[] encKey;
try
{
try
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inX509EncodedPublicKeyStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, len);
}
outStream.close();
encKey = outStream.toByteArray();
}
finally
{
inX509EncodedPublicKeyStream.close();
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return readPublicKey(encKey);
}
//--------------------------------------------------------------------------
public static PublicKey readPublicKey(byte[] inX509EncodedPublicKey)
{
PublicKey pubKey;
try
{
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(inX509EncodedPublicKey);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
pubKey = keyFactory.generatePublic(pubKeySpec);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return pubKey;
}
//--------------------------------------------------------------------------
public static PrivateKey readPrivateKey(File inPKCS8EncodedPrivateKeyFile)
{
byte[] encKey;
try
{
FileInputStream keyfis = new FileInputStream(inPKCS8EncodedPrivateKeyFile);
encKey = new byte[keyfis.available()];
keyfis.read(encKey);
keyfis.close();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return readPrivateKey(encKey);
}
//--------------------------------------------------------------------------
public static PrivateKey readPrivateKey(InputStream inPKCS8EncodedPrivateKeyStream)
{
byte[] encKey = null;
if (inPKCS8EncodedPrivateKeyStream != null)
{
try
{
try
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inPKCS8EncodedPrivateKeyStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, len);
}
outStream.close();
encKey = outStream.toByteArray();
}
finally
{
inPKCS8EncodedPrivateKeyStream.close();
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
return readPrivateKey(encKey);
}
//--------------------------------------------------------------------------
public static PrivateKey readPrivateKey(byte[] inPKCS8EncodedPrivateKey)
{
PrivateKey privKey = null;
if (inPKCS8EncodedPrivateKey != null)
{
try
{
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(inPKCS8EncodedPrivateKey);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
privKey = keyFactory.generatePrivate(keySpec);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
return privKey;
}
//--------------------------------------------------------------------------
public static byte[] encrypt(String inTextToEncrypt, PublicKey inPublicKey)
throws Exception
{
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, inPublicKey);
byte[] inBytesToEncrypt = inTextToEncrypt.getBytes(StandardCharsets.UTF_8);
byte[] encryptedBytes = cipher.doFinal(inBytesToEncrypt);
return encryptedBytes;
}
//--------------------------------------------------------------------------
public static byte[] decrypt(byte[] inBytesToDecrypt, PrivateKey inPrivateKey)
throws Exception
{
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, inPrivateKey);
byte[] decryptedBytes = cipher.doFinal(inBytesToDecrypt);
return decryptedBytes;
}
}