use of com.github.zhenwei.core.asn1.sec.ECPrivateKey in project spring-vault by spring-projects.
the class KeyFactoriesUnitTests method shouldCreateEcKey.
@Test
void shouldCreateEcKey() throws IOException, GeneralSecurityException {
PemObject key = load("privatekey-ec-256.pem", 1);
KeySpec keySpec = KeyFactories.EC.getKey(key.getContent());
assertThat(keySpec).isInstanceOf(ECPrivateKeySpec.class);
ECPrivateKeySpec ecKeySpec = (ECPrivateKeySpec) keySpec;
assertThat(ecKeySpec.getS()).isEqualTo("80321543313819895612774489145376520718294627432743956845606752593828296924959");
// Verify against BouncyCastle parser
ECPrivateKey ecPrivateKey = ECPrivateKey.getInstance(key.getContent());
ASN1Primitive parameters = ecPrivateKey.getParameters();
X9ECParameters curveParameter = X962NamedCurves.getByOID((ASN1ObjectIdentifier) parameters);
assertThat(ecKeySpec.getParams().getCofactor()).isEqualTo(curveParameter.getCurve().getCofactor().intValue());
assertThat(ecKeySpec.getParams().getOrder()).isEqualTo(curveParameter.getCurve().getOrder());
assertThat(ecKeySpec.getParams().getCurve().getA()).isEqualTo(curveParameter.getCurve().getA().toBigInteger());
assertThat(ecKeySpec.getParams().getCurve().getB()).isEqualTo(curveParameter.getCurve().getB().toBigInteger());
}
use of com.github.zhenwei.core.asn1.sec.ECPrivateKey in project robovm by robovm.
the class PrivateKeyFactory method createKey.
/**
* Create a private key parameter from the passed in PKCS8 PrivateKeyInfo object.
*
* @param keyInfo the PrivateKeyInfo object containing the key material
* @return a suitable private key parameter
* @throws IOException on an error decoding the key
*/
public static AsymmetricKeyParameter createKey(PrivateKeyInfo keyInfo) throws IOException {
AlgorithmIdentifier algId = keyInfo.getPrivateKeyAlgorithm();
if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption)) {
RSAPrivateKey keyStructure = RSAPrivateKey.getInstance(keyInfo.parsePrivateKey());
return new RSAPrivateCrtKeyParameters(keyStructure.getModulus(), keyStructure.getPublicExponent(), keyStructure.getPrivateExponent(), keyStructure.getPrime1(), keyStructure.getPrime2(), keyStructure.getExponent1(), keyStructure.getExponent2(), keyStructure.getCoefficient());
} else // else if (algId.getObjectId().equals(X9ObjectIdentifiers.dhpublicnumber))
if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
DHParameter params = DHParameter.getInstance(algId.getParameters());
ASN1Integer derX = (ASN1Integer) keyInfo.parsePrivateKey();
BigInteger lVal = params.getL();
int l = lVal == null ? 0 : lVal.intValue();
DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);
return new DHPrivateKeyParameters(derX.getValue(), dhParams);
} else // END android-removed
if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_dsa)) {
ASN1Integer derX = (ASN1Integer) keyInfo.parsePrivateKey();
ASN1Encodable de = algId.getParameters();
DSAParameters parameters = null;
if (de != null) {
DSAParameter params = DSAParameter.getInstance(de.toASN1Primitive());
parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
}
return new DSAPrivateKeyParameters(derX.getValue(), parameters);
} else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
X962Parameters params = new X962Parameters((ASN1Primitive) algId.getParameters());
X9ECParameters x9;
if (params.isNamedCurve()) {
ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(params.getParameters());
x9 = X962NamedCurves.getByOID(oid);
if (x9 == null) {
x9 = SECNamedCurves.getByOID(oid);
if (x9 == null) {
x9 = NISTNamedCurves.getByOID(oid);
// BEGIN android-removed
// if (x9 == null)
// {
// x9 = TeleTrusTNamedCurves.getByOID(oid);
// }
// END android-removed
}
}
} else {
x9 = X9ECParameters.getInstance(params.getParameters());
}
ECPrivateKey ec = ECPrivateKey.getInstance(keyInfo.parsePrivateKey());
BigInteger d = ec.getKey();
// TODO We lose any named parameters here
ECDomainParameters dParams = new ECDomainParameters(x9.getCurve(), x9.getG(), x9.getN(), x9.getH(), x9.getSeed());
return new ECPrivateKeyParameters(d, dParams);
} else {
throw new RuntimeException("algorithm identifier in key not recognised");
}
}
use of com.github.zhenwei.core.asn1.sec.ECPrivateKey in project pri-fidoiot by secure-device-onboard.
the class InteropVoucher method doPost.
@Override
protected void doPost() throws Exception {
try {
String pemString = getStringBody();
OwnershipVoucher voucher = null;
UUID guid = null;
PrivateKey signKey = null;
try (StringReader reader = new StringReader(pemString);
PEMParser parser = new PEMParser(reader)) {
for (; ; ) {
Object obj = parser.readPemObject();
if (obj == null) {
break;
}
if (obj instanceof PemObject) {
PemObject pemObj = (PemObject) obj;
if (pemObj.getType().equals("OWNERSHIP VOUCHER")) {
voucher = Mapper.INSTANCE.readValue(pemObj.getContent(), OwnershipVoucher.class);
OwnershipVoucherHeader header = Mapper.INSTANCE.readValue(voucher.getHeader(), OwnershipVoucherHeader.class);
guid = header.getGuid().toUuid();
logger.info("voucher guid: " + guid.toString());
} else if (pemObj.getType().equals("EC PRIVATE KEY")) {
ASN1Sequence seq = ASN1Sequence.getInstance(pemObj.getContent());
// PrivateKeyInfo info = PrivateKeyInfo.getInstance(seq);
// signKey = new JcaPEMKeyConverter().getPrivateKey(info);
ECPrivateKey ecpKey = ECPrivateKey.getInstance(seq);
AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, ecpKey.getParameters());
byte[] serverPkcs8 = new PrivateKeyInfo(algId, ecpKey).getEncoded();
KeyFactory fact = KeyFactory.getInstance("EC", "BC");
signKey = fact.generatePrivate(new PKCS8EncodedKeySpec(serverPkcs8));
} else if (pemObj.getType().equals("RSA PRIVATE KEY")) {
ASN1Sequence seq = ASN1Sequence.getInstance(pemObj.getContent());
PrivateKeyInfo info = PrivateKeyInfo.getInstance(seq);
signKey = new JcaPEMKeyConverter().getPrivateKey(info);
}
}
}
}
// we should have voucher and private key
if (voucher != null) {
logger.info("decoded voucher from pem");
} else {
logger.warn("unable to decode voucher from pem");
getResponse().setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
if (signKey != null) {
logger.info("decoded private key from pem");
} else {
logger.warn("unable to decode private key from pem");
}
CryptoService cs = Config.getWorker(CryptoService.class);
KeyResolver resolver = Config.getWorker(OwnerKeySupplier.class).get();
OwnerPublicKey prevKey = VoucherUtils.getLastOwner(voucher);
String alias = KeyResolver.getAlias(prevKey.getType(), new AlgorithmFinder().getKeySizeType(cs.decodeKey(prevKey)));
Certificate[] certs = resolver.getCertificateChain(alias);
extend(voucher, signKey, certs);
getTransaction();
OnboardingVoucher dbVoucher = getSession().get(OnboardingVoucher.class, guid.toString());
if (dbVoucher == null) {
dbVoucher = new OnboardingVoucher();
dbVoucher.setGuid(guid.toString());
dbVoucher.setData(Mapper.INSTANCE.writeValue(voucher));
dbVoucher.setCreatedOn(new Date(System.currentTimeMillis()));
getSession().save(dbVoucher);
} else {
dbVoucher.setData(Mapper.INSTANCE.writeValue(voucher));
getSession().update(dbVoucher);
}
// save the voucher
// todo: need to do TO0 manually
// write the guid response
byte[] guidResponse = guid.toString().getBytes(StandardCharsets.UTF_8);
getResponse().setContentLength(guidResponse.length);
getResponse().getOutputStream().write(guidResponse);
} catch (Exception e) {
logger.warn("Request failed because of internal server error.");
getResponse().setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
use of com.github.zhenwei.core.asn1.sec.ECPrivateKey in project radixdlt by radixdlt.
the class RadixKeyStore method encodePrivKey.
/**
* Encodes the specified raw secp256k1 private key into an ASN.1 encoded <a
* href="https://tools.ietf.org/html/rfc5208#section-5">Private Key Info</a> structure.
*
* <p>Note that the encoded key will not include a public key.
*
* @param rawkey The raw secp256k1 private key.
* @return The ASN.1 encoded private key.
* @throws IOException If an error occurs encoding the ASN.1 key.
*/
private static byte[] encodePrivKey(byte[] rawkey) throws IOException {
AlgorithmIdentifier ecSecp256k1 = new AlgorithmIdentifier(OID_EC_ENCRYPTION, OID_SECP256K1_CURVE);
BigInteger key = new BigInteger(1, rawkey);
ECPrivateKey privateKey = new ECPrivateKey(ECKeyPair.BYTES * Byte.SIZE, key, OID_SECP256K1_CURVE);
PrivateKeyInfo pki = new PrivateKeyInfo(ecSecp256k1, privateKey);
return pki.getEncoded();
}
use of com.github.zhenwei.core.asn1.sec.ECPrivateKey in project LinLong-Java by zhenwei1108.
the class PrivateKeyInfoFactory method createPrivateKeyInfo.
/**
* Create a PrivateKeyInfo representation of a private key with attributes.
*
* @param privateKey the key to be encoded into the info object.
* @param attributes the set of attributes to be included.
* @return the appropriate PrivateKeyInfo
* @throws IOException on an error encoding the key
*/
public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter privateKey, ASN1Set attributes) throws IOException {
if (privateKey instanceof RSAKeyParameters) {
RSAPrivateCrtKeyParameters priv = (RSAPrivateCrtKeyParameters) privateKey;
return new PrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPrivateKey(priv.getModulus(), priv.getPublicExponent(), priv.getExponent(), priv.getP(), priv.getQ(), priv.getDP(), priv.getDQ(), priv.getQInv()), attributes);
} else if (privateKey instanceof DSAPrivateKeyParameters) {
DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters) privateKey;
DSAParameters params = priv.getParameters();
return new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(params.getP(), params.getQ(), params.getG())), new ASN1Integer(priv.getX()), attributes);
} else if (privateKey instanceof ECPrivateKeyParameters) {
ECPrivateKeyParameters priv = (ECPrivateKeyParameters) privateKey;
ECDomainParameters domainParams = priv.getParameters();
ASN1Encodable params;
int orderBitLength;
if (domainParams == null) {
// Implicitly CA
params = new X962Parameters(DERNull.INSTANCE);
orderBitLength = priv.getD().bitLength();
} else if (domainParams instanceof ECGOST3410Parameters) {
GOST3410PublicKeyAlgParameters gostParams = new GOST3410PublicKeyAlgParameters(((ECGOST3410Parameters) domainParams).getPublicKeyParamSet(), ((ECGOST3410Parameters) domainParams).getDigestParamSet(), ((ECGOST3410Parameters) domainParams).getEncryptionParamSet());
int size;
ASN1ObjectIdentifier identifier;
if (cryptoProOids.contains(gostParams.getPublicKeyParamSet())) {
size = 32;
identifier = CryptoProObjectIdentifiers.gostR3410_2001;
} else {
boolean is512 = priv.getD().bitLength() > 256;
identifier = (is512) ? RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512 : RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256;
size = (is512) ? 64 : 32;
}
byte[] encKey = new byte[size];
extractBytes(encKey, size, 0, priv.getD());
return new PrivateKeyInfo(new AlgorithmIdentifier(identifier, gostParams), new DEROctetString(encKey));
} else if (domainParams instanceof ECNamedDomainParameters) {
params = new X962Parameters(((ECNamedDomainParameters) domainParams).getName());
orderBitLength = domainParams.getN().bitLength();
} else {
X9ECParameters ecP = new X9ECParameters(domainParams.getCurve(), new X9ECPoint(domainParams.getG(), false), domainParams.getN(), domainParams.getH(), domainParams.getSeed());
params = new X962Parameters(ecP);
orderBitLength = domainParams.getN().bitLength();
}
ECPoint q = new FixedPointCombMultiplier().multiply(domainParams.getG(), priv.getD());
// TODO Support point compression
DERBitString publicKey = new DERBitString(q.getEncoded(false));
return new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), new ECPrivateKey(orderBitLength, priv.getD(), publicKey, params), attributes);
} else if (privateKey instanceof X448PrivateKeyParameters) {
X448PrivateKeyParameters key = (X448PrivateKeyParameters) privateKey;
return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X448), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
} else if (privateKey instanceof X25519PrivateKeyParameters) {
X25519PrivateKeyParameters key = (X25519PrivateKeyParameters) privateKey;
return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
} else if (privateKey instanceof Ed448PrivateKeyParameters) {
Ed448PrivateKeyParameters key = (Ed448PrivateKeyParameters) privateKey;
return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
} else if (privateKey instanceof Ed25519PrivateKeyParameters) {
Ed25519PrivateKeyParameters key = (Ed25519PrivateKeyParameters) privateKey;
return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
} else {
throw new IOException("key parameters not recognized");
}
}
Aggregations