알쓸전컴(알아두면 쓸모있는 전자 컴퓨터)

RSA PKCS#1 복호화,Padding 문제 해결 본문

안드로이드

RSA PKCS#1 복호화,Padding 문제 해결

백곳 2019. 1. 5. 20:01

RSA PKCS#1 복호화,Padding 문제 해결


안드로이드 에서 RSA 복호화시 몇몇 문제들로 인해 분석한 내용 입니다.


java에서 PCKS#1 을 복호화 하려면 일반 PC java 에서는


import sun.security.util.DerInputStream;
import sun.security.util.DerValue;


2가지 라이브러리를 사용 하나 android 에서 사용이 안됩니다.


일단 아래  소스가 PKCS#1을 읽기 위한 소스 입니다. 아래 방식으로 읽어 들어 와야 합니다.

package com.arghosttown.arghosttown;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.spec.RSAPrivateCrtKeySpec;

/**
* This code is inspired and taken over from net.auth.core:oauth
* (albeit in a highly stripped variation):
* <p/>
* Source is from http://oauth.googlecode.com/svn/code/java/ which is licensed
* under the APL (http://oauth.googlecode.com/svn/code/java/LICENSE.txt)
* <p/>
* All credits go to the original author (zhang)
*
* @author roland
* @since 30/09/15
*/
public class PKCS1Util {

private PKCS1Util() {
}

public static RSAPrivateCrtKeySpec decodePKCS1(byte[] keyBytes) throws IOException {
DerParser parser = new DerParser(keyBytes);
Asn1Object sequence = parser.read();
sequence.validateSequence();
parser = new DerParser(sequence.getValue());
parser.read();

return new RSAPrivateCrtKeySpec(next(parser), next(parser),
next(parser), next(parser),
next(parser), next(parser),
next(parser), next(parser));
}

// ==========================================================================================

private static BigInteger next(DerParser parser) throws IOException {
return parser.read().getInteger();
}

static class DerParser {

private InputStream in;

DerParser(byte[] bytes) throws IOException {
this.in = new ByteArrayInputStream(bytes);
}

Asn1Object read() throws IOException {
int tag = in.read();

if (tag == -1) {
throw new IOException("Invalid DER: stream too short, missing tag");
}

int length = getLength();
byte[] value = new byte[length];
if (in.read(value) < length) {
throw new IOException("Invalid DER: stream too short, missing value");
}

return new Asn1Object(tag, value);
}

private int getLength() throws IOException {
int i = in.read();
if (i == -1) {
throw new IOException("Invalid DER: length missing");
}

if ((i & ~0x7F) == 0) {
return i;
}

int num = i & 0x7F;
if (i >= 0xFF || num > 4) {
throw new IOException("Invalid DER: length field too big ("
+ i + ")");
}

byte[] bytes = new byte[num];
if (in.read(bytes) < num) {
throw new IOException("Invalid DER: length too short");
}

return new BigInteger(1, bytes).intValue();
}
}

static class Asn1Object {

private final int type;
private final byte[] value;
private final int tag;

public Asn1Object(int tag, byte[] value) {
this.tag = tag;
this.type = tag & 0x1F;
this.value = value;
}

public byte[] getValue() {
return value;
}

BigInteger getInteger() throws IOException {
if (type != 0x02) {
throw new IOException("Invalid DER: object is not integer"); //$NON-NLS-1$
}
return new BigInteger(value);
}

void validateSequence() throws IOException {
if (type != 0x10) {
throw new IOException("Invalid DER: not a sequence");
}
if ((tag & 0x20) != 0x20) {
throw new IOException("Invalid DER: can't parse primitive entity");
}
}
}
}



그리고 아래는 소스의 일부분 입니다,


여기서 pkey 가


String pkey=
"MIIEowIBAAKCAQEAh6OvWa5vAWBTcSosC2AgRMKPb5V9xfBLhj24qIbRaTGMgppe" +
"Ay5y86CuOqI5LQ0caF271815Po934SyxRxgoJtgqk9Zq27rf+5fqa8Dp1qBo+RSS" +
"XuAD0bP0ddIRiIGuJZW4dm7Y95Z89zUzBeAnPM6LCiUc6GxQmWXG9LJK3MsuKw2W" +
"pW7fevLyczfCrnGI8av9KPXr2o2m37HI5ZZibI1UKUmaiAwWAttjpgMKJ4yggMle" +
"wZL6tlehKXgURj6i1HN7WGmjzDK7hRchGDXYozNjS403ZRLTwh0q++V1WC0nGv3B" +
"WQl2U42oINOnn5UN+072NbqfyilexR//hb9tJQIDAQABAoIBAGI0lw7dhq1+aquy" +
"lvUdgf+GxodJuyiHFId7RKlwA0qgf1VIIu02wi+2lK8LKU5/AaRmyUw0DqbHBUrZ" +
"KvmIefm15Q3o3rF8mhL1KNsfb67fsWE2Dcv3cYxxOHvdvqgRDF9WCZpmI10Pbicm" +
"M2z7oC0cdfrAaC+3zJtj3yrns+ArhX8xv2OGXXanWa+Urj6yalkFvopbojYIU0nE" +
"wLJhR8PKoeKPrNMQNEkUmV7fLv3yIN1SJaiYkG4+h6Y5UlKF9B4wFhL2i7RZTssr" +
"+6GoIWaKL1uUK64uxEE/duqKSYNnv6efxTqCoBO4KtFRQ2NHf/NckD4jnr8uGSGw"

의 키입니다.


 byte[] bPrivateKey2 = Base64.decode(pkey.getBytes(),Base64.DEFAULT);

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
KeyFactory keyFactory2 = KeyFactory.getInstance("RSA");
RSAPrivateCrtKeySpec privateKeySpec =PKCS1Util.decodePKCS1(bPrivateKey2);
privateKey2 = keyFactory2.generatePrivate(privateKeySpec);
cipher.init(Cipher.DECRYPT_MODE, privateKey2);
byte[] bPlain2 = cipher.doFinal('해석할데이터를 집어 넣어주면 됩니다. ');
String sPlain2 = new String(bPlain2);


Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

RSA/ECB/PKCS1Padding" 을 하지 않으면


위처럼 쓰레기 패딩 데이터가 붙습니다,


Comments