use of com.github.zhenwei.core.crypto.params.RSAPrivateCrtKeyParameters in project LinLong-Java by zhenwei1108.
the class OpenSSHPrivateKeyUtil method encodePrivateKey.
/**
* Encode a cipher parameters into an OpenSSH private key. This does not add headers like
* ----BEGIN RSA PRIVATE KEY----
*
* @param params the cipher parameters.
* @return a byte array
*/
public static byte[] encodePrivateKey(AsymmetricKeyParameter params) throws IOException {
if (params == null) {
throw new IllegalArgumentException("param is null");
}
if (params instanceof RSAPrivateCrtKeyParameters) {
PrivateKeyInfo pInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(params);
return pInfo.parsePrivateKey().toASN1Primitive().getEncoded();
} else if (params instanceof ECPrivateKeyParameters) {
PrivateKeyInfo pInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(params);
return pInfo.parsePrivateKey().toASN1Primitive().getEncoded();
} else if (params instanceof DSAPrivateKeyParameters) {
DSAPrivateKeyParameters dsaPrivKey = (DSAPrivateKeyParameters) params;
DSAParameters dsaParams = dsaPrivKey.getParameters();
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(new ASN1Integer(0));
vec.add(new ASN1Integer(dsaParams.getP()));
vec.add(new ASN1Integer(dsaParams.getQ()));
vec.add(new ASN1Integer(dsaParams.getG()));
// public key = g.modPow(x, p);
BigInteger pubKey = dsaParams.getG().modPow(dsaPrivKey.getX(), dsaParams.getP());
vec.add(new ASN1Integer(pubKey));
vec.add(new ASN1Integer(dsaPrivKey.getX()));
try {
return new DERSequence(vec).getEncoded();
} catch (Exception ex) {
throw new IllegalStateException("unable to encode DSAPrivateKeyParameters " + ex.getMessage());
}
} else if (params instanceof Ed25519PrivateKeyParameters) {
Ed25519PublicKeyParameters publicKeyParameters = ((Ed25519PrivateKeyParameters) params).generatePublicKey();
SSHBuilder builder = new SSHBuilder();
builder.writeBytes(AUTH_MAGIC);
// cipher name
builder.writeString("none");
// KDF name
builder.writeString("none");
// KDF options
builder.writeString("");
// Number of keys
builder.u32(1);
{
byte[] pkEncoded = OpenSSHPublicKeyUtil.encodePublicKey(publicKeyParameters);
builder.writeBlock(pkEncoded);
}
{
SSHBuilder pkBuild = new SSHBuilder();
int checkint = CryptoServicesRegistrar.getSecureRandom().nextInt();
pkBuild.u32(checkint);
pkBuild.u32(checkint);
pkBuild.writeString("ssh-ed25519");
// Public key (as part of private key pair)
byte[] pubKeyEncoded = publicKeyParameters.getEncoded();
pkBuild.writeBlock(pubKeyEncoded);
// The private key in SSH is 64 bytes long and is the concatenation of the private and the public keys
pkBuild.writeBlock(Arrays.concatenate(((Ed25519PrivateKeyParameters) params).getEncoded(), pubKeyEncoded));
// Comment for this private key (empty)
pkBuild.writeString("");
builder.writeBlock(pkBuild.getPaddedBytes());
}
return builder.getBytes();
}
throw new IllegalArgumentException("unable to convert " + params.getClass().getName() + " to openssh private key");
}
Aggregations