You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
2.6 KiB
89 lines
2.6 KiB
package helper; |
|
|
|
import java.io.ByteArrayOutputStream; |
|
import java.io.IOException; |
|
import java.io.InputStream; |
|
import java.nio.charset.StandardCharsets; |
|
import java.security.PrivateKey; |
|
import java.security.PublicKey; |
|
import java.util.regex.Matcher; |
|
import java.util.regex.Pattern; |
|
|
|
/** |
|
* @author richie |
|
* @version 10.0 |
|
* Created by richie on 2018-12-03 |
|
*/ |
|
public class KeyReader { |
|
|
|
private static final int TW_MB = 32 * 1024; |
|
|
|
private static final Pattern PUBLIC_PATTERN = Pattern.compile("-----BEGIN PUBLIC KEY-----([\\s\\S]*?)-----END PUBLIC KEY-----"); |
|
private static final Pattern PRIVATE_PATTERN = Pattern.compile("-----BEGIN PRIVATE KEY-----([\\s\\S]*?)-----END PRIVATE KEY-----"); |
|
|
|
private static PrivateKey privateKey = null; |
|
private static PublicKey publicKey = null; |
|
|
|
static { |
|
try { |
|
String text = readFileContext(); |
|
privateKey = RSAUtils.string2PrivateKey(getMatchedText(text, PRIVATE_PATTERN)); |
|
publicKey = RSAUtils.string2PublicKey(getMatchedText(text, PUBLIC_PATTERN)); |
|
} catch (Exception e) { |
|
LoggerFactory.getLogger().error(e.getMessage(), e); |
|
} |
|
} |
|
|
|
public static PrivateKey getPrivateKey() { |
|
return privateKey; |
|
} |
|
|
|
public static PublicKey getPublicKey() { |
|
return publicKey; |
|
} |
|
|
|
private static String readFileContext() { |
|
InputStream in = KeyReader.class.getResourceAsStream("/key.txt"); |
|
byte[] bytes = inputStream2Bytes(in); |
|
return new String(bytes, StandardCharsets.UTF_8); |
|
} |
|
|
|
private static String getMatchedText(String text, Pattern pattern){ |
|
Matcher m = pattern.matcher(text); |
|
if (m.find()){ |
|
return m.group(1).trim(); |
|
} |
|
return ""; |
|
} |
|
|
|
private static byte[] inputStream2Bytes(InputStream in) { |
|
if (in == null) { |
|
return new byte[0]; |
|
} |
|
byte[] temp = new byte[TW_MB]; |
|
ByteArrayOutputStream bi = new ByteArrayOutputStream(); |
|
try { |
|
int count; |
|
while ((count = in.read(temp)) > 0) { |
|
byte[] b4Add; |
|
if (temp.length == count) { |
|
b4Add = temp; |
|
} else { |
|
b4Add = ArrayUtils.subarray(temp, 0, count); |
|
} |
|
bi.write(b4Add); |
|
} |
|
} catch (IOException e) { |
|
LoggerFactory.getLogger().error(e.getMessage(), e); |
|
} finally { |
|
try { |
|
in.close(); |
|
} catch (IOException e) { |
|
LoggerFactory.getLogger().error(e.getMessage(), e); |
|
} |
|
} |
|
|
|
return bi.toByteArray(); |
|
} |
|
|
|
}
|
|
|