use of com.github.zhenwei.core.asn1.ASN1Object in project jruby-openssl by jruby.
the class PEMInputOutput method readPrivateKey.
/**
* c: PEM_read_PrivateKey + PEM_read_bio_PrivateKey
* CAUTION: KeyPair#getPublic() may be null.
*/
public static KeyPair readPrivateKey(final Reader in, char[] passwd) throws PasswordRequiredException, IOException {
final String BEG_STRING_ECPRIVATEKEY = BEF_G + PEM_STRING_ECPRIVATEKEY;
final String BEG_STRING_PKCS8INF = BEF_G + PEM_STRING_PKCS8INF;
final String BEG_STRING_PKCS8 = BEF_G + PEM_STRING_PKCS8;
final BufferedReader reader = makeBuffered(in);
String line;
while ((line = reader.readLine()) != null) {
if (line.indexOf(BEG_STRING_RSA) != -1) {
try {
return readKeyPair(reader, passwd, "RSA", BEF_E + PEM_STRING_RSA);
} catch (Exception e) {
throw mapReadException("problem creating RSA private key: ", e);
}
} else if (line.indexOf(BEG_STRING_DSA) != -1) {
try {
return readKeyPair(reader, passwd, "DSA", BEF_E + PEM_STRING_DSA);
} catch (Exception e) {
throw mapReadException("problem creating DSA private key: ", e);
}
} else if (line.indexOf(BEG_STRING_ECPRIVATEKEY) != -1) {
try {
return readKeyPair(reader, passwd, "ECDSA", BEF_E + PEM_STRING_ECPRIVATEKEY);
} catch (Exception e) {
throw mapReadException("problem creating DSA private key: ", e);
}
} else if (line.indexOf(BEG_STRING_PKCS8INF) != -1) {
try {
byte[] bytes = readBase64Bytes(reader, BEF_E + PEM_STRING_PKCS8INF);
PrivateKeyInfo info = PrivateKeyInfo.getInstance(bytes);
String type = getPrivateKeyTypeFromObjectId(info.getPrivateKeyAlgorithm().getAlgorithm());
return org.jruby.ext.openssl.impl.PKey.readPrivateKey(((ASN1Object) info.parsePrivateKey()).getEncoded(ASN1Encoding.DER), type);
} catch (Exception e) {
throw mapReadException("problem creating private key: ", e);
}
} else if (line.indexOf(BEG_STRING_PKCS8) != -1) {
try {
byte[] bytes = readBase64Bytes(reader, BEF_E + PEM_STRING_PKCS8);
EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.getInstance(bytes);
AlgorithmIdentifier algId = eIn.getEncryptionAlgorithm();
PrivateKey privKey;
if (algId.getAlgorithm().toString().equals("1.2.840.113549.1.5.13")) {
// PBES2
privKey = derivePrivateKeyPBES2(eIn, algId, passwd);
} else {
privKey = derivePrivateKeyPBES1(eIn, algId, passwd);
}
return new KeyPair(null, privKey);
} catch (Exception e) {
throw mapReadException("problem creating private key: ", e);
}
}
}
return null;
}
use of com.github.zhenwei.core.asn1.ASN1Object in project tbd-studio-se by Talend.
the class MongoDBConnectionUtil method buildSSLContext_PEM.
private static SSLContext buildSSLContext_PEM(String _keystore, String _keystorePass, String _truststore, String _truststorePass, SSLContext sslContext) {
SSLContext context = null;
final String pubCertEndDelimiter = "-----END CERTIFICATE-----";
final String privateKeyStartDelimiter = "-----BEGIN PRIVATE KEY-----";
final String privateKeyEndDelimiter = "-----END PRIVATE KEY-----";
final String privateKeyRSAStartDelimiter = "-----BEGIN RSA PRIVATE KEY-----";
final String privateKeyRSAEndDelimiter = "-----END RSA PRIVATE KEY-----";
try {
context = SSLContext.getInstance("TLS");
byte[] certAndKey = Files.readAllBytes(Paths.get(new File(_keystore).toURI()));
String[] tokens = new String(certAndKey).split(pubCertEndDelimiter);
byte[] certBytes = tokens[0].concat(pubCertEndDelimiter).getBytes();
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
java.security.cert.Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(certBytes));
//
X509Certificate cert = (X509Certificate) certificate;
PrivateKey key = null;
KeyFactory kf = KeyFactory.getInstance("RSA");
if (tokens[1].contains(privateKeyStartDelimiter)) {
byte[] privatekeyBytes = tokens[1].replace(privateKeyStartDelimiter, "").replace(privateKeyEndDelimiter, "").replace("\r\n", "").replace("\n", "").getBytes();
byte[] decode = Base64.getDecoder().decode(privatekeyBytes);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decode);
key = kf.generatePrivate(spec);
} else if (tokens[1].contains(privateKeyRSAStartDelimiter)) {
byte[] privateKeyBytes = tokens[1].replace(privateKeyRSAStartDelimiter, "").replace(privateKeyRSAEndDelimiter, "").replace("\r\n", "").replace("\n", "").getBytes("UTF-8");
byte[] decodeBytes = Base64.getDecoder().decode(privateKeyBytes);
ASN1Object fromByteArray = ASN1Sequence.fromByteArray(decodeBytes);
RSAPrivateKeyStructure asn1PrivKey = new RSAPrivateKeyStructure((ASN1Sequence) fromByteArray);
RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent());
key = kf.generatePrivate(rsaPrivKeySpec);
}
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
keystore.setCertificateEntry("cert-alias", cert);
keystore.setKeyEntry("key-alias", key, "changeit".toCharArray(), new Certificate[] { cert });
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, "changeit".toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
} catch (Exception e) {
e.printStackTrace();
}
return context;
}
use of com.github.zhenwei.core.asn1.ASN1Object in project LinLong-Java by zhenwei1108.
the class CVCertificate method toASN1Primitive.
/**
* @see com.github.zhenwei.core.asn1.ASN1Object#toASN1Primitive()
*/
public ASN1Primitive toASN1Primitive() {
ASN1EncodableVector v = new ASN1EncodableVector(2);
v.add(certificateBody);
try {
v.add(new DERApplicationSpecific(false, EACTags.STATIC_INTERNAL_AUTHENTIFICATION_ONE_STEP, new DEROctetString(signature)));
} catch (IOException e) {
throw new IllegalStateException("unable to convert signature!");
}
return new DERApplicationSpecific(EACTags.CARDHOLDER_CERTIFICATE, v);
}
use of com.github.zhenwei.core.asn1.ASN1Object in project LinLong-Java by zhenwei1108.
the class OERInputStream method parse.
public ASN1Object parse(OERDefinition.Element element) throws Exception {
switch(element.baseType) {
case SEQ_OF:
{
int l = readLength().intLength();
// This l is the number of bytes that holds the actual length of the sequence of.
byte[] lenEnc = allocateArray(l);
if (Streams.readFully(this, lenEnc) != lenEnc.length) {
throw new IOException("could not read all of count of seq-of values");
}
//
// The actual number of elements encoded into this seq-of.
//
int j = BigIntegers.fromUnsignedByteArray(lenEnc).intValue();
debugPrint(element.appendLabel("(len = " + j + ")"));
ASN1EncodableVector avec = new ASN1EncodableVector();
for (int n = 0; n < j; n++) {
avec.add(parse(element.children.get(0)));
}
return new DERSequence(avec);
}
case SEQ:
{
Sequence sequence = sequence(countOptionalChildTypes(element), element.hasDefaultChildren(), element.extensionsInDefinition);
debugPrint(element.appendLabel(sequence.toString()));
ASN1EncodableVector avec = new ASN1EncodableVector();
for (int t = 0; t < element.children.size(); t++) {
OERDefinition.Element child = element.children.get(t);
if (child.explicit) {
// debugPrint(child.appendLabel("E[" + t + "]"));
avec.add(parse(child));
} else {
if (sequence.hasOptional(element.optionalOrDefaultChildrenInOrder().indexOf(child))) {
// debugPrint(child.appendLabel("O[" + t + "]"));
avec.add(OEROptional.getInstance(parse(child)));
} else {
if (child.getDefaultValue() != null) {
avec.add(child.defaultValue);
debugPrint("Using default.");
} else {
avec.add(absent(child));
}
}
}
}
return new DERSequence(avec);
}
case CHOICE:
{
Choice choice = choice();
debugPrint(element.appendLabel(choice.toString()));
if (choice.isContextSpecific()) {
OERDefinition.Element item = element.children.get(choice.getTag());
return new DERTaggedObject(choice.tag, parse(element.children.get(choice.getTag())));
} else if (choice.isApplicationTagClass()) {
throw new IllegalStateException("Unimplemented tag type");
} else if (choice.isPrivateTagClass()) {
throw new IllegalStateException("Unimplemented tag type");
} else if (choice.isUniversalTagClass()) {
switch(choice.getTag()) {
}
} else {
throw new IllegalStateException("Unimplemented tag type");
}
}
case ENUM:
{
BigInteger bi = enumeration();
debugPrint(element.appendLabel("ENUM(" + bi + ") = " + element.children.get(bi.intValue()).label));
return new ASN1Enumerated(bi);
}
case INT:
{
byte[] data;
BigInteger bi;
//
// Special fixed width cases used for signed and unsigned 8/16/24/32/64 bit numbers.
//
int bytesToRead = element.intBytesForRange();
if (// Fixed width
bytesToRead != 0) {
data = allocateArray(Math.abs(bytesToRead));
Streams.readFully(this, data);
switch(data.length) {
case 1:
bi = BigInteger.valueOf(data[0]);
break;
case 2:
bi = BigInteger.valueOf(Pack.bigEndianToShort(data, 0));
break;
case 4:
bi = BigInteger.valueOf(Pack.bigEndianToInt(data, 0));
break;
case 8:
bi = BigInteger.valueOf(Pack.bigEndianToLong(data, 0));
break;
default:
throw new IllegalStateException("Unknown size");
}
} else if (// INTEGER(0 ... MAX) or INTEGER (0 ... n)
element.isLowerRangeZero()) {
LengthInfo lengthInfo = readLength();
data = allocateArray(lengthInfo.intLength());
Streams.readFully(this, data);
if (data.length == 0) {
bi = BigInteger.ZERO;
} else {
bi = BigIntegers.fromUnsignedByteArray(data);
}
} else {
//
// Classic twos compliment.
//
LengthInfo lengthInfo = readLength();
data = allocateArray(lengthInfo.intLength());
Streams.readFully(this, data);
if (data.length == 0) {
bi = BigInteger.ZERO;
} else {
bi = new BigInteger(data);
}
}
if (debugOutput != null) {
debugPrint(element.appendLabel("INTEGER(" + data.length + " " + bi.toString(16) + ")"));
}
return new ASN1Integer(bi);
}
case OCTET_STRING:
{
byte[] data;
int readSize = 0;
if (element.upperBound != null && element.upperBound.equals(element.lowerBound)) {
// Fixed length there is no range.
readSize = element.upperBound.intValue();
} else {
readSize = readLength().intLength();
}
data = allocateArray(readSize);
if (Streams.readFully(this, data) != readSize) {
throw new IOException("did not read all of " + element.label);
}
if (debugOutput != null) {
debugPrint(element.appendLabel("OCTET STRING (" + data.length + ") = " + Hex.toHexString(data, 0, Math.min(data.length, 32))));
}
return new DEROctetString(data);
}
case UTF8_STRING:
{
// 27.3 and 27.4 a length determinant followed by a number of octets.
byte[] data = allocateArray(readLength().intLength());
if (Streams.readFully(this, data) != data.length) {
throw new IOException("could not read all of utf 8 string");
}
String content = Strings.fromUTF8ByteArray(data);
if (debugOutput != null) {
debugPrint(element.appendLabel("UTF8 String (" + data.length + ") = " + content));
}
return new DERUTF8String(content);
}
case BIT_STRING:
{
byte[] data;
if (element.isFixedLength()) {
data = new byte[element.lowerBound.intValue() / 8];
} else if (BigInteger.ZERO.compareTo(element.upperBound) > 0) {
// Fixed size.
data = allocateArray(element.upperBound.intValue() / 8);
} else {
// Length defined.
data = allocateArray(readLength().intLength() / 8);
}
Streams.readFully(this, data);
if (debugOutput != null) {
StringBuffer sb = new StringBuffer();
sb.append("BIT STRING(" + (data.length * 8) + ") = ");
for (int i = 0; i != data.length; i++) {
byte b = data[i];
for (int t = 0; t < 8; t++) {
sb.append((b & 0x80) > 0 ? "1" : "0");
b <<= 1;
}
}
debugPrint(element.appendLabel(sb.toString()));
}
return new DERBitString(data);
}
case NULL:
debugPrint(element.appendLabel("NULL"));
return DERNull.INSTANCE;
case EXTENSION:
LengthInfo li = readLength();
byte[] value = new byte[li.intLength()];
if (Streams.readFully(this, value) != li.intLength()) {
throw new IOException("could not read all of count of open value in choice (...) ");
}
debugPrint("ext " + li.intLength() + " " + Hex.toHexString(value));
return new DEROctetString(value);
}
throw new IllegalStateException("Unhandled type " + element.baseType);
}
use of com.github.zhenwei.core.asn1.ASN1Object in project laverca by laverca.
the class CmsSignature method bytesToPkcs7SignedData.
/**
* Convert a byte array to a PKCS7 SignedData object
* @param bytes byte array
* @return PKCS7 SignedData object
*/
public static SignedData bytesToPkcs7SignedData(byte[] bytes) {
if (bytes == null) {
throw new IllegalArgumentException("null bytes");
}
ASN1InputStream ais = new ASN1InputStream(bytes);
ASN1Object asn1 = null;
try {
asn1 = ais.readObject();
} catch (IOException ioe) {
throw new IllegalArgumentException("not a pkcs7 signature");
} finally {
try {
ais.close();
} catch (IOException e) {
// Ignore
}
}
ContentInfo ci = ContentInfo.getInstance(asn1);
ASN1ObjectIdentifier typeId = ci.getContentType();
if (!typeId.equals(PKCSObjectIdentifiers.signedData)) {
throw new IllegalArgumentException("not a pkcs7 signature");
}
return SignedData.getInstance(ci.getContent());
}
Aggregations