下面列出了java.security.spec.ECGenParameterSpec#java.security.KeyFactory 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Internal method to create a new key with inherited key parameters.
*
* @param keyValueKey key from which to obtain key value
* @param keyParamsKey key from which to obtain key parameters
* @return new public key having value and parameters
* @throws CertPathValidatorException if keys are not appropriate types
* for this operation
*/
static PublicKey makeInheritedParamsKey(PublicKey keyValueKey,
PublicKey keyParamsKey) throws CertPathValidatorException
{
if (!(keyValueKey instanceof DSAPublicKey) ||
!(keyParamsKey instanceof DSAPublicKey))
throw new CertPathValidatorException("Input key is not " +
"appropriate type for " +
"inheriting parameters");
DSAParams params = ((DSAPublicKey)keyParamsKey).getParams();
if (params == null)
throw new CertPathValidatorException("Key parameters missing");
try {
BigInteger y = ((DSAPublicKey)keyValueKey).getY();
KeyFactory kf = KeyFactory.getInstance("DSA");
DSAPublicKeySpec ks = new DSAPublicKeySpec(y,
params.getP(),
params.getQ(),
params.getG());
return kf.generatePublic(ks);
} catch (GeneralSecurityException e) {
throw new CertPathValidatorException("Unable to generate key with" +
" inherited parameters: " +
e.getMessage(), e);
}
}
@Override
@TargetApi(Build.VERSION_CODES.M)
Cipher cipherForEncryption() throws GeneralSecurityException, IOException {
KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEY_STORE);
keyGenerator.initialize(getKeyGenParameterSpecBuilder(keyName, KeyProperties.BLOCK_MODE_ECB, KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1, invalidatedByBiometricEnrollment)
.build());
keyGenerator.generateKeyPair();
KeyFactory keyFactory = KeyFactory.getInstance(KeyProperties.KEY_ALGORITHM_RSA);
Cipher cipher = createCipher();
cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(keyFactory, keyStore));
return cipher;
}
private PrivateKey extractPrivateKey(InputStream rawKey, char[] passphrase) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
try (InputStreamReader pemReader = new InputStreamReader(rawKey)) {
try (PEMParser pemParser = new PEMParser(pemReader)) {
Object pemObject = pemParser.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair keyPair;
if (pemObject instanceof PrivateKeyInfo) {
return converter.getPrivateKey((PrivateKeyInfo)pemObject);
}
if (pemObject instanceof PEMEncryptedKeyPair) {
PEMEncryptedKeyPair pemEncryptedKeyPair = (PEMEncryptedKeyPair) pemObject;
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase);
keyPair = converter.getKeyPair(pemEncryptedKeyPair.decryptKeyPair(decProv));
} else {
keyPair = converter.getKeyPair((PEMKeyPair) pemObject);
}
KeyFactory keyFac = KeyFactory.getInstance("RSA");
RSAPrivateCrtKeySpec privateKeySpec = keyFac.getKeySpec(keyPair.getPrivate(), RSAPrivateCrtKeySpec.class);
return keyFac.generatePrivate(privateKeySpec);
}
}
}
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec gps = new ECGenParameterSpec ("secp256r1"); // NIST P-256
kpg.initialize(gps);
KeyPair apair = kpg.generateKeyPair();
ECPublicKey apub = (ECPublicKey)apair.getPublic();
ECParameterSpec aspec = apub.getParams();
// could serialize aspec for later use (in compatible JRE)
//
// for test only reuse bogus pubkey, for real substitute values
ECPoint apoint = apub.getW();
BigInteger x = apoint.getAffineX(), y = apoint.getAffineY();
// construct point plus params to pubkey
ECPoint bpoint = new ECPoint (x,y);
ECPublicKeySpec bpubs = new ECPublicKeySpec (bpoint, aspec);
KeyFactory kfa = KeyFactory.getInstance ("EC");
ECPublicKey bpub = (ECPublicKey) kfa.generatePublic(bpubs);
new Ssh2EcdsaSha2NistPublicKey(bpub);
}
@Override
public boolean isSignatureValid(byte[] data, byte[] signature, Pubkey pubkey) {
try {
ECParameterSpec spec = new ECParameterSpec(
EC_CURVE_PARAMETERS.getCurve(),
EC_CURVE_PARAMETERS.getG(),
EC_CURVE_PARAMETERS.getN(),
EC_CURVE_PARAMETERS.getH(),
EC_CURVE_PARAMETERS.getSeed()
);
ECPoint Q = keyToPoint(pubkey.getSigningKey());
KeySpec keySpec = new ECPublicKeySpec(Q, spec);
PublicKey publicKey = KeyFactory.getInstance(ALGORITHM_ECDSA, provider).generatePublic(keySpec);
Signature sig = Signature.getInstance(ALGORITHM_ECDSA, provider);
sig.initVerify(publicKey);
sig.update(data);
return sig.verify(signature);
} catch (GeneralSecurityException e) {
throw new ApplicationException(e);
}
}
private void readPrivateKeyPKCS1PEM(String privateKeyPath) throws IOException, NoSuchAlgorithmException,
InvalidKeySpecException {
String content = new String(
Files.readAllBytes(Paths.get(privateKeyPath)), Charset.forName("UTF-8"));
content = content.replaceAll("\\n", "").replace(START_RSA_PRIVATE_KEY, "")
.replace(END_RSA_PRIVATE_KEY, "");
byte[] bytes = Base64.getDecoder().decode(content);
DerInputStream derReader = new DerInputStream(bytes);
DerValue[] seq = derReader.getSequence(0);
// skip version seq[0];
BigInteger modulus = seq[1].getBigInteger();
BigInteger publicExp = seq[2].getBigInteger();
BigInteger privateExp = seq[3].getBigInteger();
BigInteger prime1 = seq[4].getBigInteger();
BigInteger prime2 = seq[5].getBigInteger();
BigInteger exp1 = seq[6].getBigInteger();
BigInteger exp2 = seq[7].getBigInteger();
BigInteger crtCoef = seq[8].getBigInteger();
RSAPrivateCrtKeySpec keySpec =
new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
privateKey = keyFactory.generatePrivate(keySpec);
}
public Key engineGetKey(String alias, char[] password)
throws NoSuchAlgorithmException, UnrecoverableKeyException {
alias = alias.toLowerCase(Locale.ENGLISH);
if (!privateKeys.containsKey(alias))
return null;
byte[] key = decryptKey((byte[]) privateKeys.get(alias),
charsToBytes(password));
Certificate[] chain = engineGetCertificateChain(alias);
if (chain.length > 0) {
try {
// Private and public keys MUST have the same algorithm.
KeyFactory fact = KeyFactory.getInstance(
chain[0].getPublicKey().getAlgorithm());
return fact.generatePrivate(new PKCS8EncodedKeySpec(key));
} catch (InvalidKeySpecException x) {
throw new UnrecoverableKeyException(x.getMessage());
}
} else
return new SecretKeySpec(key, alias);
}
public PrivateKey LoadPrivateKey(String path, String algorithm)
throws IOException, NoSuchAlgorithmException,
InvalidKeySpecException {
// Read Private Key.
File filePrivateKey = new File(path + "/private.key");
FileInputStream fis = new FileInputStream(path + "/private.key");
byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
fis.read(encodedPrivateKey);
fis.close();
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
encodedPrivateKey);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
return privateKey;
}
/**
* Internal method to create a new key with inherited key parameters.
*
* @param keyValueKey key from which to obtain key value
* @param keyParamsKey key from which to obtain key parameters
* @return new public key having value and parameters
* @throws CertPathValidatorException if keys are not appropriate types
* for this operation
*/
static PublicKey makeInheritedParamsKey(PublicKey keyValueKey,
PublicKey keyParamsKey) throws CertPathValidatorException
{
if (!(keyValueKey instanceof DSAPublicKey) ||
!(keyParamsKey instanceof DSAPublicKey))
throw new CertPathValidatorException("Input key is not " +
"appropriate type for " +
"inheriting parameters");
DSAParams params = ((DSAPublicKey)keyParamsKey).getParams();
if (params == null)
throw new CertPathValidatorException("Key parameters missing");
try {
BigInteger y = ((DSAPublicKey)keyValueKey).getY();
KeyFactory kf = KeyFactory.getInstance("DSA");
DSAPublicKeySpec ks = new DSAPublicKeySpec(y,
params.getP(),
params.getQ(),
params.getG());
return kf.generatePublic(ks);
} catch (GeneralSecurityException e) {
throw new CertPathValidatorException("Unable to generate key with" +
" inherited parameters: " +
e.getMessage(), e);
}
}
/**
* Verifies a signature.
*
* @param originalMessage The original message.
* @param signedMessage The signature of the original message.
* @param signingPublicKey The public key corresponding to the private key used to sign the message.
* @return Boolean indicating if the signature is verified.
*/
public boolean verifySignature(
byte[] originalMessage,
byte[] signedMessage,
byte[] signingPublicKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance(cryptographyProperties.getSignatureAlgorithm(), BouncyCastleProvider.PROVIDER_NAME);
KeySpec keySpec = new X509EncodedKeySpec(new SubjectPublicKeyInfo(signatureAlgorithmId, signingPublicKey).getEncoded());
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(cryptographyProperties.getSignatureAlgorithm(), BouncyCastleProvider.PROVIDER_NAME);
signature.initVerify(pubKey);
signature.update(originalMessage);
return signature.verify(signedMessage);
} catch (NoSuchAlgorithmException | NoSuchProviderException
| IOException | InvalidKeySpecException | InvalidKeyException
| SignatureException e) {
return false;
}
}
private KeyPair loadRsaKeys(Path publicFile, Path privateFile)
throws GeneralSecurityException, ReflectiveOperationException,
IOException
{
KeyFactory factory = KeyFactory.getInstance("RSA");
// load public key
PublicKey publicKey;
try(ObjectInputStream in =
new ObjectInputStream(Files.newInputStream(publicFile)))
{
publicKey = factory.generatePublic(new RSAPublicKeySpec(
(BigInteger)in.readObject(), (BigInteger)in.readObject()));
}
// load private key
PrivateKey privateKey;
try(ObjectInputStream in =
new ObjectInputStream(Files.newInputStream(privateFile)))
{
privateKey = factory.generatePrivate(new RSAPrivateKeySpec(
(BigInteger)in.readObject(), (BigInteger)in.readObject()));
}
return new KeyPair(publicKey, privateKey);
}
private PublicKey getPublicKeyFromPrivateEC(DerValue bitString, ECPrivateKey privateKey) throws InvalidKeySpecException, IOException, NoSuchAlgorithmException {
// Build an X.509 DER encoded byte array from the provided bitString
//
// SubjectPublicKeyInfo ::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING
// }
DerValue[] sequence = new DerInputStream(privateKey.getEncoded()).getSequence();
byte[] encodedPublicKey = new DerOutputStream()
.writeValue(new DerValue(Tag.Sequence, new DerOutputStream()
.writeValue(new DerValue(Tag.Sequence, sequence[1].toByteArray()))
.writeValue(new DerValue(Tag.BitString, bitString.toByteArray()))))
.toByteArray();
return KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(encodedPublicKey));
}
public Ssh2DsaPrivateKey(BigInteger p, BigInteger q, BigInteger g,
BigInteger x, BigInteger y) throws SshException {
try {
KeyFactory kf = JCEProvider
.getProviderForAlgorithm(JCEAlgorithms.JCE_DSA) == null ? KeyFactory
.getInstance(JCEAlgorithms.JCE_DSA) : KeyFactory
.getInstance(JCEAlgorithms.JCE_DSA, JCEProvider
.getProviderForAlgorithm(JCEAlgorithms.JCE_DSA));
DSAPrivateKeySpec spec = new DSAPrivateKeySpec(x, p, q, g);
prv = (DSAPrivateKey) kf.generatePrivate(spec);
pub = new Ssh2DsaPublicKey(p, q, g, y);
} catch (Throwable e) {
throw new SshException(e);
}
}
/**
* This method will accept keycloak base URL and realm name. Based on provided values it will
* fetch public key from keycloak.
*
* @param url A string value having keycloak base URL
* @param realm Keycloak realm name
* @return Public key used to verify user access token.
*/
public PublicKey getPublicKeyFromKeyCloak(String url, String realm) {
try {
Map<String, String> valueMap = null;
Decoder urlDecoder = Base64.getUrlDecoder();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
String publicKeyString = requestKeyFromKeycloak(url, realm);
if (publicKeyString != null) {
valueMap = getValuesFromJson(publicKeyString);
if (valueMap != null) {
BigInteger modulus = new BigInteger(1, urlDecoder.decode(valueMap.get(MODULUS)));
BigInteger publicExponent = new BigInteger(1, urlDecoder.decode(valueMap.get(EXPONENT)));
PublicKey key = keyFactory.generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
saveToCache(key);
return key;
}
}
} catch (Exception e) {
ProjectLogger.log(
"KeyCloakRsaKeyFetcher:getPublicKeyFromKeyCloak: Exception occurred with message = "
+ e.getMessage(),
LoggerEnum.ERROR);
}
return null;
}
@Produces
Optional<JWTAuthConfiguration> getOptionalContextInfo() throws NoSuchAlgorithmException, InvalidKeySpecException {
final String pemEncoded = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlivFI8qB4D0y2jy0CfEq" +
"Fyy46R0o7S8TKpsx5xbHKoU1VWg6QkQm+ntyIv1p4kE1sPEQO73+HY8+Bzs75XwR" +
"TYL1BmR1w8J5hmjVWjc6R2BTBGAYRPFRhor3kpM6ni2SPmNNhurEAHw7TaqszP5e" +
"UF/F9+KEBWkwVta+PZ37bwqSE4sCb1soZFrVz/UT/LF4tYpuVYt3YbqToZ3pZOZ9" +
"AX2o1GCG3xwOjkc4x0W7ezbQZdC9iftPxVHR8irOijJRRjcPDtA6vPKpzLl6CyYn" +
"sIYPd99ltwxTHjr3npfv/3Lw50bAkbT4HeLFxTx4flEoZLKO/g0bAoV2uqBhkA9x" +
"nQIDAQAB";
byte[] encodedBytes = Base64.getDecoder().decode(pemEncoded);
final X509EncodedKeySpec spec = new X509EncodedKeySpec(encodedBytes);
final KeyFactory kf = KeyFactory.getInstance("RSA");
final RSAPublicKey pk = (RSAPublicKey) kf.generatePublic(spec);
return Optional.of(JWTAuthConfiguration.authConfiguration(pk, "https://server.example.com", false));
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
setProvider(Security.getProvider("SunEC"));
EC_KEY_GENERATOR = KeyPairGenerator.getInstance("EC", _provider);
Path byte_location = Paths.get("src/test/java/com/microsoft/azure/keyvault/cryptography/test/resources/byte_array.bin");
CEK = Files.readAllBytes(byte_location);
FACTORY = KeyFactory.getInstance("EC", _provider);
DIGEST_256 = MessageDigest.getInstance("SHA-256");
DIGEST_384 = MessageDigest.getInstance("SHA-384");
DIGEST_512 = MessageDigest.getInstance("SHA-512");
CURVE_TO_DIGEST = ImmutableMap.<JsonWebKeyCurveName, MessageDigest>builder()
.put(JsonWebKeyCurveName.P_256, DIGEST_256)
.put(JsonWebKeyCurveName.P_384, DIGEST_384)
.put(JsonWebKeyCurveName.P_521, DIGEST_512)
.put(JsonWebKeyCurveName.P_256K, DIGEST_256)
.build();
//JsonWebKeyCurveName.SECP256K1)
CURVE_LIST = Arrays.asList(JsonWebKeyCurveName.P_256, JsonWebKeyCurveName.P_384, JsonWebKeyCurveName.P_521, JsonWebKeyCurveName.P_256K);
}
@Test
public void testValidKeyPairWithDifferentAlgorithmNames() throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException, CryptoException, InvalidKeySpecException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDSA", BC);
keyPairGenerator.initialize(new ECGenParameterSpec("prime256v1"), SecureRandom.getInstance("SHA1PRNG"));
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// private key has algorithm "ECDSA" (because it was generated by BC)
PrivateKey privateKey = keyPair.getPrivate();
// now convert public key to standard JCE object (so it has algorithm name "EC" instead of "ECDSA")
PublicKey publicKey = KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(keyPair.getPublic().getEncoded()));
assertTrue(KeyPairUtil.validKeyPair(privateKey, publicKey));
}
static DHECredentials valueOf(NamedGroup ng,
byte[] encodedPublic) throws IOException, GeneralSecurityException {
if (ng.type != NamedGroupType.NAMED_GROUP_FFDHE) {
throw new RuntimeException(
"Credentials decoding: Not FFDHE named group");
}
if (encodedPublic == null || encodedPublic.length == 0) {
return null;
}
DHParameterSpec params = (DHParameterSpec)ng.getParameterSpec();
if (params == null) {
return null;
}
KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
DHPublicKeySpec spec = new DHPublicKeySpec(
new BigInteger(1, encodedPublic),
params.getP(), params.getG());
DHPublicKey publicKey =
(DHPublicKey)kf.generatePublic(spec);
return new DHECredentials(publicKey, ng);
}
public static PublicKey createKeyFromString(String str, byte[] bArr) {
try {
byte[] decode = Base64.decode(str, 0);
int readInt = readInt(decode, 0);
byte[] obj = new byte[readInt];
System.arraycopy(decode, 4, obj, 0, readInt);
BigInteger bigInteger = new BigInteger(1, obj);
int readInt2 = readInt(decode, readInt + 4);
byte[] obj2 = new byte[readInt2];
System.arraycopy(decode, readInt + 8, obj2, 0, readInt2);
BigInteger bigInteger2 = new BigInteger(1, obj2);
decode = MessageDigest.getInstance("SHA-1").digest(decode);
bArr[0] = (byte) 0;
System.arraycopy(decode, 0, bArr, 1, 4);
return KeyFactory.getInstance("RSA").generatePublic(
new RSAPublicKeySpec(bigInteger, bigInteger2));
}
catch (Throwable e) {
throw new RuntimeException(e);
}
}
/**
* from <type><space><base64data><space><comment> to public key
*/
private static PublicKey toPublicKey(String sshPublicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
String[] line = sshPublicKey.trim().split(" ", 3);
String type = line[0];
String content = line[1];
ByteBuffer buf = ByteBuffer.wrap(Base64.getDecoder().decode(content));
// format of decoded content is: <type><keyparams>
// where type and each param is a DER string
String decodedType = new String(readDERString(buf));
if (!decodedType.equals(type)) {
throw new IllegalArgumentException("expected " + type + ", got " + decodedType);
}
if (type.equals("ssh-rsa")) {
BigInteger e = new BigInteger(readDERString(buf));
BigInteger y = new BigInteger(readDERString(buf));
return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(y, e));
}
throw new InvalidKeySpecException("Unknown key type '" + type + "'");
}
@Override
public void generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
// https://github.com/bcgit/bc-java/blob/53d17ef99e30c6bd49e6eec9235e3eefca6a222d/pkix/src/test/java/org/bouncycastle/cert/test/CertTest.java
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
"b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16));
RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec(new BigInteger(
"b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger(
"9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger(
"c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger(
"b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger(
"b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));
KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
setPrivateKey(fact.generatePrivate(privKeySpec));
setPublicKey(fact.generatePublic(pubKeySpec));
}
public static RSAPublicKey decodeRSAPublicKey(String key, ExceptionInterceptor interceptor) throws SQLException {
try {
if (key == null) {
throw new SQLException("key parameter is null");
}
int offset = key.indexOf("\n") + 1;
int len = key.indexOf("-----END PUBLIC KEY-----") - offset;
// TODO: use standard decoders with Java 6+
byte[] certificateData = Base64Decoder.decode(key.getBytes(), offset, len);
X509EncodedKeySpec spec = new X509EncodedKeySpec(certificateData);
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPublicKey) kf.generatePublic(spec);
} catch (Exception ex) {
throw SQLError.createSQLException("Unable to decode public key", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, ex, interceptor);
}
}
private PublicKey getRevocationPublicKey(String str) throws EnrollmentException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {
if (Utils.isNullOrEmpty(str)) {
throw new EnrollmentException("fabric-ca-server did not return 'issuerPublicKey' in the response from " + HFCA_IDEMIXCRED);
}
String pem = new String(Base64.getDecoder().decode(str));
byte[] der = convertPemToDer(pem);
return KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(der));
}
/**
* 08-13 16:50:39.352: W/System.err(26987):
* java.security.spec.InvalidKeySpecException: java.lang.RuntimeException:
* error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
* @param content
* @param privateKey
* @return
*/
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
Base64.decode(privateKey));
KeyFactory keyf;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
keyf = KeyFactory.getInstance("RSA", "BC");
}else {
keyf = KeyFactory.getInstance(ALGORITHM);//rsa
}
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature
.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(DEFAULT_CHARSET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static KeyFactory getInstance(final String provider) throws NoSuchProviderException {
try {
return KeyFactory.getInstance(ALGORITHM, provider);
} catch (NoSuchAlgorithmException ex) {
throw new AssertionError(algorithmAssertionMsg, ex);
}
}
private static int copy(int testnum) throws Exception {
if (ks == null) {
ks = KeyStore.getInstance(KS_TYPE, provider);
ks.load(null, tokenPwd);
}
KeyFactory kf = KeyFactory.getInstance("RSA", provider);
PrivateKey pkSession = (PrivateKey)kf.translateKey(pk3);
System.out.println("pkSession = " + pkSession);
ks.setKeyEntry("pkSession", pkSession, null, chain3);
KeyStore.PrivateKeyEntry pke =
(KeyStore.PrivateKeyEntry)ks.getEntry("pkSession", null);
System.out.println("pkSession = " + pke.getPrivateKey());
Certificate[] chain = pke.getCertificateChain();
if (chain.length != chain3.length) {
throw new SecurityException("received chain not correct length");
}
for (int i = 0; i < chain.length; i++) {
if (!chain[i].equals(chain3[i])) {
throw new SecurityException("received chain not equal");
}
}
System.out.println("test " + testnum++ + " passed");
return testnum;
}
private static PublicKey generatePublicKeyFromString(String key, String algorithm) {
PublicKey publicKey = null;
if(key.length()>1){
key = cleanKey(key);
byte[] keyByteArray = java.util.Base64.getDecoder().decode(key);
try {
KeyFactory kf = KeyFactory.getInstance(algorithm);
EncodedKeySpec keySpec = new X509EncodedKeySpec(keyByteArray);
publicKey = kf.generatePublic(keySpec);
} catch (Exception e) {
Output.outputError(e.getMessage());
}
}
return publicKey;
}
/**
* 还原私钥,PKCS8EncodedKeySpec 用于构建私钥的规范
*
* @param keyBytes
* @return
*/
private static PrivateKey loadPrivateKey(byte[] keyBytes) {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
keyBytes);
try {
KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateKey = factory
.generatePrivate(pkcs8EncodedKeySpec);
return privateKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* RSA验签名检查
* @param content 待签名数据
* @param sign 签名值
* @param ali_public_key 支付宝公钥
* @param input_charset 编码格式
* @return 布尔值
*/
public static boolean verify(String content, String sign, String ali_public_key, String input_charset)
{
try
{
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode(ali_public_key);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature
.getInstance(SIGN_ALGORITHMS);
signature.initVerify(pubKey);
signature.update( content.getBytes(input_charset) );
boolean bverify = signature.verify( Base64.decode(sign) );
return bverify;
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
public static byte[] encryptByPrivateKey(byte[] data, byte[] keyBytes)throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
// ����ݼ���
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(data);
}