use of org.bouncycastle.util.io.pem.PemHeader in project XobotOS by xamarin.
the class MiscPEMGenerator method createPemObject.
private PemObject createPemObject(Object obj, String algorithm, char[] password, SecureRandom random) throws IOException {
if (obj instanceof KeyPair) {
return createPemObject(((KeyPair) obj).getPrivate(), algorithm, password, random);
}
String type = null;
byte[] keyData = null;
if (obj instanceof RSAPrivateCrtKey) {
type = "RSA PRIVATE KEY";
RSAPrivateCrtKey k = (RSAPrivateCrtKey) obj;
RSAPrivateKeyStructure keyStruct = new RSAPrivateKeyStructure(k.getModulus(), k.getPublicExponent(), k.getPrivateExponent(), k.getPrimeP(), k.getPrimeQ(), k.getPrimeExponentP(), k.getPrimeExponentQ(), k.getCrtCoefficient());
// convert to bytearray
keyData = keyStruct.getEncoded();
} else if (obj instanceof DSAPrivateKey) {
type = "DSA PRIVATE KEY";
DSAPrivateKey k = (DSAPrivateKey) obj;
DSAParams p = k.getParams();
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERInteger(0));
v.add(new DERInteger(p.getP()));
v.add(new DERInteger(p.getQ()));
v.add(new DERInteger(p.getG()));
BigInteger x = k.getX();
BigInteger y = p.getG().modPow(x, p.getP());
v.add(new DERInteger(y));
v.add(new DERInteger(x));
keyData = new DERSequence(v).getEncoded();
} else if (obj instanceof PrivateKey && "ECDSA".equals(((PrivateKey) obj).getAlgorithm())) {
type = "EC PRIVATE KEY";
PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(ASN1Object.fromByteArray(((PrivateKey) obj).getEncoded()));
keyData = privInfo.getPrivateKey().getEncoded();
}
if (type == null || keyData == null) {
// TODO Support other types?
throw new IllegalArgumentException("Object type not supported: " + obj.getClass().getName());
}
String dekAlgName = Strings.toUpperCase(algorithm);
// Note: For backward compatibility
if (dekAlgName.equals("DESEDE")) {
dekAlgName = "DES-EDE3-CBC";
}
int ivLength = dekAlgName.startsWith("AES-") ? 16 : 8;
byte[] iv = new byte[ivLength];
random.nextBytes(iv);
byte[] encData = PEMUtilities.crypt(true, provider, keyData, password, dekAlgName, iv);
List headers = new ArrayList(2);
headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));
return new PemObject(type, headers, encData);
}
Aggregations